diff --git a/PROMS/AdjustBuildRevision/Program.cs b/PROMS/AdjustBuildRevision/Program.cs index 773f3aaf..b2a41b3c 100644 --- a/PROMS/AdjustBuildRevision/Program.cs +++ b/PROMS/AdjustBuildRevision/Program.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; @@ -35,31 +33,7 @@ namespace AdjustBuildRevision outline = Regex.Replace(line, @"([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)""\)", DateTime.Now.ToString("2.4.yyMM.dHH") + "\")"); else outline = Regex.Replace(line, @"([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)""\)", DateTime.Now.ToString("2.3.yyMM.dHH") + "\")"); - // if (outline != line) - // { - // Console.WriteLine("Before: '{0}'", line); - // Console.WriteLine("After: '{0}'", outline); - // lines[i] = outline; - // changed = true; - // } - // else - // { - // Console.WriteLine("No change: '{0}'", line); - // } - // } - //} - //if (changed) - //{ - // if (!fi.IsReadOnly) fi.IsReadOnly = false; - // StreamWriter sw = fi.CreateText(); - // foreach (string line in lines) - // sw.WriteLine(line); - // sw.Close(); - // string line = lines[i]; - // string outline = line; - // if (line.Contains("AssemblyVersion") || line.Contains("AssemblyFileVersion")) - // { - //outline = Regex.Replace(line, @"([0-9]*)\.([0-9]*)\.([0-9]*)\.([0-9]*)""\)", DateTime.Now.ToString("1.1.yyMM.dHH") + "\")"); + if (outline != line) { Console.WriteLine("Before: '{0}'", line); @@ -84,7 +58,7 @@ namespace AdjustBuildRevision } else { - MessageBox.Show("File " + fi.FullName + " does not exist"); + MessageBox.Show($"File {fi.FullName} does not exist"); } } catch (Exception ex) @@ -93,10 +67,6 @@ namespace AdjustBuildRevision } } - //private static DateTime GetLatestDateTime(string path) - //{ - // return GetLatestDateTime(new DirectoryInfo(path)); - //} private static DateTime GetLatestDateTime(DirectoryInfo di, DateTime dtCheck) { DateTime dtMax = dtCheck; @@ -104,24 +74,14 @@ namespace AdjustBuildRevision foreach(FileInfo myFile in myFiles) { DateTime dt = myFile.LastWriteTime; - //if (dt > dtCheck) - //{ - //Console.WriteLine("\"File\"\t\"{0}\"\t\"{1}\"\t{2}\t{3}",myFile.FullName,dt.ToString("1.1.yyMM.dHH"),dt,dtCheck); - if(dtMax < dt) dtMax = dt; - //} + if(dtMax < dt) dtMax = dt; } DirectoryInfo[] myFolders = di.GetDirectories(); foreach (DirectoryInfo diChild in myFolders) { DateTime dtChild = GetLatestDateTime(diChild,dtCheck); - //if (dtChild > dtCheck) - //{ - //Console.WriteLine("\"SubFolder\"\t\"{0}\"\t\"{1}\"\t{2}\t{3}", diChild.FullName, dtChild.ToString("1.1.yyMM.dHH"),dtChild,dtCheck); - if(dtChild > dtMax) dtMax = dtChild; - //} + if(dtChild > dtMax) dtMax = dtChild; } - //if(dtMax > dtCheck) - // Console.WriteLine("\"Folder\"\t\"{0}\"\t\"{1}\"", di.FullName, dtMax.ToString("1.1.yyMM.dHH")); return dtMax; } } diff --git a/PROMS/DropDownPanel/Controls/DropDownPanel.cs b/PROMS/DropDownPanel/Controls/DropDownPanel.cs index 49646260..660c8f85 100644 --- a/PROMS/DropDownPanel/Controls/DropDownPanel.cs +++ b/PROMS/DropDownPanel/Controls/DropDownPanel.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel; -using System.Diagnostics; using System.Drawing; using System.Windows.Forms; @@ -15,7 +14,7 @@ namespace AT.STO.UI.Win { #region Private Variable Declarations private IDropDownAware _dropDownControl = null; - private DropDownWindowHelper _dropDownHelper = null; + private readonly DropDownWindowHelper _dropDownHelper = null; private Form _owner = null; #endregion #region Constructor / Destructor @@ -47,7 +46,7 @@ namespace AT.STO.UI.Win /// protected override void OnHandleCreated(EventArgs e) { - _owner = this.FindForm(); + _owner = FindForm(); _dropDownHelper.ReleaseHandle(); if (_owner != null) @@ -66,8 +65,8 @@ namespace AT.STO.UI.Win { base.OnResize(e); combo.Location = new Point(0, 0); - combo.Width = this.ClientRectangle.Width; - this.Height = combo.Height; + combo.Width = ClientRectangle.Width; + Height = combo.Height; } #endregion #region Event Handler @@ -96,7 +95,7 @@ namespace AT.STO.UI.Win else { _dropDownHelper.CloseDropDown(); - this.Focus(); + Focus(); } } @@ -115,7 +114,7 @@ namespace AT.STO.UI.Win private void DropDownHelper_DropDownCancel(object sender, DropDownCancelEventArgs e) { - if (this.Bounds.Contains(Parent.PointToClient(e.CursorLocation))) + if (Bounds.Contains(Parent.PointToClient(e.CursorLocation))) { e.Cancel = true; } @@ -137,31 +136,22 @@ namespace AT.STO.UI.Win { SetValue(e.Value as ILookupItem); } - - if (this.FinishEditing != null) - { - this.FinishEditing(this, e); - } - - _dropDownControl.FinishEditing -= new DropDownValueChangedEventHandler(DropDown_FinishEditing); + + FinishEditing?.Invoke(this, e); + + _dropDownControl.FinishEditing -= new DropDownValueChangedEventHandler(DropDown_FinishEditing); _dropDownControl.ValueChanged -= new DropDownValueChangedEventHandler(DropDown_ValueChanged); _dropDownHelper.CloseDropDown(); } - - private void DropDown_ValueChanged(object sender, DropDownValueChangedEventArgs e) - { - if (this.ValueChanged != null) - { - this.ValueChanged(this, e); - } - } - #endregion - #region Public Properties - /// - /// Get or set the control (has to implement IDropDownAware) that is to - /// be displayed as the dropdown portion of the combobox. - /// - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + + private void DropDown_ValueChanged(object sender, DropDownValueChangedEventArgs e) => ValueChanged?.Invoke(this, e); + #endregion + #region Public Properties + /// + /// Get or set the control (has to implement IDropDownAware) that is to + /// be displayed as the dropdown portion of the combobox. + /// + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IDropDownAware DropDownControl { get { return _dropDownControl; } @@ -169,24 +159,21 @@ namespace AT.STO.UI.Win { _dropDownControl = value; - this.Controls.Add(_dropDownControl as Control); + Controls.Add(_dropDownControl as Control); } } - #endregion - #region Public Methods - public override string ToString() - { - return this.Name; - } - #endregion - #region Private Methods - /// - /// Calculate an acceptable position of the DropDownForm even in a - /// multi screen environment. - /// - /// - /// - private Point GetDropDownPosition(DropDownForm DropDown) + #endregion + #region Public Methods + public override string ToString() => Name; + #endregion + #region Private Methods + /// + /// Calculate an acceptable position of the DropDownForm even in a + /// multi screen environment. + /// + /// + /// + private Point GetDropDownPosition(DropDownForm DropDown) { Point lt = Parent.PointToScreen(new Point(Left, Top)); Point rb = Parent.PointToScreen(new Point(Right, Bottom)); diff --git a/PROMS/DropDownPanel/Events/Events.cs b/PROMS/DropDownPanel/Events/Events.cs index e5659774..3abc20ee 100644 --- a/PROMS/DropDownPanel/Events/Events.cs +++ b/PROMS/DropDownPanel/Events/Events.cs @@ -35,10 +35,9 @@ namespace AT.STO.UI.Win /// public class DropDownCancelEventArgs : EventArgs { - #region Private Variable Declarations - private bool _cancel = false; - private Point _cursorLocation; - private Form _dropDown = null; + #region Private Variable Declarations + private Point _cursorLocation; + private readonly Form _dropDown = null; #endregion #region Constructor / Destructor /// @@ -51,36 +50,26 @@ namespace AT.STO.UI.Win { _dropDown = DropDown; _cursorLocation = CursorLocation; - _cancel = false; - } - #endregion - #region Public Properties - /// - /// - /// - public bool Cancel - { - get { return _cancel; } - set { _cancel = value; } + Cancel = false; } + #endregion + #region Public Properties + /// + /// + /// + public bool Cancel { get; set; } = false; - /// - /// - /// - public Point CursorLocation - { - get { return _cursorLocation; } - } + /// + /// + /// + public Point CursorLocation => _cursorLocation; - /// - /// - /// - public Form DropDown - { - get { return _dropDown; } - } - #endregion - } + /// + /// + /// + public Form DropDown => _dropDown; + #endregion + } /// /// Contains event information for a event. @@ -91,64 +80,50 @@ namespace AT.STO.UI.Win public class DropDownClosedEventArgs : EventArgs { #region Private Variable Declarations - private Form _dropDown = null; - #endregion - #region Constructor / Destructor - /// - /// Constructs a new instance of this class for the specified - /// popup form. - /// - /// DropDown Form which is being closed. - public DropDownClosedEventArgs(Form DropDown) - { - _dropDown = DropDown; - } - #endregion - #region Public Properties - /// - /// Gets the dropdown form which is being closed. - /// - public Form DropDown - { - get { return _dropDown; } - } - #endregion - } + private readonly Form _dropDown = null; + #endregion + #region Constructor / Destructor + /// + /// Constructs a new instance of this class for the specified + /// popup form. + /// + /// DropDown Form which is being closed. + public DropDownClosedEventArgs(Form DropDown) => _dropDown = DropDown; + #endregion + #region Public Properties + /// + /// Gets the dropdown form which is being closed. + /// + public Form DropDown => _dropDown; + #endregion + } /// /// Contains event information for DropDownValueChangedEventHandler. /// public class DropDownValueChangedEventArgs : EventArgs { - #region Private Variable Declarations - private object _value = null; - #endregion - #region Constructor / Destructor - /// - /// Default Constructor - /// - public DropDownValueChangedEventArgs() + #region Private Variable Declarations + #endregion + #region Constructor / Destructor + /// + /// Default Constructor + /// + public DropDownValueChangedEventArgs() { } - - /// - /// Initialization with the control's value. - /// - /// - public DropDownValueChangedEventArgs(object Value) - { - _value = Value; - } - #endregion - #region Public Properties - /// - /// Gets or sets the control's value. - /// - public object Value - { - get { return _value; } - set { _value = value; } - } - #endregion - } + + /// + /// Initialization with the control's value. + /// + /// + public DropDownValueChangedEventArgs(object Value) => this.Value = Value; + #endregion + #region Public Properties + /// + /// Gets or sets the control's value. + /// + public object Value { get; set; } = null; + #endregion + } } diff --git a/PROMS/DropDownPanel/Forms/DropDownForm.cs b/PROMS/DropDownPanel/Forms/DropDownForm.cs index c6923a15..4916bf2f 100644 --- a/PROMS/DropDownPanel/Forms/DropDownForm.cs +++ b/PROMS/DropDownPanel/Forms/DropDownForm.cs @@ -13,22 +13,19 @@ namespace AT.STO.UI.Win internal partial class DropDownForm : Form, IDropDownAware { #region Private Variable Declaration - private IDropDownAware _control = null; - #endregion - #region Constructor / Destructor - /// - /// Default Constructor - /// - public DropDownForm() - { - InitializeComponent(); - } + private readonly IDropDownAware _control = null; + #endregion + #region Constructor / Destructor + /// + /// Default Constructor + /// + public DropDownForm() => InitializeComponent(); - /// - /// Constructor to initialize the for with the control to display. - /// - /// The control to display. - public DropDownForm(IDropDownAware Ctrl) : this() + /// + /// Constructor to initialize the for with the control to display. + /// + /// The control to display. + public DropDownForm(IDropDownAware Ctrl) : this() { if (Ctrl != null) { @@ -41,7 +38,7 @@ namespace AT.STO.UI.Win #region Form Events protected override void OnClosing(CancelEventArgs e) { - this.Controls.Remove(_control as Control); + Controls.Remove(_control as Control); base.OnClosing(e); } @@ -58,29 +55,20 @@ namespace AT.STO.UI.Win #region Event Handler private void Ctrl_FinishEditing(object sender, DropDownValueChangedEventArgs e) { - if (this.FinishEditing != null) - { - this.FinishEditing(this, e); - } + FinishEditing?.Invoke(this, e); - _control.FinishEditing -= new DropDownValueChangedEventHandler(Ctrl_FinishEditing); + _control.FinishEditing -= new DropDownValueChangedEventHandler(Ctrl_FinishEditing); _control.ValueChanged -= new DropDownValueChangedEventHandler(Ctrl_ValueChanged); } - - private void Ctrl_ValueChanged(object sender, DropDownValueChangedEventArgs e) - { - if (this.ValueChanged != null) - { - this.ValueChanged(this, e); - } - } - #endregion - #region IDropDownAware Implementation - /// - /// Fired either on OK, Cancel or a click outside the control to indicate - /// that the user has finished editing. - /// - public event DropDownValueChangedEventHandler FinishEditing; + + private void Ctrl_ValueChanged(object sender, DropDownValueChangedEventArgs e) => ValueChanged?.Invoke(this, e); + #endregion + #region IDropDownAware Implementation + /// + /// Fired either on OK, Cancel or a click outside the control to indicate + /// that the user has finished editing. + /// + public event DropDownValueChangedEventHandler FinishEditing; /// /// Fired on any change of the controls's value during the editing process. @@ -100,15 +88,15 @@ namespace AT.STO.UI.Win private void InitializeControl(Control Ctrl) { Size size = Ctrl.Size; - Size inner = this.ClientRectangle.Size; - Size outer = this.Size; + Size inner = ClientRectangle.Size; + Size outer = Size; int gap = outer.Width - inner.Width; size.Width += gap; size.Height += gap; - this.Size = size; - this.Controls.Add(Ctrl); + Size = size; + Controls.Add(Ctrl); Ctrl.Location = new Point(0, 0); Ctrl.Visible = true; Ctrl.Invalidate(); diff --git a/PROMS/DropDownPanel/Helper/DropDownMessageFilter.cs b/PROMS/DropDownPanel/Helper/DropDownMessageFilter.cs index cca60462..d0ad764d 100644 --- a/PROMS/DropDownPanel/Helper/DropDownMessageFilter.cs +++ b/PROMS/DropDownPanel/Helper/DropDownMessageFilter.cs @@ -1,4 +1,3 @@ -using System; using System.Drawing; using System.Windows.Forms; @@ -21,59 +20,48 @@ namespace AT.STO.UI.Win private const int WM_NCLBUTTONDOWN = 0x0A1; private const int WM_NCRBUTTONDOWN = 0x0A4; private const int WM_NCMBUTTONDOWN = 0x0A7; - #endregion - #region Private Variable Declarations - private Form _dropDown = null; - private DropDownWindowHelper _owner = null; + #endregion + #region Private Variable Declarations + private readonly DropDownWindowHelper _owner = null; #endregion #region Event Declarations public event DropDownCancelEventHandler DropDownCancel; - #endregion - #region Constructor / Destructor - /// - /// Constructs a new instance of this class and sets the owning - /// object. - /// - /// The object - /// which owns this class. - public DropDownMessageFilter(DropDownWindowHelper Owner) - { - _owner = Owner; - } - #endregion - #region Public Properties - /// - /// Gets/sets the dropdown form which is being displayed. - /// - public Form DropDown - { - get { return _dropDown; } - set { _dropDown = value; } - } - #endregion - #region Private Methods - private void OnMouseDown() + #endregion + #region Constructor / Destructor + /// + /// Constructs a new instance of this class and sets the owning + /// object. + /// + /// The object + /// which owns this class. + public DropDownMessageFilter(DropDownWindowHelper Owner) => _owner = Owner; + #endregion + #region Public Properties + /// + /// Gets/sets the dropdown form which is being displayed. + /// + public Form DropDown { get; set; } = null; + #endregion + #region Private Methods + private void OnMouseDown() { Point cursorPos = Cursor.Position; // Get the cursor location - if (!_dropDown.Bounds.Contains(cursorPos)) // Check if it is within the popup form + if (!DropDown.Bounds.Contains(cursorPos)) // Check if it is within the popup form { - OnDropDownCancel(new DropDownCancelEventArgs(_dropDown, cursorPos)); // If not, then call to see if it should be closed + OnDropDownCancel(new DropDownCancelEventArgs(DropDown, cursorPos)); // If not, then call to see if it should be closed } } #endregion #region DropDownCancelEvent Implementation protected virtual void OnDropDownCancel(DropDownCancelEventArgs e) { - if (this.DropDownCancel != null) - { - this.DropDownCancel(this, e); - } + DropDownCancel?.Invoke(this, e); - if (!e.Cancel) + if (!e.Cancel) { _owner.CloseDropDown(); - _dropDown = null; // Clear reference for GC + DropDown = null; // Clear reference for GC } } #endregion @@ -90,7 +78,7 @@ namespace AT.STO.UI.Win /// This implementation always returns false. public bool PreFilterMessage(ref Message m) { - if (_dropDown != null) + if (DropDown != null) { switch (m.Msg) { diff --git a/PROMS/DropDownPanel/Helper/DropDownWindowHelper.cs b/PROMS/DropDownPanel/Helper/DropDownWindowHelper.cs index e3eb0308..2f291045 100644 --- a/PROMS/DropDownPanel/Helper/DropDownWindowHelper.cs +++ b/PROMS/DropDownPanel/Helper/DropDownWindowHelper.cs @@ -1,6 +1,5 @@ using System; using System.Drawing; -using System.Runtime.InteropServices; using System.Windows.Forms; namespace AT.STO.UI.Win @@ -22,7 +21,7 @@ namespace AT.STO.UI.Win private Form _dropDown = null; private bool _dropDownShowing = false; - private DropDownMessageFilter _filter = null; + private readonly DropDownMessageFilter _filter = null; private Form _owner = null; private bool _skipClose = false; #endregion @@ -42,31 +41,25 @@ namespace AT.STO.UI.Win _filter.DropDownCancel -= new DropDownCancelEventHandler(Popup_Cancel); _filter.DropDownCancel += new DropDownCancelEventHandler(Popup_Cancel); } - #endregion - #region Event Handler - private void Popup_Cancel(object sender, DropDownCancelEventArgs e) - { - OnDropDownCancel(e); - } + #endregion + #region Event Handler + private void Popup_Cancel(object sender, DropDownCancelEventArgs e) => OnDropDownCancel(e); - /// - /// Responds to the - /// event from the popup form. - /// - /// Popup form that has been closed. - /// Not used. - private void Popup_Closed(object sender, EventArgs e) - { - CloseDropDown(); - } - - /// - /// Subclasses the owning form's existing Window Procedure to enables the - /// title bar to remain active when a popup is show, and to detect if - /// the user clicks onto another application whilst the popup is visible. - /// - /// Window Procedure Message - protected override void WndProc(ref Message m) + /// + /// Responds to the + /// event from the popup form. + /// + /// Popup form that has been closed. + /// Not used. + private void Popup_Closed(object sender, EventArgs e) => CloseDropDown(); + + /// + /// Subclasses the owning form's existing Window Procedure to enables the + /// title bar to remain active when a popup is show, and to detect if + /// the user clicks onto another application whilst the popup is visible. + /// + /// Window Procedure Message + protected override void WndProc(ref Message m) { base.WndProc(ref m); @@ -76,7 +69,7 @@ namespace AT.STO.UI.Win { if (((int)m.WParam) == 0) // Check if the title bar will made inactive: { // Note it's no good to try and consume this message; if you try to do that you'll end up with windows - UIApiCalls.SendMessage(this.Handle, UIApiCalls.WM_NCACTIVATE, 1, IntPtr.Zero); // If so reactivate it. + UIApiCalls.SendMessage(Handle, UIApiCalls.WM_NCACTIVATE, 1, IntPtr.Zero); // If so reactivate it. } } else if (m.Msg == UIApiCalls.WM_ACTIVATEAPP) @@ -84,7 +77,7 @@ namespace AT.STO.UI.Win if ((int)m.WParam == 0) // Check if the application is being deactivated. { CloseDropDown(); // It is so cancel the popup: - UIApiCalls.PostMessage(this.Handle, UIApiCalls.WM_NCACTIVATE, 0, IntPtr.Zero); // And put the title bar into the inactive state: + UIApiCalls.PostMessage(Handle, UIApiCalls.WM_NCACTIVATE, 0, IntPtr.Zero); // And put the title bar into the inactive state: } } } @@ -168,22 +161,19 @@ namespace AT.STO.UI.Win _owner = null; } } - #endregion - #region Public Properties - /// - /// Indicator weither the DropDown is showing. - /// - public bool DropDownShowing + #endregion + #region Public Properties + /// + /// Indicator weither the DropDown is showing. + /// + public bool DropDownShowing => _dropDownShowing; + #endregion + #region Event Implementation + protected virtual void OnDropDownCancel(DropDownCancelEventArgs e) { - get { return _dropDownShowing; } - } - #endregion - #region Event Implementation - protected virtual void OnDropDownCancel(DropDownCancelEventArgs e) - { - if (this.DropDownCancel != null) + if (DropDownCancel != null) { - this.DropDownCancel(this, e); + DropDownCancel(this, e); if (!e.Cancel) { @@ -191,14 +181,8 @@ namespace AT.STO.UI.Win } } } - - protected virtual void OnPDropDownClosed(DropDownClosedEventArgs e) - { - if (this.DropDownClosed != null) - { - this.DropDownClosed(this, e); - } - } - #endregion - } + + protected virtual void OnPDropDownClosed(DropDownClosedEventArgs e) => DropDownClosed?.Invoke(this, e); + #endregion + } } diff --git a/PROMS/DropDownPanel/Interfaces/IDropDownAware.cs b/PROMS/DropDownPanel/Interfaces/IDropDownAware.cs index 94874f2b..b5dd43ab 100644 --- a/PROMS/DropDownPanel/Interfaces/IDropDownAware.cs +++ b/PROMS/DropDownPanel/Interfaces/IDropDownAware.cs @@ -1,5 +1,3 @@ -using System; - namespace AT.STO.UI.Win { /// diff --git a/PROMS/DropDownPanel/Interfaces/ILookupItem.cs b/PROMS/DropDownPanel/Interfaces/ILookupItem.cs index b3181e2a..7470b14a 100644 --- a/PROMS/DropDownPanel/Interfaces/ILookupItem.cs +++ b/PROMS/DropDownPanel/Interfaces/ILookupItem.cs @@ -1,5 +1,3 @@ -using System; - namespace AT.STO.UI.Win { public interface ILookupItem where T: struct diff --git a/PROMS/FlexableMessageBox/FlexibleMessageBox.cs b/PROMS/FlexableMessageBox/FlexibleMessageBox.cs index 535b983a..1eb8b401 100644 --- a/PROMS/FlexableMessageBox/FlexibleMessageBox.cs +++ b/PROMS/FlexableMessageBox/FlexibleMessageBox.cs @@ -1,8 +1,6 @@ using System; using System.Diagnostics; using System.Drawing; -using System.Globalization; -//using System.Linq; using System.Windows.Forms; @@ -121,10 +119,7 @@ namespace JR.Utils.GUI.Forms /// /// The text. /// The dialog result. - public static DialogResult Show(string text) - { - return FlexibleMessageBoxForm.Show(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(string text) => FlexibleMessageBoxForm.Show(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -132,10 +127,7 @@ namespace JR.Utils.GUI.Forms /// The owner. /// The text. /// The dialog result. - public static DialogResult Show(IWin32Window owner, string text) - { - return FlexibleMessageBoxForm.Show(owner, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(IWin32Window owner, string text) => FlexibleMessageBoxForm.Show(owner, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -143,10 +135,7 @@ namespace JR.Utils.GUI.Forms /// The text. /// The caption. /// The dialog result. - public static DialogResult Show(string text, string caption) - { - return FlexibleMessageBoxForm.Show(null, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(string text, string caption) => FlexibleMessageBoxForm.Show(null, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -155,10 +144,7 @@ namespace JR.Utils.GUI.Forms /// The text. /// The caption. /// The dialog result. - public static DialogResult Show(IWin32Window owner, string text, string caption) - { - return FlexibleMessageBoxForm.Show(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(IWin32Window owner, string text, string caption) => FlexibleMessageBoxForm.Show(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -167,10 +153,7 @@ namespace JR.Utils.GUI.Forms /// The caption. /// The buttons. /// The dialog result. - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) - { - return FlexibleMessageBoxForm.Show(null, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) => FlexibleMessageBoxForm.Show(null, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -180,10 +163,7 @@ namespace JR.Utils.GUI.Forms /// The caption. /// The buttons. /// The dialog result. - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) - { - return FlexibleMessageBoxForm.Show(owner, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) => FlexibleMessageBoxForm.Show(owner, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -193,10 +173,7 @@ namespace JR.Utils.GUI.Forms /// The buttons. /// The icon. /// - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) - { - return FlexibleMessageBoxForm.Show(null, text, caption, buttons, icon, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) => FlexibleMessageBoxForm.Show(null, text, caption, buttons, icon, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -207,10 +184,7 @@ namespace JR.Utils.GUI.Forms /// The buttons. /// The icon. /// The dialog result. - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) - { - return FlexibleMessageBoxForm.Show(owner, text, caption, buttons, icon, MessageBoxDefaultButton.Button1); - } + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) => FlexibleMessageBoxForm.Show(owner, text, caption, buttons, icon, MessageBoxDefaultButton.Button1); /// /// Shows the specified message box. @@ -221,10 +195,7 @@ namespace JR.Utils.GUI.Forms /// The icon. /// The default button. /// The dialog result. - public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) - { - return FlexibleMessageBoxForm.Show(null, text, caption, buttons, icon, defaultButton); - } + public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) => FlexibleMessageBoxForm.Show(null, text, caption, buttons, icon, defaultButton); /// /// Shows the specified message box. @@ -236,10 +207,7 @@ namespace JR.Utils.GUI.Forms /// The icon. /// The default button. /// The dialog result. - public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) - { - return FlexibleMessageBoxForm.Show(owner, text, caption, buttons, icon, defaultButton); - } + public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) => FlexibleMessageBoxForm.Show(owner, text, caption, buttons, icon, defaultButton); /// /// Shows the specified message box. @@ -251,10 +219,8 @@ namespace JR.Utils.GUI.Forms /// The icon. /// The default button. /// The dialog result. - public static DialogResult ShowCustom(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) - { - return FlexibleMessageBoxForm.ShowCustom(null, text, caption, buttons, icon); - } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping owner for legacy reasons")] + public static DialogResult ShowCustom(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) => FlexibleMessageBoxForm.ShowCustom(null, text, caption, buttons, icon); #endregion @@ -341,7 +307,7 @@ namespace JR.Utils.GUI.Forms this.richTextBoxMessage.TabIndex = 0; this.richTextBoxMessage.TabStop = false; this.richTextBoxMessage.Text = ""; - this.richTextBoxMessage.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBoxMessage_LinkClicked); + this.richTextBoxMessage.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.RichTextBoxMessage_LinkClicked); // // panel1 // @@ -431,8 +397,8 @@ namespace JR.Utils.GUI.Forms #region Private constants //These separators are used for the "copy to clipboard" standard operation, triggered by Ctrl + C (behavior and clipboard format is like in a standard MessageBox) - private static readonly String STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; - private static readonly String STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; + private static readonly string STANDARD_MESSAGEBOX_SEPARATOR_LINES = "---------------------------\n"; + private static readonly string STANDARD_MESSAGEBOX_SEPARATOR_SPACES = " "; //These are the possible buttons (in a standard MessageBox) private enum ButtonID { OK = 0, CANCEL, YES, NO, ABORT, RETRY, IGNORE, OVERWRITE, RENAME }; @@ -440,10 +406,10 @@ namespace JR.Utils.GUI.Forms //These are the buttons texts for different languages. //If you want to add a new language, add it here and in the GetButtonText-Function private enum TwoLetterISOLanguageID { en, de, es, it }; - private static readonly String[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore", "&Overwrite", "&Rename" }; //Note: This is also the fallback language - private static readonly String[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren", "&Overwrite", "&Rename" }; - private static readonly String[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar", "&Overwrite", "&Rename" }; - private static readonly String[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora", "&Overwrite", "&Rename" }; + private static readonly string[] BUTTON_TEXTS_ENGLISH_EN = { "OK", "Cancel", "&Yes", "&No", "&Abort", "&Retry", "&Ignore", "&Overwrite", "&Rename" }; //Note: This is also the fallback language + private static readonly string[] BUTTON_TEXTS_GERMAN_DE = { "OK", "Abbrechen", "&Ja", "&Nein", "&Abbrechen", "&Wiederholen", "&Ignorieren", "&Overwrite", "&Rename" }; + private static readonly string[] BUTTON_TEXTS_SPANISH_ES = { "Aceptar", "Cancelar", "&Sí", "&No", "&Abortar", "&Reintentar", "&Ignorar", "&Overwrite", "&Rename" }; + private static readonly string[] BUTTON_TEXTS_ITALIAN_IT = { "OK", "Annulla", "&Sì", "&No", "&Interrompi", "&Riprova", "&Ignora", "&Overwrite", "&Rename" }; #endregion @@ -451,7 +417,7 @@ namespace JR.Utils.GUI.Forms private MessageBoxDefaultButton defaultButton; private int visibleButtonsCount; - private TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; + private readonly TwoLetterISOLanguageID languageID = TwoLetterISOLanguageID.en; #endregion @@ -758,9 +724,9 @@ namespace JR.Utils.GUI.Forms /// The instance containing the event data. private void FlexibleMessageBoxForm_Shown(object sender, EventArgs e) { - int buttonIndexToFocus = 1; Button buttonToFocus; + int buttonIndexToFocus; //Set the default button... switch (this.defaultButton) { @@ -799,7 +765,7 @@ namespace JR.Utils.GUI.Forms /// /// The source of the event. /// The instance containing the event data. - private void richTextBoxMessage_LinkClicked(object sender, LinkClickedEventArgs e) + private void RichTextBoxMessage_LinkClicked(object sender, LinkClickedEventArgs e) { try { @@ -877,12 +843,14 @@ namespace JR.Utils.GUI.Forms public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { //Create a new instance of the FlexibleMessageBox form - var flexibleMessageBoxForm = new FlexibleMessageBoxForm(); - flexibleMessageBoxForm.ShowInTaskbar = false; + var flexibleMessageBoxForm = new FlexibleMessageBoxForm + { + ShowInTaskbar = false, - //Bind the caption and the message text - flexibleMessageBoxForm.CaptionText = caption; - flexibleMessageBoxForm.MessageText = text; + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; flexibleMessageBoxForm.FlexibleMessageBoxFormBindingSource.DataSource = flexibleMessageBoxForm; //Set the buttons visibilities and texts. Also set a default button. @@ -914,15 +882,18 @@ namespace JR.Utils.GUI.Forms /// The icon. /// The default button. /// The dialog result. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping buttons for legacy reasons")] public static DialogResult ShowCustom(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { //Create a new instance of the FlexibleMessageBox form - var flexibleMessageBoxForm = new FlexibleMessageBoxForm(); - flexibleMessageBoxForm.ShowInTaskbar = false; + var flexibleMessageBoxForm = new FlexibleMessageBoxForm + { + ShowInTaskbar = false, - //Bind the caption and the message text - flexibleMessageBoxForm.CaptionText = caption; - flexibleMessageBoxForm.MessageText = text; + //Bind the caption and the message text + CaptionText = caption, + MessageText = text + }; flexibleMessageBoxForm.FlexibleMessageBoxFormBindingSource.DataSource = flexibleMessageBoxForm; //Set the buttons visibilities and texts. Also set a default button. diff --git a/PROMS/Formats/Formats.csproj b/PROMS/Formats/Formats.csproj index c73a80c5..63e75909 100644 --- a/PROMS/Formats/Formats.csproj +++ b/PROMS/Formats/Formats.csproj @@ -66,6 +66,7 @@ frmFormatCopy.cs + diff --git a/PROMS/Formats/GlobalSuppressions.cs b/PROMS/Formats/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/Formats/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/Formats/Program.cs b/PROMS/Formats/Program.cs index ecbbfc91..59ba4f28 100644 --- a/PROMS/Formats/Program.cs +++ b/PROMS/Formats/Program.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Windows.Forms; namespace Formats diff --git a/PROMS/Formats/frmFormatCopy.cs b/PROMS/Formats/frmFormatCopy.cs index be941c3e..e5f3d7fe 100644 --- a/PROMS/Formats/frmFormatCopy.cs +++ b/PROMS/Formats/frmFormatCopy.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.IO; using System.Windows.Forms; @@ -28,7 +23,7 @@ namespace Formats txbxPROMSFormatsPath.Text = savedFormatPath; else { - string curFolder = Environment.CurrentDirectory; // C:\development/PROMS/Formats/bin/debug + string curFolder = Environment.CurrentDirectory; // .../PROMS/Formats/bin/debug int idx = curFolder.ToUpper().IndexOf(@"\PROMS\"); txbxPROMSFormatsPath.Text = curFolder.Substring(0, idx); } @@ -40,9 +35,8 @@ namespace Formats DirectoryInfo di = new DirectoryInfo(path); if (di.Exists == false) //return; { - DialogResult dlgrslt = DialogResult.No; - dlgrslt = MessageBox.Show(string.Format("{0} does not exist. Create it?", path), "Create Folder?", MessageBoxButtons.YesNo); - if (dlgrslt == DialogResult.Yes) + DialogResult dlgrslt = MessageBox.Show(string.Format("{0} does not exist. Create it?", path), "Create Folder?", MessageBoxButtons.YesNo); + if (dlgrslt == DialogResult.Yes) { di.Create(); di.CreateSubdirectory("fmtall"); @@ -86,10 +80,11 @@ namespace Formats private void btnBrowse_Click(object sender, EventArgs e) { - FolderBrowserDialog fbd = new FolderBrowserDialog(); - - fbd.SelectedPath = txbxPROMSFormatsPath.Text; - if (fbd.ShowDialog() == DialogResult.OK) + FolderBrowserDialog fbd = new FolderBrowserDialog + { + SelectedPath = txbxPROMSFormatsPath.Text + }; + if (fbd.ShowDialog() == DialogResult.OK) { if (Directory.Exists(fbd.SelectedPath)) txbxPROMSFormatsPath.Text = fbd.SelectedPath + @"\"; } @@ -116,9 +111,9 @@ namespace Formats if (!txbxPROMSFormatsPath.Text.EndsWith(@"\")) txbxPROMSFormatsPath.Text += @"\"; // There should be a "fmtall" and "genmacall" folder in the delelopment project folder - // ex: C:\development\PROMS\Formats\fmtall and C:\development\PROMS\Formats\genmacall - string destFmtallPath = txbxPROMSFormatsPath.Text + @"fmtall\"; - string destGenmacallPath = txbxPROMSFormatsPath.Text + @"genmacall\"; + // ex: ...\PROMS\Formats\fmtall and ...\PROMS\Formats\genmacall + string destFmtallPath = $@"{txbxPROMSFormatsPath.Text}fmtall\"; + string destGenmacallPath = $@"{txbxPROMSFormatsPath.Text}genmacall\"; string srcFmtallPath = @"..\..\"; // up to levels from startup path // clear the destination fmtall and genmacall folders @@ -156,14 +151,10 @@ namespace Formats } Properties.Settings.Default.FormatPath = txbxPROMSFormatsPath.Text.Substring(0,txbxPROMSFormatsPath.Text.Length-1); // save the copy format path minus the ending backslash Properties.Settings.Default.Save(); - //if(MessageBox.Show("Do you want to end the Format Copier?","Formats Copied.", MessageBoxButtons.YesNo, MessageBoxIcon.Question)== DialogResult.Yes) - Application.Exit(); - } - - private void buttonX2_Click(object sender, EventArgs e) - { Application.Exit(); } - } + private void buttonX2_Click(object sender, EventArgs e) => Application.Exit(); + + } } \ No newline at end of file diff --git a/PROMS/LBWordLibrary/GlobalSuppressions.cs b/PROMS/LBWordLibrary/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/LBWordLibrary/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/LBWordLibrary/LBComObject.cs b/PROMS/LBWordLibrary/LBComObject.cs index 8bc36189..e73e8dd0 100644 --- a/PROMS/LBWordLibrary/LBComObject.cs +++ b/PROMS/LBWordLibrary/LBComObject.cs @@ -1,64 +1,46 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Reflection; +using System.Windows.Forms.VisualStyles; namespace LBWordLibrary { public abstract partial class LBComObject { - private Object _Item; - internal Object Item + private object _Item; + internal object Item { get { return _Item; } set { _Item = value; - if (value != null) _MyType = _Item.GetType(); + if (value != null) MyType = _Item.GetType(); } } - private Type _MyType; - public Type MyType - { - get { return _MyType; } - set { _MyType = value; } - } - protected LBComObject() { } + + public Type MyType { get; set; } + protected LBComObject() { } protected LBComObject(string ProgID) { Type objClassType; objClassType = Type.GetTypeFromProgID(ProgID); Item = Activator.CreateInstance(objClassType); } - protected LBComObject(Object item) - { - Item = item; - } - private Object DoInvokeMember(string name, Object[] parameters, BindingFlags bf, Binder b) + protected LBComObject(object item) => Item = item; + private object DoInvokeMember(string name, object[] parameters, BindingFlags bf, Binder b) { try { - return _MyType.InvokeMember(name, bf, b, _Item, parameters); + return MyType.InvokeMember(name, bf, b, _Item, parameters); } catch (Exception ex) { - throw new Exception(string.Format("LBComObject.DoInvokeMember {0}.{1}", _MyType.Name, name), ex); + throw new Exception(string.Format("LBComObject.DoInvokeMember {0}.{1}", MyType.Name, name), ex); } - return null; } - protected void SetProperty(string propertyName, params Object[] parameters) - { - DoInvokeMember(propertyName, parameters, BindingFlags.SetProperty, null); - } - protected Object GetProperty(string propertyName) - { - return DoInvokeMember(propertyName, null, BindingFlags.GetProperty, null); - } - protected Object GetProperty(string propertyName, params Object[] parameters) - { - return DoInvokeMember(propertyName, parameters, BindingFlags.GetProperty, null); - } - protected Object InvokeMethod(string methodName, params Object[] parameters) + protected void SetProperty(string propertyName, params object[] parameters) => DoInvokeMember(propertyName, parameters, BindingFlags.SetProperty, null); + protected object GetProperty(string propertyName) => DoInvokeMember(propertyName, null, BindingFlags.GetProperty, null); + protected object GetProperty(string propertyName, params object[] parameters) => DoInvokeMember(propertyName, parameters, BindingFlags.GetProperty, null); + protected object InvokeMethod(string methodName, params object[] parameters) { if (parameters != null) FixParameters(parameters); @@ -71,150 +53,79 @@ namespace LBWordLibrary if (parameters[i] is LBComObject) parameters[i] = (parameters[i] as LBComObject).Item; } - protected Object InvokeMethod(string methodName) - { - return InvokeMethod(methodName, null); - } - } + protected object InvokeMethod(string methodName) => InvokeMethod(methodName, null); + } public class LBComObjectList : LBComObject where TList : LBComObjectList where TItem : LBComObject, new() { - //public new(Object item):base(item){} public TItem Add() { - TItem tmp = new TItem(); - tmp.Item = InvokeMethod("Add"); - return tmp; + TItem tmp = new TItem + { + Item = InvokeMethod("Add") + }; + return tmp; } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - // Get each item in a collection - public Object this[int item] - { - get - { - return InvokeMethod("Item", item);// Use Item Method to get an entry from an object list - } - } - } + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + // Get each item in a collection + public object this[int item] => InvokeMethod("Item", item);// Use Item Method to get an entry from an object list + } public partial class LBApplicationClass : LBComObject { public LBApplicationClass() : base("Word.Application") { } - public LBApplicationClass(Object item) : base(item) { } - public Boolean Visible + public LBApplicationClass(object item) : base(item) { } + public bool Visible { - get { return (GetProperty("Visible") as Boolean? ?? false); } + get { return (GetProperty("Visible") as bool? ?? false); } set { SetProperty("Visible", value); } } - public LBDocuments Documents - { - get { return new LBDocuments(GetProperty("Documents")); } - } - public LBSelection Selection - { - get { return new LBSelection(GetProperty("Selection")); } - } - public LBDocumentClass ActiveDocument - { - get { return new LBDocumentClass(GetProperty("ActiveDocument")); } - } - public LBWindow ActiveWindow - { - get { return new LBWindow(GetProperty("ActiveWindow")); } - } - public String Version - { - get { return (GetProperty("Version").ToString()); } - } - public String ActivePrinter + public LBDocuments Documents => new LBDocuments(GetProperty("Documents")); + public LBSelection Selection => new LBSelection(GetProperty("Selection")); + public LBDocumentClass ActiveDocument => new LBDocumentClass(GetProperty("ActiveDocument")); + public LBWindow ActiveWindow => new LBWindow(GetProperty("ActiveWindow")); + public string Version => (GetProperty("Version").ToString()); + public string ActivePrinter { get { return (GetProperty("ActivePrinter").ToString()); } set { SetProperty("ActivePrinter", value); } } - public int BackgroundPrintingStatus - { - get { return (GetProperty("BackgroundPrintingStatus") as int? ?? 0); } - } - public LBWdWindowState WindowState + public int BackgroundPrintingStatus => (GetProperty("BackgroundPrintingStatus") as int? ?? 0); + public LBWdWindowState WindowState { get { return (LBWdWindowState)GetProperty("WindowState"); } set { SetProperty("WindowState", value); } } - public int BackgroundSavingStatus - { - get { return (GetProperty("BackgroundSavingStatus") as int? ?? 0); } - } - public void Quit() - { - InvokeMethod("Quit", Missing.Value, Missing.Value, Missing.Value); - } - public void Quit(object SaveChanges, object OriginalFormat, object RouteDocument) - { - InvokeMethod("Quit", SaveChanges, OriginalFormat, RouteDocument); - } - public void PrintOut() - { - InvokeMethod("PrintOut", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); - } - public void PrintOut(object Background, object Append, object Range, object OutputFileName, object From, object To, object Item, object Copies, object Pages, object PageType, object PrintToFile, object Collate, object FileName, object ActivePrinterMacGX, object ManualDuplexPrint, object PrintZoomColumn, object PrintZoomRow, object PrintZoomPaperWidth, object PrintZoomPaperHeight) - { - InvokeMethod("PrintOut", Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, FileName, ActivePrinterMacGX, ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight); - } - public void Activate() - { - InvokeMethod("Activate"); - } - } + public int BackgroundSavingStatus => (GetProperty("BackgroundSavingStatus") as int? ?? 0); + public void Quit() => InvokeMethod("Quit", Missing.Value, Missing.Value, Missing.Value); + public void Quit(object SaveChanges, object OriginalFormat, object RouteDocument) => InvokeMethod("Quit", SaveChanges, OriginalFormat, RouteDocument); + public void PrintOut() => InvokeMethod("PrintOut", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); + public void PrintOut(object Background, object Append, object Range, object OutputFileName, object From, object To, object Item, object Copies, object Pages, object PageType, object PrintToFile, object Collate, object FileName, object ActivePrinterMacGX, object ManualDuplexPrint, object PrintZoomColumn, object PrintZoomRow, object PrintZoomPaperWidth, object PrintZoomPaperHeight) => InvokeMethod("PrintOut", Background, Append, Range, OutputFileName, From, To, Item, Copies, Pages, PageType, PrintToFile, Collate, FileName, ActivePrinterMacGX, ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, PrintZoomPaperHeight); + public void Activate() => InvokeMethod("Activate"); + } public partial class LBDocuments : LBComObjectList /* Collection */ { - public LBDocuments(Object item) - { - Item = item; - } - public LBDocumentClass Open(object FileName) - { - return new LBDocumentClass(InvokeMethod("Open", FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); - } - public LBDocumentClass Open(object FileName, object ConfirmConversions, object ReadOnly, object AddToRecentFiles, object PasswordDocument, object PasswordTemplate, object Revert, object WritePasswordDocument, object WritePasswordTemplate, object Format, object Encoding, object Visible, object OpenAndRepair, object DocumentDirection, object NoEncodingDialog, object XMLTransform) - { - return new LBDocumentClass(InvokeMethod("Open", FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible, OpenAndRepair, DocumentDirection, NoEncodingDialog, XMLTransform)); - } - } + public LBDocuments(object item) => Item = item; + public LBDocumentClass Open(object FileName) => new LBDocumentClass(InvokeMethod("Open", FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); + public LBDocumentClass Open(object FileName, object ConfirmConversions, object ReadOnly, object AddToRecentFiles, object PasswordDocument, object PasswordTemplate, object Revert, object WritePasswordDocument, object WritePasswordTemplate, object Format, object Encoding, object Visible, object OpenAndRepair, object DocumentDirection, object NoEncodingDialog, object XMLTransform) => new LBDocumentClass(InvokeMethod("Open", FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible, OpenAndRepair, DocumentDirection, NoEncodingDialog, XMLTransform)); + } public partial class LBSelection : LBComObject { public LBSelection() { } - public LBSelection(Object item) : base(item) { } - public LBRange Range - { - get { return new LBRange(GetProperty("Range")); } - } - public LBStyle Style - { - get { return new LBStyle(GetProperty("Style")); } - } - public LBParagraphFormatClass ParagraphFormat - { - get { return new LBParagraphFormatClass(GetProperty("ParagraphFormat")); } - } - public String Text + public LBSelection(object item) : base(item) { } + public LBRange Range => new LBRange(GetProperty("Range")); + public LBStyle Style => new LBStyle(GetProperty("Style")); + public LBParagraphFormatClass ParagraphFormat => new LBParagraphFormatClass(GetProperty("ParagraphFormat")); + public string Text { //B2022-083: Support Conditional RO Values get { return Convert.ToString(GetProperty("Text")); } set { SetProperty("Text", value); } } - public LBWdSelectionType Type - { - get { return (LBWdSelectionType)GetProperty("Type"); } - } - public LBFind Find - { - get { return new LBFind(GetProperty("Find")); } - } - public LBFontClass Font - { - get { return new LBFontClass(GetProperty("Font")); } - } - public int End + public LBWdSelectionType Type => (LBWdSelectionType)GetProperty("Type"); + public LBFind Find => new LBFind(GetProperty("Find")); + public LBFontClass Font => new LBFontClass(GetProperty("Font")); + public int End { get { return (GetProperty("End") as int? ?? 0); } set { SetProperty("End", value); } @@ -224,15 +135,9 @@ namespace LBWordLibrary get { return (GetProperty("Start") as int? ?? 0); } set { SetProperty("Start", value); } } - public LBInlineShapes InlineShapes - { - get { return new LBInlineShapes(GetProperty("InlineShapes")); } - } - public LBParagraphs Paragraphs - { - get { return new LBParagraphs(GetProperty("Paragraphs")); } - } - public LBTables Tables + public LBInlineShapes InlineShapes => new LBInlineShapes(GetProperty("InlineShapes")); + public LBParagraphs Paragraphs => new LBParagraphs(GetProperty("Paragraphs")); + public LBTables Tables { // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content get @@ -262,227 +167,77 @@ namespace LBWordLibrary } } } - public LBRows Rows - { - get { return new LBRows(GetProperty("Rows")); } - } - public void WholeStory() - { - InvokeMethod("WholeStory"); - } - public int MoveStart() - { - return InvokeMethod("MoveStart", Missing.Value, Missing.Value) as int? ?? 0; - } - public int MoveStart(object Unit, object Count) - { - return InvokeMethod("MoveStart", Unit, Count) as int? ?? 0; - } - public int MoveEnd() - { - return InvokeMethod("MoveEnd", Missing.Value, Missing.Value) as int? ?? 0; - } - public int MoveEnd(object Unit, object Count) - { - return InvokeMethod("MoveEnd", Unit, Count) as int? ?? 0; - } - public void Copy() - { - InvokeMethod("Copy"); - } - public int EndKey() - { - return InvokeMethod("EndKey", Missing.Value, Missing.Value) as int? ?? 0; - } - public int EndKey(object Unit, object Extend) - { - return InvokeMethod("EndKey", Unit, Extend) as int? ?? 0; - } - public void TypeText(string Text) - { - InvokeMethod("TypeText", Text); - } - public int EndOf() - { - return InvokeMethod("EndOf", Missing.Value, Missing.Value) as int? ?? 0; - } - public int EndOf(object Unit, object Extend) - { - return InvokeMethod("EndOf", Unit, Extend) as int? ?? 0; - } - public LBRange GoTo() - { - return new LBRange(InvokeMethod("GoTo", Missing.Value, Missing.Value, Missing.Value, Missing.Value)); - } - public LBRange GoTo(object What, object Which, object Count, object Name) - { - return new LBRange(InvokeMethod("GoTo", What, Which, Count, Name)); - } - public void InsertSymbol(int CharacterNumber) - { - InvokeMethod("InsertSymbol", CharacterNumber, Missing.Value, Missing.Value, Missing.Value); - } - public void InsertSymbol(int CharacterNumber, object Font, object Unicode, object Bias) - { - InvokeMethod("InsertSymbol", CharacterNumber, Font, Unicode, Bias); - } - public int MoveRight() - { - return InvokeMethod("MoveRight", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; - } - public int MoveRight(object Unit, object Count, object Extend) - { - return InvokeMethod("MoveRight", Unit, Count, Extend) as int? ?? 0; - } - public int MoveLeft() - { - return InvokeMethod("MoveLeft", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; - } - public int MoveLeft(object Unit, object Count, object Extend) - { - return InvokeMethod("MoveLeft", Unit, Count, Extend) as int? ?? 0; - } - public void SelectCell() - { - InvokeMethod("SelectCell"); - } - public void SelectRow() - { - InvokeMethod("SelectRow"); - } - public void SelectColumn() - { - InvokeMethod("SelectColumn"); - } - public void TypeParagraph() - { - InvokeMethod("TypeParagraph"); - } - public void TypeBackspace() - { - InvokeMethod("TypeBackspace"); - } - public int MoveDown() - { - return InvokeMethod("MoveDown", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; - } - public int MoveDown(object Unit, object Count, object Extend) - { - return InvokeMethod("MoveDown", Unit, Count, Extend) as int? ?? 0; - } - public int MoveUp() - { - return InvokeMethod("MoveUp", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; - } - public int MoveUp(object Unit, object Count, object Extend) - { - return InvokeMethod("MoveUp", Unit, Count, Extend) as int? ?? 0; - } - } + public LBRows Rows => new LBRows(GetProperty("Rows")); + public void WholeStory() => InvokeMethod("WholeStory"); + public int MoveStart() => InvokeMethod("MoveStart", Missing.Value, Missing.Value) as int? ?? 0; + public int MoveStart(object Unit, object Count) => InvokeMethod("MoveStart", Unit, Count) as int? ?? 0; + public int MoveEnd() => InvokeMethod("MoveEnd", Missing.Value, Missing.Value) as int? ?? 0; + public int MoveEnd(object Unit, object Count) => InvokeMethod("MoveEnd", Unit, Count) as int? ?? 0; + public void Copy() => InvokeMethod("Copy"); + public int EndKey() => InvokeMethod("EndKey", Missing.Value, Missing.Value) as int? ?? 0; + public int EndKey(object Unit, object Extend) => InvokeMethod("EndKey", Unit, Extend) as int? ?? 0; + public void TypeText(string Text) => InvokeMethod("TypeText", Text); + public int EndOf() => InvokeMethod("EndOf", Missing.Value, Missing.Value) as int? ?? 0; + public int EndOf(object Unit, object Extend) => InvokeMethod("EndOf", Unit, Extend) as int? ?? 0; + public LBRange GoTo() => new LBRange(InvokeMethod("GoTo", Missing.Value, Missing.Value, Missing.Value, Missing.Value)); + public LBRange GoTo(object What, object Which, object Count, object Name) => new LBRange(InvokeMethod("GoTo", What, Which, Count, Name)); + public void InsertSymbol(int CharacterNumber) => InvokeMethod("InsertSymbol", CharacterNumber, Missing.Value, Missing.Value, Missing.Value); + public void InsertSymbol(int CharacterNumber, object Font, object Unicode, object Bias) => InvokeMethod("InsertSymbol", CharacterNumber, Font, Unicode, Bias); + public int MoveRight() => InvokeMethod("MoveRight", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; + public int MoveRight(object Unit, object Count, object Extend) => InvokeMethod("MoveRight", Unit, Count, Extend) as int? ?? 0; + public int MoveLeft() => InvokeMethod("MoveLeft", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; + public int MoveLeft(object Unit, object Count, object Extend) => InvokeMethod("MoveLeft", Unit, Count, Extend) as int? ?? 0; + public void SelectCell() => InvokeMethod("SelectCell"); + public void SelectRow() => InvokeMethod("SelectRow"); + public void SelectColumn() => InvokeMethod("SelectColumn"); + public void TypeParagraph() => InvokeMethod("TypeParagraph"); + public void TypeBackspace() => InvokeMethod("TypeBackspace"); + public int MoveDown() => InvokeMethod("MoveDown", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; + public int MoveDown(object Unit, object Count, object Extend) => InvokeMethod("MoveDown", Unit, Count, Extend) as int? ?? 0; + public int MoveUp() => InvokeMethod("MoveUp", Missing.Value, Missing.Value, Missing.Value) as int? ?? 0; + public int MoveUp(object Unit, object Count, object Extend) => InvokeMethod("MoveUp", Unit, Count, Extend) as int? ?? 0; + } public partial class LBDocumentClass : LBComObject { public LBDocumentClass() { } - public LBDocumentClass(Object item) : base(item) { } - public LBApplicationClass Application + public LBDocumentClass(object item) : base(item) { } + public LBApplicationClass Application => new LBApplicationClass(GetProperty("Application")); + public int SaveFormat => (GetProperty("SaveFormat") as int? ?? 0); + public string FullName => (GetProperty("FullName").ToString()); + public LBShapes Shapes => new LBShapes(GetProperty("Shapes")); + public LBWindow ActiveWindow => new LBWindow(GetProperty("ActiveWindow")); + public LBPageSetup PageSetup => new LBPageSetup(GetProperty("PageSetup")); + public bool Saved { - get { return new LBApplicationClass(GetProperty("Application")); } - } - public int SaveFormat - { - get { return (GetProperty("SaveFormat") as int? ?? 0); } - } - public String FullName - { - get { return (GetProperty("FullName").ToString()); } - } - public LBShapes Shapes - { - get { return new LBShapes(GetProperty("Shapes")); } - } - public LBWindow ActiveWindow - { - get { return new LBWindow(GetProperty("ActiveWindow")); } - } - public LBPageSetup PageSetup - { - get { return new LBPageSetup(GetProperty("PageSetup")); } - } - public Boolean Saved - { - get { return (GetProperty("Saved") as Boolean? ?? false); } + get { return (GetProperty("Saved") as bool? ?? false); } set { SetProperty("Saved", value); } } - public LBTables Tables - { - get { return new LBTables(GetProperty("Tables")); } - } - public float DefaultTabStop + public LBTables Tables => new LBTables(GetProperty("Tables")); + public float DefaultTabStop { get { return (GetProperty("DefaultTabStop") as float? ?? 0); } set { SetProperty("DefaultTabStop", value); } } - public void SaveAs2000() - { - InvokeMethod("SaveAs2000", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); - } - public void SaveAs2000(object FileName, object FileFormat, object LockComments, object Password, object AddToRecentFiles, object WritePassword, object ReadOnlyRecommended, object EmbedTrueTypeFonts, object SaveNativePictureFormat, object SaveFormsData, object SaveAsAOCELetter) - { - InvokeMethod("SaveAs2000", FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter); - } - public void SaveAs() - { - InvokeMethod("SaveAs", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); - } - public void SaveAs(object FileName, object FileFormat, object LockComments, object Password, object AddToRecentFiles, object WritePassword, object ReadOnlyRecommended, object EmbedTrueTypeFonts, object SaveNativePictureFormat, object SaveFormsData, object SaveAsAOCELetter, object Encoding, object InsertLineBreaks, object AllowSubstitutions, object LineEnding, object AddBiDiMarks) - { - InvokeMethod("SaveAs", FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks); - } - public void Close() - { - InvokeMethod("Close", Missing.Value, Missing.Value, Missing.Value); - } - public void Close(object SaveChanges, object OriginalFormat, object RouteDocument) - { - InvokeMethod("Close", SaveChanges, OriginalFormat, RouteDocument); - } - public void ExportAsFixedFormat(string OutputFileName, LBWdExportFormat ExportFormat) - { - InvokeMethod("ExportAsFixedFormat", OutputFileName, ExportFormat, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); - } - public void ExportAsFixedFormat(string OutputFileName, LBWdExportFormat ExportFormat, Boolean OpenAfterExport, LBWdExportOptimizeFor OptimizeFor, LBWdExportRange Range, int From, int To, LBWdExportItem Item, Boolean IncludeDocProps, Boolean KeepIRM, LBWdExportCreateBookmarks CreateBookmarks, Boolean DocStructureTags, Boolean BitmapMissingFonts, Boolean UseISO19005_1, object FixedFormatExtClassPtr) - { - InvokeMethod("ExportAsFixedFormat", OutputFileName, ExportFormat, OpenAfterExport, OptimizeFor, Range, From, To, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1, FixedFormatExtClassPtr); - } - public LBRange Range() - { - return new LBRange(InvokeMethod("Range", Missing.Value, Missing.Value)); - } - public LBRange Range(object Start, object End) - { - return new LBRange(InvokeMethod("Range", Start, End)); - } - public Boolean Undo() - { - return InvokeMethod("Undo", Missing.Value) as Boolean? ?? false; - } - public Boolean Undo(object Times) - { - return InvokeMethod("Undo", Times) as Boolean? ?? false; - } - } + public void SaveAs2000() => InvokeMethod("SaveAs2000", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); + public void SaveAs2000(object FileName, object FileFormat, object LockComments, object Password, object AddToRecentFiles, object WritePassword, object ReadOnlyRecommended, object EmbedTrueTypeFonts, object SaveNativePictureFormat, object SaveFormsData, object SaveAsAOCELetter) => InvokeMethod("SaveAs2000", FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter); + public void SaveAs() => InvokeMethod("SaveAs", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); + public void SaveAs(object FileName, object FileFormat, object LockComments, object Password, object AddToRecentFiles, object WritePassword, object ReadOnlyRecommended, object EmbedTrueTypeFonts, object SaveNativePictureFormat, object SaveFormsData, object SaveAsAOCELetter, object Encoding, object InsertLineBreaks, object AllowSubstitutions, object LineEnding, object AddBiDiMarks) => InvokeMethod("SaveAs", FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks); + public void Close() => InvokeMethod("Close", Missing.Value, Missing.Value, Missing.Value); + public void Close(object SaveChanges, object OriginalFormat, object RouteDocument) => InvokeMethod("Close", SaveChanges, OriginalFormat, RouteDocument); + public void ExportAsFixedFormat(string OutputFileName, LBWdExportFormat ExportFormat) => InvokeMethod("ExportAsFixedFormat", OutputFileName, ExportFormat, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); + public void ExportAsFixedFormat(string OutputFileName, LBWdExportFormat ExportFormat, bool OpenAfterExport, LBWdExportOptimizeFor OptimizeFor, LBWdExportRange Range, int From, int To, LBWdExportItem Item, bool IncludeDocProps, bool KeepIRM, LBWdExportCreateBookmarks CreateBookmarks, bool DocStructureTags, bool BitmapMissingFonts, bool UseISO19005_1, object FixedFormatExtClassPtr) => InvokeMethod("ExportAsFixedFormat", OutputFileName, ExportFormat, OpenAfterExport, OptimizeFor, Range, From, To, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1, FixedFormatExtClassPtr); + public LBRange Range() => new LBRange(InvokeMethod("Range", Missing.Value, Missing.Value)); + public LBRange Range(object Start, object End) => new LBRange(InvokeMethod("Range", Start, End)); + public bool Undo() => InvokeMethod("Undo", Missing.Value) as bool? ?? false; + public bool Undo(object Times) => InvokeMethod("Undo", Times) as bool? ?? false; + } public partial class LBWindow : LBComObject { public LBWindow() { } - public LBWindow(Object item) : base(item) { } - public LBPane ActivePane - { - get { return new LBPane(GetProperty("ActivePane")); } - } - public LBView View - { - get { return new LBView(GetProperty("View")); } - } - } + public LBWindow(object item) : base(item) { } + public LBPane ActivePane => new LBPane(GetProperty("ActivePane")); + public LBView View => new LBView(GetProperty("View")); + } public enum LBWdWindowState { wdWindowStateNormal = 0, @@ -493,78 +248,39 @@ namespace LBWordLibrary { public LBRange() { } - // B2022-088: Find Doc Ro button not working in Word Sections - public LBFind Find - { - get { return new LBFind(GetProperty("Find")); } - } + // B2022-088: Find Doc Ro button not working in Word Sections + public LBFind Find => new LBFind(GetProperty("Find")); - public int MoveStart() - { - return InvokeMethod("MoveStart", Missing.Value, Missing.Value) as int? ?? 0; - } + public int MoveStart() => InvokeMethod("MoveStart", Missing.Value, Missing.Value) as int? ?? 0; - public int MoveStart(object Unit, object Count) - { - return InvokeMethod("MoveStart", Unit, Count) as int? ?? 0; - } + public int MoveStart(object Unit, object Count) => InvokeMethod("MoveStart", Unit, Count) as int? ?? 0; - public int MoveEnd() - { - return InvokeMethod("MoveEnd", Missing.Value, Missing.Value) as int? ?? 0; - } + public int MoveEnd() => InvokeMethod("MoveEnd", Missing.Value, Missing.Value) as int? ?? 0; - public int MoveEnd(object Unit, object Count) - { - return InvokeMethod("MoveEnd", Unit, Count) as int? ?? 0; - } + public int MoveEnd(object Unit, object Count) => InvokeMethod("MoveEnd", Unit, Count) as int? ?? 0; - public void InsertSymbol(int CharacterNumber) - { - InvokeMethod("InsertSymbol", CharacterNumber, Missing.Value, Missing.Value, Missing.Value); - } + public void InsertSymbol(int CharacterNumber) => InvokeMethod("InsertSymbol", CharacterNumber, Missing.Value, Missing.Value, Missing.Value); - public void InsertSymbol(int CharacterNumber, object Font, object Unicode, object Bias) - { - InvokeMethod("InsertSymbol", CharacterNumber, Font, Unicode, Bias); - } + public void InsertSymbol(int CharacterNumber, object Font, object Unicode, object Bias) => InvokeMethod("InsertSymbol", CharacterNumber, Font, Unicode, Bias); - public void TypeText(string Text) - { - InvokeMethod("TypeText", Text); - } + public void TypeText(string Text) => InvokeMethod("TypeText", Text); - public LBRange(Object item) : base(item) { } - // B2018-028 Word 2016 has a different value for the Vertical Position Relative to the Text Boundary than older version of Word. - // We now need to calculated the last row of text in the PROMS attachment differently. - // We now subtract the TopMargin the Page Setup from the Vertical Position Relative to the Page (Lenght in LBObjectExtension.cs) - public LBPageSetup PageSetup - { - get { return new LBPageSetup(GetProperty("PageSetup")); } - } - // C2019-021 Added LateBinding for ListFormat - public LBListFormat ListFormat - { - get { return new LBListFormat(GetProperty("ListFormat")); } - } - public LBFontClass Font - { - get { return new LBFontClass(GetProperty("Font")); } - } - public LBWdColorIndex HighlightColorIndex + public LBRange(object item) : base(item) { } + // B2018-028 Word 2016 has a different value for the Vertical Position Relative to the Text Boundary than older version of Word. + // We now need to calculated the last row of text in the PROMS attachment differently. + // We now subtract the TopMargin the Page Setup from the Vertical Position Relative to the Page (Lenght in LBObjectExtension.cs) + public LBPageSetup PageSetup => new LBPageSetup(GetProperty("PageSetup")); + // C2019-021 Added LateBinding for ListFormat + public LBListFormat ListFormat => new LBListFormat(GetProperty("ListFormat")); + public LBFontClass Font => new LBFontClass(GetProperty("Font")); + public LBWdColorIndex HighlightColorIndex { get { return (LBWdColorIndex)GetProperty("HighlightColorIndex"); } set { SetProperty("HighlightColorIndex", value); } } - public LBParagraphFormatClass ParagraphFormat - { - get { return new LBParagraphFormatClass(GetProperty("ParagraphFormat")); } - } - public LBParagraphs Paragraphs - { - get { return new LBParagraphs(GetProperty("Paragraphs")); } - } - public int End + public LBParagraphFormatClass ParagraphFormat => new LBParagraphFormatClass(GetProperty("ParagraphFormat")); + public LBParagraphs Paragraphs => new LBParagraphs(GetProperty("Paragraphs")); + public int End { get { return (GetProperty("End") as int? ?? 0); } set { SetProperty("End", value); } @@ -574,25 +290,16 @@ namespace LBWordLibrary get { return (GetProperty("Start") as int? ?? 0); } set { SetProperty("Start", value); } } - public String Text + public string Text { get { return (GetProperty("Text").ToString()); } set { SetProperty("Text", value); } } - public LBTables Tables - { - get { return new LBTables(GetProperty("Tables")); } - } - public LBRows Rows - { - get { return new LBRows(GetProperty("Rows")); } - } - public LBColumns Columns - { - get { return new LBColumns(GetProperty("Columns")); } - } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public LBCells Cells + public LBTables Tables => new LBTables(GetProperty("Tables")); + public LBRows Rows => new LBRows(GetProperty("Rows")); + public LBColumns Columns => new LBColumns(GetProperty("Columns")); + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public LBCells Cells { get { @@ -600,29 +307,20 @@ namespace LBWordLibrary { return new LBCells(GetProperty("Cells")); } - catch(Exception ex) - { + catch (Exception) + { return null; } } } - public LBRange GoTo() - { - return new LBRange(InvokeMethod("GoTo", Missing.Value, Missing.Value, Missing.Value, Missing.Value)); - } - public LBRange GoTo(object What, object Which, object Count, object Name) - { - return new LBRange(InvokeMethod("GoTo", What, Which, Count, Name)); - } - public LBRange Select() - { - return new LBRange(InvokeMethod("Select")); - } - } + public LBRange GoTo() => new LBRange(InvokeMethod("GoTo", Missing.Value, Missing.Value, Missing.Value, Missing.Value)); + public LBRange GoTo(object What, object Which, object Count, object Name) => new LBRange(InvokeMethod("GoTo", What, Which, Count, Name)); + public LBRange Select() => new LBRange(InvokeMethod("Select")); + } public partial class LBParagraphFormatClass : LBComObject { public LBParagraphFormatClass() { } - public LBParagraphFormatClass(Object item) : base(item) { } + public LBParagraphFormatClass(object item) : base(item) { } public LBWdLineSpacing LineSpacingRule { get { return (LBWdLineSpacing)GetProperty("LineSpacingRule"); } @@ -689,14 +387,11 @@ namespace LBWordLibrary public partial class LBFind : LBComObject { public LBFind() { } - public LBFind(Object item) : base(item) { } - public LBReplacement Replacement + public LBFind(object item) : base(item) { } + public LBReplacement Replacement => new LBReplacement(GetProperty("Replacement")); + public bool Forward { - get { return new LBReplacement(GetProperty("Replacement")); } - } - public Boolean Forward - { - get { return (GetProperty("Forward") as Boolean? ?? false); } + get { return (GetProperty("Forward") as bool? ?? false); } set { SetProperty("Forward", value); } } public LBWdFindWrap Wrap @@ -704,58 +399,49 @@ namespace LBWordLibrary get { return (LBWdFindWrap)GetProperty("Wrap"); } set { SetProperty("Wrap", value); } } - public Boolean Format + public bool Format { - get { return (GetProperty("Format") as Boolean? ?? false); } + get { return (GetProperty("Format") as bool? ?? false); } set { SetProperty("Format", value); } } - public Boolean MatchWholeWord + public bool MatchWholeWord { - get { return (GetProperty("MatchWholeWord") as Boolean? ?? false); } + get { return (GetProperty("MatchWholeWord") as bool? ?? false); } set { SetProperty("MatchWholeWord", value); } } - public Boolean MatchWildcards + public bool MatchWildcards { - get { return (GetProperty("MatchWildcards") as Boolean? ?? false); } + get { return (GetProperty("MatchWildcards") as bool? ?? false); } set { SetProperty("MatchWildcards", value); } } - public Boolean MatchSoundsLike + public bool MatchSoundsLike { - get { return (GetProperty("MatchSoundsLike") as Boolean? ?? false); } + get { return (GetProperty("MatchSoundsLike") as bool? ?? false); } set { SetProperty("MatchSoundsLike", value); } } - public Boolean MatchAllWordForms + public bool MatchAllWordForms { - get { return (GetProperty("MatchAllWordForms") as Boolean? ?? false); } + get { return (GetProperty("MatchAllWordForms") as bool? ?? false); } set { SetProperty("MatchAllWordForms", value); } } - public String Text + public string Text { get { return (GetProperty("Text").ToString()); } set { SetProperty("Text", value); } } - public Boolean MatchCase + public bool MatchCase { - get { return (GetProperty("MatchCase") as Boolean? ?? false); } + get { return (GetProperty("MatchCase") as bool? ?? false); } set { SetProperty("MatchCase", value); } } - public Boolean Execute() - { - return InvokeMethod("Execute", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Boolean? ?? false; - } - public Boolean Execute(object FindText, object MatchCase, object MatchWholeWord, object MatchWildcards, object MatchSoundsLike, object MatchAllWordForms, object Forward, object Wrap, object Format, object ReplaceWith, object Replace, object MatchKashida, object MatchDiacritics, object MatchAlefHamza, object MatchControl) - { - return InvokeMethod("Execute", FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl) as Boolean? ?? false; - } - public void ClearFormatting() - { - InvokeMethod("ClearFormatting"); - } - } + public bool Execute() => InvokeMethod("Execute", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value) as bool? ?? false; + public bool Execute(object FindText, object MatchCase, object MatchWholeWord, object MatchWildcards, object MatchSoundsLike, object MatchAllWordForms, object Forward, object Wrap, object Format, object ReplaceWith, object Replace, object MatchKashida, object MatchDiacritics, object MatchAlefHamza, object MatchControl) => InvokeMethod("Execute", FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl) as bool? ?? false; + public void ClearFormatting() => InvokeMethod("ClearFormatting"); + } public partial class LBFontClass : LBComObject { public LBFontClass() { } - public LBFontClass(Object item) : base(item) { } + public LBFontClass(object item) : base(item) { } public LBWdColor Color { get { return (LBWdColor)GetProperty("Color"); } @@ -781,7 +467,7 @@ namespace LBWordLibrary get { return (GetProperty("Size") as float? ?? 0); } set { SetProperty("Size", value); } } - public String Name + public string Name { get { return (GetProperty("Name").ToString()); } set { SetProperty("Name", value); } @@ -837,85 +523,35 @@ namespace LBWordLibrary } public partial class LBInlineShapes : LBComObjectList /* Collection */ { - public LBInlineShapes(Object item) - { - Item = item; - } - public LBInlineShape AddPicture(string FileName) - { - return new LBInlineShape(InvokeMethod("AddPicture", FileName, Missing.Value, Missing.Value, Missing.Value)); - } - public LBInlineShape AddPicture(string FileName, object LinkToFile, object SaveWithDocument, object Range) - { - return new LBInlineShape(InvokeMethod("AddPicture", FileName, LinkToFile, SaveWithDocument, Range)); - } - } + public LBInlineShapes(object item) => Item = item; + public LBInlineShape AddPicture(string FileName) => new LBInlineShape(InvokeMethod("AddPicture", FileName, Missing.Value, Missing.Value, Missing.Value)); + public LBInlineShape AddPicture(string FileName, object LinkToFile, object SaveWithDocument, object Range) => new LBInlineShape(InvokeMethod("AddPicture", FileName, LinkToFile, SaveWithDocument, Range)); + } public partial class LBParagraphs : LBComObjectList /* Collection */ { - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public LBParagraph this[int item] - { - get // Get a Cell from a List - { - return new LBParagraph(base[item]); - } - } - public LBParagraphs(Object item) - { - Item = item; - } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public LBParagraph First - { - get { return new LBParagraph(GetProperty("First")); } - } - public LBParagraph Last - { - get { return new LBParagraph(GetProperty("Last")); } - } - public System.Object GetEnumerator() - { - return InvokeMethod("GetEnumerator"); - } - } + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public new LBParagraph this[int item] => new LBParagraph(base[item]); + public LBParagraphs(object item) => Item = item; + public int Count => (GetProperty("Count") as int? ?? 0); + public LBParagraph First => new LBParagraph(GetProperty("First")); + public LBParagraph Last => new LBParagraph(GetProperty("Last")); + public object GetEnumerator() => InvokeMethod("GetEnumerator"); + } public partial class LBTables : LBComObjectList /* Collection */ { - public LBTables(Object item) - { - Item = item; - } - public LBTable Add(LBRange Range, int NumRows, int NumColumns) - { - return new LBTable(InvokeMethod("Add", Range, NumRows, NumColumns, Missing.Value, Missing.Value)); - } - public LBTable Add(LBRange Range, int NumRows, int NumColumns, object DefaultTableBehavior, object AutoFitBehavior) - { - return new LBTable(InvokeMethod("Add", Range, NumRows, NumColumns, DefaultTableBehavior, AutoFitBehavior)); - } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public LBTable this[int item] - { - get - { // Get a Table from a list - return new LBTable(base[item]); - } - } + public LBTables(object item) => Item = item; + public LBTable Add(LBRange Range, int NumRows, int NumColumns) => new LBTable(InvokeMethod("Add", Range, NumRows, NumColumns, Missing.Value, Missing.Value)); + public LBTable Add(LBRange Range, int NumRows, int NumColumns, object DefaultTableBehavior, object AutoFitBehavior) => new LBTable(InvokeMethod("Add", Range, NumRows, NumColumns, DefaultTableBehavior, AutoFitBehavior)); + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public int Count => (GetProperty("Count") as int? ?? 0); + // Get a Table from a list + public new LBTable this[int item] => new LBTable(base[item]); - } + } public partial class LBCells : LBComObjectList /* Collection */ { - public LBCells(Object item) - { - Item = item; - } - public LBWdCellVerticalAlignment VerticalAlignment + public LBCells(object item) => Item = item; + public LBWdCellVerticalAlignment VerticalAlignment { get { return (LBWdCellVerticalAlignment)GetProperty("VerticalAlignment"); } set { SetProperty("VerticalAlignment", value); } @@ -925,54 +561,27 @@ namespace LBWordLibrary get { return (GetProperty("Height") as float? ?? 0); } set { SetProperty("Height", value); } } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public LBBorders Borders - { - get { return new LBBorders(GetProperty("Borders")); } - } - public System.Object GetEnumerator() - { - return InvokeMethod("GetEnumerator"); - } - public void Merge() - { - InvokeMethod("Merge"); - } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public LBCell this[int item] - { - get // Get a Cell from a List - { - return new LBCell(base[item]); - } - } + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public int Count => (GetProperty("Count") as int? ?? 0); + public LBBorders Borders => new LBBorders(GetProperty("Borders")); + public object GetEnumerator() => InvokeMethod("GetEnumerator"); + public void Merge() => InvokeMethod("Merge"); + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public new LBCell this[int item] => new LBCell(base[item]); - } + } public partial class LBRows : LBComObjectList /* Collection */ { - public LBRows(Object item) - { - Item = item; - } - public int HeadingFormat + public LBRows(object item) => Item = item; + public int HeadingFormat { get { return (GetProperty("HeadingFormat") as int? ?? 0); } set { SetProperty("HeadingFormat", value); } } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public LBRow First - { - get { return new LBRow(GetProperty("First")); } - } - public int AllowBreakAcrossPages + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public int Count => (GetProperty("Count") as int? ?? 0); + public LBRow First => new LBRow(GetProperty("First")); + public int AllowBreakAcrossPages { get { return (GetProperty("AllowBreakAcrossPages") as int? ?? 0); } set { SetProperty("AllowBreakAcrossPages", value); } @@ -980,23 +589,14 @@ namespace LBWordLibrary } public partial class LBShapes : LBComObjectList /* Collection */ { - public LBShapes(Object item) - { - Item = item; - } - public LBShape AddPicture(string FileName) - { - return new LBShape(InvokeMethod("AddPicture", FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); - } - public LBShape AddPicture(string FileName, object LinkToFile, object SaveWithDocument, object Left, object Top, object Width, object Height, object Anchor) - { - return new LBShape(InvokeMethod("AddPicture", FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height, Anchor)); - } - } + public LBShapes(object item) => Item = item; + public LBShape AddPicture(string FileName) => new LBShape(InvokeMethod("AddPicture", FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value)); + public LBShape AddPicture(string FileName, object LinkToFile, object SaveWithDocument, object Left, object Top, object Width, object Height, object Anchor) => new LBShape(InvokeMethod("AddPicture", FileName, LinkToFile, SaveWithDocument, Left, Top, Width, Height, Anchor)); + } public partial class LBPageSetup : LBComObject { public LBPageSetup() { } - public LBPageSetup(Object item) : base(item) { } + public LBPageSetup(object item) : base(item) { } public float BottomMargin { get { return (GetProperty("BottomMargin") as float? ?? 0); } @@ -1079,28 +679,22 @@ namespace LBWordLibrary public partial class LBPane : LBComObject { public LBPane() { } - public LBPane(Object item) : base(item) { } - public LBPages Pages - { - get { return new LBPages(GetProperty("Pages")); } - } - public LBView View - { - get { return new LBView(GetProperty("View")); } - } - } + public LBPane(object item) : base(item) { } + public LBPages Pages => new LBPages(GetProperty("Pages")); + public LBView View => new LBView(GetProperty("View")); + } public partial class LBView : LBComObject { public LBView() { } - public LBView(Object item) : base(item) { } + public LBView(object item) : base(item) { } public LBWdViewType Type { get { return (LBWdViewType)GetProperty("Type"); } set { SetProperty("Type", value); } } - public Boolean ShowRevisionsAndComments + public bool ShowRevisionsAndComments { - get { return (GetProperty("ShowRevisionsAndComments") as Boolean? ?? false); } + get { return (GetProperty("ShowRevisionsAndComments") as bool? ?? false); } set { SetProperty("ShowRevisionsAndComments", value); } } public LBWdRevisionsView RevisionsView @@ -1108,11 +702,8 @@ namespace LBWordLibrary get { return (LBWdRevisionsView)GetProperty("RevisionsView"); } set { SetProperty("RevisionsView", value); } } - public LBZoom Zoom - { - get { return new LBZoom(GetProperty("Zoom")); } - } - } + public LBZoom Zoom => new LBZoom(GetProperty("Zoom")); + } public enum LBWdColorIndex { wdNoHighlight = 0, @@ -1136,35 +727,14 @@ namespace LBWordLibrary } public partial class LBColumns : LBComObjectList /* Collection */ { - public LBColumns(Object item) - { - Item = item; - } - public LBColumn First - { - get { return new LBColumn(GetProperty("First")); } - } - public LBColumn Last - { - get { return new LBColumn(GetProperty("Last")); } - } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public System.Object GetEnumerator() - { - return InvokeMethod("GetEnumerator"); - } - public LBColumn this[int item] - { - get // Get a Column from a List - { - return new LBColumn(base[item]); - } - } + public LBColumns(object item) => Item = item; + public LBColumn First => new LBColumn(GetProperty("First")); + public LBColumn Last => new LBColumn(GetProperty("Last")); + public int Count => (GetProperty("Count") as int? ?? 0); + public object GetEnumerator() => InvokeMethod("GetEnumerator"); + public new LBColumn this[int item] => new LBColumn(base[item]); - } + } public enum LBWdLineSpacing { wdLineSpaceSingle = 0, @@ -1189,17 +759,14 @@ namespace LBWordLibrary public partial class LBReplacement : LBComObject { public LBReplacement() { } - public LBReplacement(Object item) : base(item) { } - public String Text + public LBReplacement(object item) : base(item) { } + public string Text { get { return (GetProperty("Text").ToString()); } set { SetProperty("Text", value); } } - public void ClearFormatting() - { - InvokeMethod("ClearFormatting"); - } - } + public void ClearFormatting() => InvokeMethod("ClearFormatting"); + } public enum LBWdFindWrap { wdFindStop = 0, @@ -1293,7 +860,7 @@ namespace LBWordLibrary public partial class LBInlineShape : LBComObject { public LBInlineShape() { } - public LBInlineShape(Object item) : base(item) { } + public LBInlineShape(object item) : base(item) { } public float Height { get { return (GetProperty("Height") as float? ?? 0); } @@ -1308,30 +875,18 @@ namespace LBWordLibrary public partial class LBParagraph : LBComObject { public LBParagraph() { } - public LBParagraph(Object item) : base(item) { } - public LBRange Range - { - get { return new LBRange(GetProperty("Range")); } - } - } + public LBParagraph(object item) : base(item) { } + public LBRange Range => new LBRange(GetProperty("Range")); + } public partial class LBTable : LBComObject { public LBTable() { } - public LBTable(Object item) : base(item) { } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public LBRange Range - { - get { return new LBRange(GetProperty("Range")); } - } - public LBColumns Columns - { - get { return new LBColumns(GetProperty("Columns")); } - } - public LBRows Rows - { - get { return new LBRows(GetProperty("Rows")); } - } - public float TopPadding + public LBTable(object item) : base(item) { } + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public LBRange Range => new LBRange(GetProperty("Range")); + public LBColumns Columns => new LBColumns(GetProperty("Columns")); + public LBRows Rows => new LBRows(GetProperty("Rows")); + public float TopPadding { get { return (GetProperty("TopPadding") as float? ?? 0); } set { SetProperty("TopPadding", value); } @@ -1360,38 +915,26 @@ namespace LBWordLibrary } public partial class LBBorders : LBComObjectList /* Collection */ { - public LBBorders(Object item) - { - Item = item; - } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - } + public LBBorders(object item) => Item = item; + public int Count => (GetProperty("Count") as int? ?? 0); + } public partial class LBRow : LBComObject { public LBRow() { } - public LBRow(Object item) : base(item) { } + public LBRow(object item) : base(item) { } public float Height { get { return (GetProperty("Height") as float? ?? 0); } set { SetProperty("Height", value); } } - public void Select() - { - InvokeMethod("Select"); - } - } + public void Select() => InvokeMethod("Select"); + } public partial class LBShape : LBComObject { public LBShape() { } - public LBShape(Object item) : base(item) { } - public void ConvertToInlineShape() - { - InvokeMethod("ConvertToInlineShape"); - } - public float Height + public LBShape(object item) : base(item) { } + public void ConvertToInlineShape() => InvokeMethod("ConvertToInlineShape"); + public float Height { get { return (GetProperty("Height") as float? ?? 0); } set { SetProperty("Height", value); } @@ -1401,21 +944,8 @@ namespace LBWordLibrary get { return (GetProperty("Width") as float? ?? 0); } set { SetProperty("Width", value); } } - //public float ScaleHeight - //{ - // get { return (GetProperty("ScaleHeight") as float? ?? 0); } - // set { SetProperty("ScaleHeight", value); } - //} - //public float ScaleWidth - //{ - // get { return (GetProperty("ScaleWidth") as float? ?? 0); } - // set { SetProperty("ScaleWidth", value); } - //} - public LBRange Anchor - { - get { return new LBRange(GetProperty("Anchor")); } - } - public LBMsoTriState LockAspectRatio + public LBRange Anchor => new LBRange(GetProperty("Anchor")); + public LBMsoTriState LockAspectRatio { get { return (LBMsoTriState)GetProperty("LockAspectRatio"); } set { SetProperty("LockAspectRatio", value); } @@ -1455,9 +985,9 @@ namespace LBWordLibrary get { return (GetProperty("LockAnchor") as int? ?? 0); } set { SetProperty("LockAnchor", value); } } - public Boolean LayoutInCell + public bool LayoutInCell { - get { return (GetProperty("LayoutInCell") as Boolean? ?? false); } + get { return (GetProperty("LayoutInCell") as bool? ?? false); } set { SetProperty("LayoutInCell", value); } } } @@ -1513,15 +1043,9 @@ namespace LBWordLibrary } public partial class LBPages : LBComObjectList /* Collection */ { - public LBPages(Object item) - { - Item = item; - } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - } + public LBPages(object item) => Item = item; + public int Count => (GetProperty("Count") as int? ?? 0); + } public enum LBWdViewType { wdNormalView = 1, @@ -1540,7 +1064,7 @@ namespace LBWordLibrary public partial class LBZoom : LBComObject { public LBZoom() { } - public LBZoom(Object item) : base(item) { } + public LBZoom(object item) : base(item) { } public LBWdPageFit PageFit { get { return (LBWdPageFit)GetProperty("PageFit"); } @@ -1555,29 +1079,17 @@ namespace LBWordLibrary public partial class LBColumn : LBComObject { public LBColumn() { } - public LBColumn(Object item) : base(item) { } + public LBColumn(object item) : base(item) { } public float Width { get { return (GetProperty("Width") as float? ?? 0); } set { SetProperty("Width", value); } } - public int Index - { - get { return (GetProperty("Index") as int? ?? 0); } - } - public LBColumn Next - { - get { return new LBColumn(GetProperty("Next")); } - } - public LBColumn Previous - { - get { return new LBColumn(GetProperty("Previous")); } - } - public void SetWidth(float ColumnWidth, LBWdRulerStyle RulerStyle) - { - InvokeMethod("SetWidth", ColumnWidth, RulerStyle); - } - } + public int Index => (GetProperty("Index") as int? ?? 0); + public LBColumn Next => new LBColumn(GetProperty("Next")); + public LBColumn Previous => new LBColumn(GetProperty("Previous")); + public void SetWidth(float ColumnWidth, LBWdRulerStyle RulerStyle) => InvokeMethod("SetWidth", ColumnWidth, RulerStyle); + } public enum LBWdRelativeHorizontalPosition { wdRelativeHorizontalPositionMargin = 0, @@ -1617,15 +1129,15 @@ namespace LBWordLibrary public partial class LBBorder : LBComObject { public LBBorder() { } - public LBBorder(Object item) : base(item) { } + public LBBorder(object item) : base(item) { } public LBWdLineStyle LineStyle { get { return (LBWdLineStyle)GetProperty("LineStyle"); } set { SetProperty("LineStyle", value); } } - public Boolean Visible + public bool Visible { - get { return (GetProperty("Visible") as Boolean? ?? false); } + get { return (GetProperty("Visible") as bool? ?? false); } set { SetProperty("Visible", value); } } } @@ -1671,29 +1183,14 @@ namespace LBWordLibrary public partial class LBCell : LBComObject { public LBCell() { } - public LBCell(Object item) : base(item) { } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public LBRange Range - { - get { return new LBRange(GetProperty("Range")); } - } - public LBColumn Column - { - get { return new LBColumn(GetProperty("Column")); } - } - public LBCell Next - { - get { return new LBCell(GetProperty("Next")); } - } - public LBCell Previous - { - get { return new LBCell(GetProperty("Previous")); } - } - public LBRow Row - { - get { return new LBRow(GetProperty("Row")); } - } - public LBWdCellVerticalAlignment VerticalAlignment + public LBCell(object item) : base(item) { } + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public LBRange Range => new LBRange(GetProperty("Range")); + public LBColumn Column => new LBColumn(GetProperty("Column")); + public LBCell Next => new LBCell(GetProperty("Next")); + public LBCell Previous => new LBCell(GetProperty("Previous")); + public LBRow Row => new LBRow(GetProperty("Row")); + public LBWdCellVerticalAlignment VerticalAlignment { get { return (LBWdCellVerticalAlignment)GetProperty("VerticalAlignment"); } set { SetProperty("VerticalAlignment", value); } @@ -1708,24 +1205,12 @@ namespace LBWordLibrary get { return (GetProperty("Height") as float? ?? 0); } set { SetProperty("Height", value); } } - // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content - public int RowIndex - { - get { return (GetProperty("RowIndex") as int? ?? 0); } - } - public int ColumnIndex - { - get { return (GetProperty("ColumnIndex") as int? ?? 0); } - } - public LBTables Tables - { - get { return new LBTables(GetProperty("Tables")); } - } - public void SetWidth(float ColumnWidth, LBWdRulerStyle RulerStyle) - { - InvokeMethod("SetWidth", ColumnWidth, RulerStyle); - } - } + // C2019-021 RHM 5/15/2019 Added newe methods and properties for Import Word Content + public int RowIndex => (GetProperty("RowIndex") as int? ?? 0); + public int ColumnIndex => (GetProperty("ColumnIndex") as int? ?? 0); + public LBTables Tables => new LBTables(GetProperty("Tables")); + public void SetWidth(float ColumnWidth, LBWdRulerStyle RulerStyle) => InvokeMethod("SetWidth", ColumnWidth, RulerStyle); + } public enum LBWdSaveFormat { wdFormatDocument = 0, @@ -1785,31 +1270,16 @@ namespace LBWordLibrary public partial class LBPage : LBComObject { public LBPage() { } - public LBPage(Object item) : base(item) { } - public int Height - { - get { return (GetProperty("Height") as int? ?? 0); } - } - public int Left - { - get { return (GetProperty("Left") as int? ?? 0); } - } - public LBRectangles Rectangles - { - get { return new LBRectangles(GetProperty("Rectangles")); } - } - public int Top - { - get { return (GetProperty("Top") as int? ?? 0); } - } - public int Width - { - get { return (GetProperty("Width") as int? ?? 0); } - } - } + public LBPage(object item) : base(item) { } + public int Height => (GetProperty("Height") as int? ?? 0); + public int Left => (GetProperty("Left") as int? ?? 0); + public LBRectangles Rectangles => new LBRectangles(GetProperty("Rectangles")); + public int Top => (GetProperty("Top") as int? ?? 0); + public int Width => (GetProperty("Width") as int? ?? 0); + } public partial class LBRectangles : LBComObjectList /* Collection */ { - public LBRectangles(Object item) + public LBRectangles(object item) { Item = item; } @@ -1821,36 +1291,21 @@ namespace LBWordLibrary public partial class LBRectangle : LBComObject { public LBRectangle() { } - public LBRectangle(Object item) : base(item) { } - public LBLines Lines - { - get { return new LBLines(GetProperty("Lines")); } - } - } + public LBRectangle(object item) : base(item) { } + public LBLines Lines => new LBLines(GetProperty("Lines")); + } public partial class LBLines : LBComObjectList /* Collection */ { - public LBLines(Object item) - { - Item = item; - } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - } + public LBLines(object item) => Item = item; + public int Count => (GetProperty("Count") as int? ?? 0); + } public partial class LBLine : LBComObject { public LBLine() { } - public LBLine(Object item) : base(item) { } - public int Top - { - get { return (GetProperty("Top") as int? ?? 0); } - } - public int Height - { - get { return (GetProperty("Height") as int? ?? 0); } - } - } + public LBLine(object item) : base(item) { } + public int Top => (GetProperty("Top") as int? ?? 0); + public int Height => (GetProperty("Height") as int? ?? 0); + } public enum LBWdMovementType { wdMove = 0, @@ -1905,54 +1360,29 @@ namespace LBWordLibrary public partial class LBPictureFormat : LBComObject { public LBPictureFormat() { } - public LBPictureFormat(Object item) : base(item) { } + public LBPictureFormat(object item) : base(item) { } } public partial class LBStyle : LBComObject { public LBStyle() { } - public LBStyle(Object item) : base(item) { } - public String NameLocal + public LBStyle(object item) : base(item) { } + public string NameLocal { get { return (GetProperty("NameLocal").ToString()); } set { SetProperty("NameLocal", value); } } - public int ListLevelNumber - { - get { return (GetProperty("ListLevelNumber") as int? ?? 0); } - } - } + public int ListLevelNumber => (GetProperty("ListLevelNumber") as int? ?? 0); + } // C2019-021 Added new object type LBListFormat public partial class LBListFormat : LBComObject { public LBListFormat() { } - public LBListFormat(Object item) : base(item) { } - public String NameLocal + public LBListFormat(object item) : base(item) { } + public string NameLocal { get { return (GetProperty("NameLocal").ToString()); } set { SetProperty("NameLocal", value); } } - public string ListString - { - get { return (GetProperty("ListString").ToString()); } - } - } - // public partial class LBStyles : LBComObjectList /* Collection */ -// { -// public LBStyles(Object item) -// { -// Item = item; -// } -// public int Count -// { -// get { return (GetProperty("Count") as int? ?? 0); } -// } -// public LBStyle Item -// { -// get { return new LBStyle(GetProperty("Item")); } -// } -// public System.Object GetEnumerator() -// { -// return InvokeMethod("GetEnumerator"); -// } -// } + public string ListString => (GetProperty("ListString").ToString()); + } } diff --git a/PROMS/LBWordLibrary/LBObjectExtension.cs b/PROMS/LBWordLibrary/LBObjectExtension.cs index 8af4c527..93d44e07 100644 --- a/PROMS/LBWordLibrary/LBObjectExtension.cs +++ b/PROMS/LBWordLibrary/LBObjectExtension.cs @@ -1,654 +1,519 @@ +using Microsoft.Win32; +using Read64bitRegistryFrom32bitApp; using System; using System.Collections.Generic; -using System.Text; using System.Reflection; -using Microsoft.Win32; -using System.Windows.Forms; +using System.Text; using System.Text.RegularExpressions; -using Read64bitRegistryFrom32bitApp; +using System.Windows.Forms; namespace LBWordLibrary { - public partial class LBApplicationClass : LBComObject - { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - /// - /// This gives the option of specifying Background = false to print in the foreground. - /// - /// boolean BackGround - /// If true - document will be printed in the background - /// If false - document will be printed in the foreground - public void PrintOut(Boolean Background) - { - InvokeMethod("PrintOut", Background, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); - } - public void Quit(bool save) - { - InvokeMethod("Quit", save, Missing.Value, Missing.Value); - } - public bool VolianPDFInstalled - { - get - { - foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) - if (printer == "VolianPDF Writer") return true; - return false; - } - } - private static bool? _WordPDFExporterInstalled = null; - public static bool WordPDFExporterInstalled - { - get - { - if (_WordPDFExporterInstalled == null) - { - // this is to determine if ExportAsFixedFormat was installed in MSOffice - // This key only worked for Vista - //RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"Installer\Components\12B306B24E250DD428FC7016B6FB4BD8"); - // This key works for Windows Vista and Windows 7 - try - { - string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\0E5C161912A2A6C4C93C76678926C56C"; - bool validKey = RegistryWOW6432.CheckRegKey64Valid(RegHive.HKEY_LOCAL_MACHINE, keyPath); - _WordPDFExporterInstalled = validKey; - if(!validKey) - _MyLog.WarnFormat("MSWord2007 PDF Export Registry Key Missing"); - //RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadSubTree); - //if (key == null) - //{ - // RegistryKey localMachine64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); - // key = localMachine64.OpenSubKey(keystring, RegistryKeyPermissionCheck.ReadSubTree); - //} - //if (key != null) - //{ - // key.Close(); - // _WordPDFExporterInstalled = true; - // return (bool) _WordPDFExporterInstalled; - //} - //_WordPDFExporterInstalled = FindEXP_PDF(); - return (bool) _WordPDFExporterInstalled; - } - catch (Exception ex) - { - _MyLog.WarnFormat("MSWord2007 PDF Export Registry Key Failure {0} - {1}", ex.GetType().Name, ex.Message); - _WordPDFExporterInstalled = false; - return (bool) _WordPDFExporterInstalled; - } + public partial class LBApplicationClass : LBComObject + { + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + /// + /// This gives the option of specifying Background = false to print in the foreground. + /// + /// boolean BackGround + /// If true - document will be printed in the background + /// If false - document will be printed in the foreground + public void PrintOut(bool Background) => InvokeMethod("PrintOut", Background, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); + public void Quit(bool save) => InvokeMethod("Quit", save, Missing.Value, Missing.Value); + public bool VolianPDFInstalled + { + get + { + foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) + if (printer == "VolianPDF Writer") return true; + return false; + } + } + private static bool? _WordPDFExporterInstalled = null; + public static bool WordPDFExporterInstalled + { + get + { + if (_WordPDFExporterInstalled == null) + { + // this is to determine if ExportAsFixedFormat was installed in MSOffice + // This key only worked for Vista + //RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"Installer\Components\12B306B24E250DD428FC7016B6FB4BD8"); + // This key works for Windows Vista and Windows 7 + try + { + string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\0E5C161912A2A6C4C93C76678926C56C"; + bool validKey = RegistryWOW6432.CheckRegKey64Valid(RegHive.HKEY_LOCAL_MACHINE, keyPath); + _WordPDFExporterInstalled = validKey; + if (!validKey) + _MyLog.WarnFormat("MSWord2007 PDF Export Registry Key Missing"); + + return (bool)_WordPDFExporterInstalled; + } + catch (Exception ex) + { + _MyLog.WarnFormat("MSWord2007 PDF Export Registry Key Failure {0} - {1}", ex.GetType().Name, ex.Message); + _WordPDFExporterInstalled = false; + return (bool)_WordPDFExporterInstalled; + } - } - return (bool) _WordPDFExporterInstalled; - } - } - private static bool FindEXP_PDF() - { - bool retval = false; - DateTime dtStart = DateTime.Now; - try - { - //string keystr = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\0E5C161912A2A6C4C93C76678926C56C"; - RegistryKey key = null; - string keystr = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components"; - while (key == null && keystr != "") - { - key = Registry.LocalMachine.OpenSubKey(keystr, RegistryKeyPermissionCheck.ReadSubTree); - keystr = keystr.Substring(0, keystr.LastIndexOf("\\")); - } - if (FindKeys(key, "EXP_PDF.DLL")) - retval = true; - } - catch (Exception ex) - { - AddKeyFound(string.Format("{0} - {1}", ex.GetType().Name, ex.Message)); - } - finally - { - DateTime dtEnd = DateTime.Now; - TimeSpan ts = TimeSpan.FromTicks(dtEnd.Ticks - dtStart.Ticks); - AddKeyFound(string.Format("{0} Seconds", ts.TotalSeconds)); - } - return retval; - } - private static bool FindKeys(RegistryKey key, string find) - { - string[] keyNames = key.GetSubKeyNames(); - foreach (string keyName in keyNames) - { - using (RegistryKey subKey = key.OpenSubKey(keyName, RegistryKeyPermissionCheck.ReadSubTree)) - { - if (FindKeys(subKey, find)) return true; - } - } - if (FindNames(key, find)) return true; - return false; - } - private static bool FindNames(RegistryKey key, string find) - { - string[] names = key.GetValueNames(); - foreach (string name in names) - { - if (FindNames(key, name, find)) return true; - } - return false; - } - private static bool FindNames(RegistryKey key, string name, string find) - { - RegistryValueKind kind = key.GetValueKind(name); - if (kind == RegistryValueKind.String) - { - string val = (string)key.GetValue(name); - if (val.Contains(find)) - { - AddKeyFound(string.Format("'{0}'\r\n Value {1} = '{2}'", key.ToString(), name, val)); - return true; - } - } - return false; - } - private static void AddKeyFound(string str) - { - _MyLog.WarnFormat("RegistryKeySearch: {0}",str); - } - private bool CanCreatePDFFile(string pdfFileName) - { - System.IO.FileInfo file = new System.IO.FileInfo(pdfFileName); - if (!file.Exists) return true; - try - { - file.Delete(); - return true; - } - catch (System.IO.IOException exio) - { - if (exio.Message.StartsWith("The process cannot access the file")) return false; - throw new Exception(string.Format("Cannot Delete PDF file {0}", pdfFileName), exio); - } - catch (Exception ex) - { - throw new Exception(string.Format("Cannot Delete PDF file {0}", pdfFileName), ex); - } - } - private string AvailableFileName(string pdfFileName) - { - if (CanCreatePDFFile(pdfFileName)) return pdfFileName; - string prefix = pdfFileName.Replace(".pdf", ""); - for (int i = 1; i < 1000; i++) - { - string newname = string.Format("{0}_{1:000}.PDF", prefix, i); - if (CanCreatePDFFile(newname)) return newname; - } - throw new Exception("Cannot find a name to use"); - } - public string CreatePDF(string pdfFileName, bool openPDF,int DebugStatus) - { - pdfFileName = CreatePDF(pdfFileName, DebugStatus); - if (openPDF) OpenPDF(pdfFileName); - return pdfFileName; - } - static List _AcrobatProcesses=new List(); - private static void OpenPDF(string pdfFileName) - { - _AcrobatProcesses.Add(System.Diagnostics.Process.Start(pdfFileName)); - } - public static void ClosePDFs() - { - foreach(System.Diagnostics.Process proc in _AcrobatProcesses) - if (!proc.HasExited) - KillAndWait(proc); - } - private static void KillAndWait(System.Diagnostics.Process proc) - { - Console.WriteLine("{0:s.ffff} Killing Adobe", DateTime.Now); - DateTime tStart = DateTime.Now; - proc.Kill(); - DateTime tEnd = DateTime.Now.AddMilliseconds(100); - while (DateTime.Now < tEnd) - { - Application.DoEvents(); - } - Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.ffff} {1:yyyy-MM-dd HH:mm:ss.ffff} {2}", DateTime.Now, proc.ExitTime - ,TimeSpan.FromTicks(proc.ExitTime.Ticks - tStart.Ticks).TotalMilliseconds); - } - public string CreatePDF(string pdfFileName, int DebugStatus) - { - pdfFileName = AvailableFileName(pdfFileName); - if (((int)Convert.ToSingle(Version)) > 12) - return CreatePDF2007(pdfFileName, DebugStatus); - if (((int)Convert.ToSingle(Version)) == 12 && WordPDFExporterInstalled) - { - //_MyLog.WarnFormat("Word PDF Exporter Installed - MSWord Version = '{0}'" , Version); - return CreatePDF2007(pdfFileName, DebugStatus); - } - if (VolianPDFInstalled) - { - _MyLog.WarnFormat("Using VolianPDFWriter - MSWord Version = '{0}'", Version); - return CreatePDF2003BG(pdfFileName); - } - //else // Force PDF Export - //{ - // _MyLog.WarnFormat("Force PDF Export for Michelle - MSWord Version = '{0}'", Version); - // return CreatePDF2007(pdfFileName, DebugStatus); - throw new Exception("No PDF Writer support installed for MS Word sections"); - //} - } - public string CreatePDF2003FG(string pdfFileName, bool openPDF) - { - pdfFileName = CreatePDF2003FG(pdfFileName); - if (openPDF) OpenPDF(pdfFileName); - return pdfFileName; - } - public string CreatePDF2003FG(string pdfFileName) - { - pdfFileName = AvailableFileName(pdfFileName); - if (!VolianPDFInstalled) - throw new Exception("VolianPDF Writer is not installed properly"); - try - { - string printer = ActivePrinter; - RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\VolianPDF Writer"); - key.SetValue("OutputFile", pdfFileName, RegistryValueKind.String); - key.SetValue("BypassSaveAs", "1", RegistryValueKind.String); - key.Close(); - ActivePrinter = "VolianPDF Writer"; - PrintOut(false); - ActivePrinter = printer; - Registry.CurrentUser.DeleteSubKeyTree(@"Software\VolianPDF Writer"); - return pdfFileName; - } - catch (Exception ex) - { - throw new Exception("Error creating PDF - LBApplicationClass.CreatePDF2003FG", ex); - } - } - public string CreatePDF2003BG(string pdfFileName, bool openPDF) - { - pdfFileName = CreatePDF2003BG(pdfFileName); - if (openPDF) OpenPDF(pdfFileName); - return pdfFileName; - } - public string CreatePDF2003BG(string pdfFileName) - { - pdfFileName = AvailableFileName(pdfFileName); - if (!VolianPDFInstalled) - throw new Exception("VolianPDF Writer is not installed properly"); - try - { - string printer = ActivePrinter; - RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\VolianPDF Writer"); - key.SetValue("OutputFile", pdfFileName, RegistryValueKind.String); - key.SetValue("BypassSaveAs", "1", RegistryValueKind.String); - key.Close(); - ActivePrinter = "VolianPDF Writer"; - PrintOut(true); - do - { - // Console.WriteLine("Background Printing Status = {0}", _MyApp.BackgroundPrintingStatus); - Application.DoEvents(); - } while (BackgroundPrintingStatus == 1); - ActivePrinter = printer; - Registry.CurrentUser.DeleteSubKeyTree(@"Software\VolianPDF Writer"); - return pdfFileName; - } - catch (Exception ex) - { - throw new Exception("Error creating PDF - LBApplicationClass.CreatePDF2003BG", ex); - } - } - public string CreatePDF2007(string pdfFileName, bool openPDF, int DebugStatus) - { - pdfFileName = CreatePDF2007(pdfFileName, DebugStatus); - if (openPDF) OpenPDF(pdfFileName); - return pdfFileName; - } - public string CreatePDF2007(string pdfFileName,int DebugStatus) - { - pdfFileName = AvailableFileName(pdfFileName); - // Removed to support MSWord 2010 and beyond. - //if (!WordPDFExporterInstalled) - // throw new Exception("MS Word PDF Exporter is not installed"); - try - { - ActiveDocument.ExportAsFixedFormat(pdfFileName, LBWdExportFormat.wdExportFormatPDF, DebugStatus); - return pdfFileName; - } - catch (Exception ex) - { - throw new Exception("Error creating PDF - LBApplicationClass.CreatePDF2007", ex); - } - } - } - public partial class LBDocuments - { - public LBDocumentClass Open(string fileName, Boolean addToRecentFiles) - { - return Open(fileName, Missing.Value, Missing.Value, addToRecentFiles); - } - private LBDocumentClass Open(params object[] myParams) - { - return new LBDocumentClass(InvokeMethod("Open", myParams)); - } - } - public partial class LBDocumentClass : LBComObject - { - public void ExportAsFixedFormat(string OutputFileName, LBWdExportFormat ExportFormat, int DebugStatus) - { - // iso 19005-1 compliant (PDF/A) [UseISO19005_1] should be set to false. for compare print - // iso 19005-1 compliant (PDF/A) [UseISO19005_1] should be set to true for production print - InvokeMethod("ExportAsFixedFormat", OutputFileName, ExportFormat, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, DebugStatus == 0, Missing.Value); - } - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - public void SaveAs2000(string fileName) - { - if (fileName.ToUpper().EndsWith("DOC")) - SaveAs2000(fileName, LBWdSaveFormat.wdFormatDocument); - else if (fileName.ToUpper().EndsWith("RTF")) - SaveAs2000(fileName, LBWdSaveFormat.wdFormatRTF); - else - SaveAs2000(fileName); - } - public void SaveAs2000(params object[] myParams) - { - InvokeMethod("SaveAs2000", myParams); - } - public void SaveAs(string fileName) - { - if (fileName.ToUpper().EndsWith("DOC")) - SaveAs2(fileName, LBWdSaveFormat.wdFormatDocument, Missing.Value, Missing.Value, false); - else if (fileName.ToUpper().EndsWith("RTF")) - SaveAs2(fileName, LBWdSaveFormat.wdFormatRTF, Missing.Value, Missing.Value, false); - else if (fileName.ToUpper().EndsWith("TXT")) - SaveAs2(fileName, LBWdSaveFormat.wdFormatDOSText, Missing.Value, Missing.Value, false); - else if (fileName.ToUpper().EndsWith("DOCX")) - SaveAs2(fileName, LBWdSaveFormat.wdFormatXMLDocument, Missing.Value, Missing.Value, false); - else - SaveAs2(fileName, Missing.Value, Missing.Value, Missing.Value, false); - } - public void SaveAs2(params object[] myParams) - { - InvokeMethod("SaveAs", myParams); - } - public void SaveAs(string fileName, LBWdSaveFormat format) - { - SaveAs2(fileName, format, Missing.Value, Missing.Value, false); - } - public LBRange Range(int Start, int End) - { - return new LBRange(InvokeMethod("Range", Start, End)); - } - /// - /// Length is Pages and Partial Pages - /// The integral part is the number of full pages - /// The decimal part is the size of the last page divided by 7200 - /// (the first two digits should be the number of inches) - /// - public float Length - { - get - { - ActiveWindow.ActivePane.View.Type = LBWdViewType.wdPrintView; - ActiveWindow.View.Type = LBWdViewType.wdPrintView; - LBPages myPages = ActiveWindow.ActivePane.Pages;// Start with pages - float retval = (float)myPages.Count - 1; - LBRange myRange = Range(); - - myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToAbsolute, 0); - float mytop = myRange.PageSetup.TopMargin; + } + return (bool)_WordPDFExporterInstalled; + } + } + + private static bool FindKeys(RegistryKey key, string find) + { + string[] keyNames = key.GetSubKeyNames(); + foreach (string keyName in keyNames) + { + using (RegistryKey subKey = key.OpenSubKey(keyName, RegistryKeyPermissionCheck.ReadSubTree)) + { + if (FindKeys(subKey, find)) return true; + } + } + if (FindNames(key, find)) return true; + return false; + } + private static bool FindNames(RegistryKey key, string find) + { + string[] names = key.GetValueNames(); + foreach (string name in names) + { + if (FindNames(key, name, find)) return true; + } + return false; + } + private static bool FindNames(RegistryKey key, string name, string find) + { + RegistryValueKind kind = key.GetValueKind(name); + if (kind == RegistryValueKind.String) + { + string val = (string)key.GetValue(name); + if (val.Contains(find)) + { + AddKeyFound(string.Format("'{0}'\r\n Value {1} = '{2}'", key.ToString(), name, val)); + return true; + } + } + return false; + } + private static void AddKeyFound(string str) => _MyLog.WarnFormat("RegistryKeySearch: {0}", str); + private bool CanCreatePDFFile(string pdfFileName) + { + System.IO.FileInfo file = new System.IO.FileInfo(pdfFileName); + if (!file.Exists) return true; + try + { + file.Delete(); + return true; + } + catch (System.IO.IOException exio) + { + if (exio.Message.StartsWith("The process cannot access the file")) return false; + throw new Exception(string.Format("Cannot Delete PDF file {0}", pdfFileName), exio); + } + catch (Exception ex) + { + throw new Exception(string.Format("Cannot Delete PDF file {0}", pdfFileName), ex); + } + } + private string AvailableFileName(string pdfFileName) + { + if (CanCreatePDFFile(pdfFileName)) return pdfFileName; + string prefix = pdfFileName.Replace(".pdf", ""); + for (int i = 1; i < 1000; i++) + { + string newname = string.Format("{0}_{1:000}.PDF", prefix, i); + if (CanCreatePDFFile(newname)) return newname; + } + throw new Exception("Cannot find a name to use"); + } + public string CreatePDF(string pdfFileName, bool openPDF, int DebugStatus) + { + pdfFileName = CreatePDF(pdfFileName, DebugStatus); + if (openPDF) OpenPDF(pdfFileName); + return pdfFileName; + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + static List _AcrobatProcesses = new List(); + private static void OpenPDF(string pdfFileName) => _AcrobatProcesses.Add(System.Diagnostics.Process.Start(pdfFileName)); + public static void ClosePDFs() + { + foreach (System.Diagnostics.Process proc in _AcrobatProcesses) + if (!proc.HasExited) + KillAndWait(proc); + } + private static void KillAndWait(System.Diagnostics.Process proc) + { + Console.WriteLine("{0:s.ffff} Killing Adobe", DateTime.Now); + DateTime tStart = DateTime.Now; + proc.Kill(); + DateTime tEnd = DateTime.Now.AddMilliseconds(100); + while (DateTime.Now < tEnd) + { + Application.DoEvents(); + } + Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.ffff} {1:yyyy-MM-dd HH:mm:ss.ffff} {2}", DateTime.Now, proc.ExitTime + , TimeSpan.FromTicks(proc.ExitTime.Ticks - tStart.Ticks).TotalMilliseconds); + } + public string CreatePDF(string pdfFileName, int DebugStatus) + { + pdfFileName = AvailableFileName(pdfFileName); + if (((int)Convert.ToSingle(Version)) > 12) + return CreatePDF2007(pdfFileName, DebugStatus); + if (((int)Convert.ToSingle(Version)) == 12 && WordPDFExporterInstalled) + { + //_MyLog.WarnFormat("Word PDF Exporter Installed - MSWord Version = '{0}'" , Version); + return CreatePDF2007(pdfFileName, DebugStatus); + } + if (VolianPDFInstalled) + { + _MyLog.WarnFormat("Using VolianPDFWriter - MSWord Version = '{0}'", Version); + return CreatePDF2003BG(pdfFileName); + } + throw new Exception("No PDF Writer support installed for MS Word sections"); + } + public string CreatePDF2003FG(string pdfFileName, bool openPDF) + { + pdfFileName = CreatePDF2003FG(pdfFileName); + if (openPDF) OpenPDF(pdfFileName); + return pdfFileName; + } + public string CreatePDF2003FG(string pdfFileName) + { + pdfFileName = AvailableFileName(pdfFileName); + if (!VolianPDFInstalled) + throw new Exception("VolianPDF Writer is not installed properly"); + try + { + string printer = ActivePrinter; + RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\VolianPDF Writer"); + key.SetValue("OutputFile", pdfFileName, RegistryValueKind.String); + key.SetValue("BypassSaveAs", "1", RegistryValueKind.String); + key.Close(); + ActivePrinter = "VolianPDF Writer"; + PrintOut(false); + ActivePrinter = printer; + Registry.CurrentUser.DeleteSubKeyTree(@"Software\VolianPDF Writer"); + return pdfFileName; + } + catch (Exception ex) + { + throw new Exception("Error creating PDF - LBApplicationClass.CreatePDF2003FG", ex); + } + } + public string CreatePDF2003BG(string pdfFileName, bool openPDF) + { + pdfFileName = CreatePDF2003BG(pdfFileName); + if (openPDF) OpenPDF(pdfFileName); + return pdfFileName; + } + public string CreatePDF2003BG(string pdfFileName) + { + pdfFileName = AvailableFileName(pdfFileName); + if (!VolianPDFInstalled) + throw new Exception("VolianPDF Writer is not installed properly"); + try + { + string printer = ActivePrinter; + RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\VolianPDF Writer"); + key.SetValue("OutputFile", pdfFileName, RegistryValueKind.String); + key.SetValue("BypassSaveAs", "1", RegistryValueKind.String); + key.Close(); + ActivePrinter = "VolianPDF Writer"; + PrintOut(true); + do + { + // Console.WriteLine("Background Printing Status = {0}", _MyApp.BackgroundPrintingStatus); + Application.DoEvents(); + } while (BackgroundPrintingStatus == 1); + ActivePrinter = printer; + Registry.CurrentUser.DeleteSubKeyTree(@"Software\VolianPDF Writer"); + return pdfFileName; + } + catch (Exception ex) + { + throw new Exception("Error creating PDF - LBApplicationClass.CreatePDF2003BG", ex); + } + } + public string CreatePDF2007(string pdfFileName, bool openPDF, int DebugStatus) + { + pdfFileName = CreatePDF2007(pdfFileName, DebugStatus); + if (openPDF) OpenPDF(pdfFileName); + return pdfFileName; + } + public string CreatePDF2007(string pdfFileName, int DebugStatus) + { + pdfFileName = AvailableFileName(pdfFileName); + try + { + ActiveDocument.ExportAsFixedFormat(pdfFileName, LBWdExportFormat.wdExportFormatPDF, DebugStatus); + return pdfFileName; + } + catch (Exception ex) + { + throw new Exception("Error creating PDF - LBApplicationClass.CreatePDF2007", ex); + } + } + } + public partial class LBDocuments + { + public LBDocumentClass Open(string fileName, bool addToRecentFiles) => Open(fileName, Missing.Value, Missing.Value, addToRecentFiles); + private LBDocumentClass Open(params object[] myParams) => new LBDocumentClass(InvokeMethod("Open", myParams)); + } + public partial class LBDocumentClass : LBComObject + { + public void ExportAsFixedFormat(string OutputFileName, LBWdExportFormat ExportFormat, int DebugStatus) + { + // iso 19005-1 compliant (PDF/A) [UseISO19005_1] should be set to false. for compare print + // iso 19005-1 compliant (PDF/A) [UseISO19005_1] should be set to true for production print + InvokeMethod("ExportAsFixedFormat", OutputFileName, ExportFormat, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, DebugStatus == 0, Missing.Value); + } + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + public void SaveAs2000(string fileName) + { + if (fileName.ToUpper().EndsWith("DOC")) + SaveAs2000(fileName, LBWdSaveFormat.wdFormatDocument); + else if (fileName.ToUpper().EndsWith("RTF")) + SaveAs2000(fileName, LBWdSaveFormat.wdFormatRTF); + else + SaveAs2000(fileName); + } + public void SaveAs2000(params object[] myParams) => InvokeMethod("SaveAs2000", myParams); + public void SaveAs(string fileName) + { + if (fileName.ToUpper().EndsWith("DOC")) + SaveAs2(fileName, LBWdSaveFormat.wdFormatDocument, Missing.Value, Missing.Value, false); + else if (fileName.ToUpper().EndsWith("RTF")) + SaveAs2(fileName, LBWdSaveFormat.wdFormatRTF, Missing.Value, Missing.Value, false); + else if (fileName.ToUpper().EndsWith("TXT")) + SaveAs2(fileName, LBWdSaveFormat.wdFormatDOSText, Missing.Value, Missing.Value, false); + else if (fileName.ToUpper().EndsWith("DOCX")) + SaveAs2(fileName, LBWdSaveFormat.wdFormatXMLDocument, Missing.Value, Missing.Value, false); + else + SaveAs2(fileName, Missing.Value, Missing.Value, Missing.Value, false); + } + public void SaveAs2(params object[] myParams) => InvokeMethod("SaveAs", myParams); + public void SaveAs(string fileName, LBWdSaveFormat format) => SaveAs2(fileName, format, Missing.Value, Missing.Value, false); + public LBRange Range(int Start, int End) => new LBRange(InvokeMethod("Range", Start, End)); + /// + /// Length is Pages and Partial Pages + /// The integral part is the number of full pages + /// The decimal part is the size of the last page divided by 7200 + /// (the first two digits should be the number of inches) + /// + public float Length + { + get + { + ActiveWindow.ActivePane.View.Type = LBWdViewType.wdPrintView; + ActiveWindow.View.Type = LBWdViewType.wdPrintView; + LBPages myPages = ActiveWindow.ActivePane.Pages;// Start with pages + float retval = (float)myPages.Count - 1; + LBRange myRange = Range(); + + myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToAbsolute, 0); + float mytop = myRange.PageSetup.TopMargin; myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToLast, 100); - //float partial = (float) myRange.get_Information(LBWdInformation.wdVerticalPositionRelativeToTextBoundary); - // B2018-028 Word 2016 has a different value for the Vertical Position Relative to the Text Boundary than older version of Word. - // We now need to calculated the last row of text in the PROMS attachment differently. - // We now subtract the TopMargin the Page Setup from the Vertical Position Relative to the Page - // this works with older versions of MS Word as well. - float partial = (float)myRange.get_Information(LBWdInformation.wdVerticalPositionRelativeToPage) - mytop; - partial += myRange.Font.Size; - retval += partial / 7200; - return retval; - } - } - public string Ascii - { - get - { - LBRange myRange = Range(); - myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToLast, 100); - myRange.Start = 0; - return ReplaceSymbolCharacters(GetRangeText(myRange)); - } - } - private static string[] SymbolFontName = { "VolianDraw", "WingDings", "VESymb", "VESymbFix", "Symbol" }; - private static bool IsSymbolFont(string fontName) - { - foreach (string symbolFont in SymbolFontName) - if (fontName.ToUpper().StartsWith(symbolFont.ToUpper())) - return true; - return false; - } - - /// - /// Checks to see if the document contains symbol characters - /// - /// - public bool HasSymbolCharacters - { - get - { - LBRange myRange = Range(); - myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToLast, 100); - myRange.Start = 0; - int end = myRange.End; - string myText = GetRangeText(myRange); - //return _RegFindSymbol.IsMatch(myText); - MatchCollection problems = _RegFindSymbol.Matches(myText); - int offset = 0; - foreach (Match problem in problems) - { - myRange.Start = problem.Index + offset; - myRange.End = problem.Index + problem.Length + offset; - int newOffset = FindRangeOffset(myRange, problem, offset, end); - if (IsSymbolFont(myRange.Font.Name)) - { - Console.WriteLine("Font '{0}' has Symbols", myRange.Font.Name); - //return true; - } - else - return true; - offset = newOffset; - } - return false; - } - } - Regex _RegFindSymbol = new Regex("[\\uF020-\\uF07F]+"); + float partial = (float)myRange.get_Information(LBWdInformation.wdVerticalPositionRelativeToPage) - mytop; + partial += myRange.Font.Size; + retval += partial / 7200; + return retval; + } + } + public string Ascii + { + get + { + LBRange myRange = Range(); + myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToLast, 100); + myRange.Start = 0; + return ReplaceSymbolCharacters(GetRangeText(myRange)); + } + } + private static readonly string[] SymbolFontName = { "VolianDraw", "WingDings", "VESymb", "VESymbFix", "Symbol" }; + private static bool IsSymbolFont(string fontName) + { + foreach (string symbolFont in SymbolFontName) + if (fontName.ToUpper().StartsWith(symbolFont.ToUpper())) + return true; + return false; + } - /// - /// Get the Range Text with error handling. myRange.Text sometimes will get a null reference exception. - /// - /// - /// - internal static string GetRangeText(LBRange myRange) - { - string text=""; - try - { - if (myRange.Start == myRange.End)// If Start and End equal return an empty string. - text = ""; - else - text = myRange.Text; - } - catch (Exception ex) - { - Console.WriteLine("GetRangeText {0} - {1}", ex.GetType().Name, ex.Message); - } - return text; - } - /// - /// Looks for the problem string and adjusts the range as necessary - /// - /// - /// - /// - /// - /// - private int FindRangeOffset(LBRange myRange, Match problem, int offset, int end) - { - // try to find the string - string text = GetRangeText(myRange); - if (text != problem.Value) - { - // Get the entire text starting at the offset of the first match - myRange.Start = problem.Index + offset; - myRange.End = end; - text = GetRangeText(myRange); - while (!text.StartsWith(problem.Value)) - { - int newStart = text.IndexOf(problem.Value);// Find the string if it is not at the beginning - myRange.Start += myRange.Start == newStart ? newStart + 1 : newStart; // adjust the starting location - text = GetRangeText(myRange);// get the text to check - } - myRange.End = myRange.Start + problem.Length; // assume that the end should be the start plus the length - text = GetRangeText(myRange); - while (text.Length < problem.Length) // If the result is too short increase the length - { - myRange.End += (problem.Length - text.Length); - text = GetRangeText(myRange); - } - } - return myRange.Start - problem.Index; - } - /// - /// ReplaceSymbolCharacters processes the string returned and changes any symbols (0xF0??) to normal characters - /// - /// - /// - private static string ReplaceSymbolCharacters(string str) - { - StringBuilder results = new StringBuilder(); - foreach (char c in str) - { - if ((c & 0xFF00) == 0xF000) - results.Append((char)(c & 0xFF)); - else - results.Append((char)(c)); - } - return results.ToString(); - } - /// - /// Close the document - /// - /// Save Changes - public void Close(bool SaveChanges) - { - InvokeMethod("Close", SaveChanges, Missing.Value, Missing.Value); - } - } - public partial class LBFind - { - public void ReplaceAll() - { - this.Execute(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, - Missing.Value, Missing.Value, Missing.Value, Missing.Value, LBWdReplace.wdReplaceAll, Missing.Value, - Missing.Value, Missing.Value, Missing.Value); - } - } - public partial class LBFontClass : LBComObject - { - public int TextColor - { - get { return (int)GetProperty("Color"); } - set { SetProperty("Color", value); } - } - } - public partial class LBRange : LBComObject - { - public Object get_Information(LBWdInformation info) - { - return GetProperty("Information", info); - } - public LBRange GoTo(LBWdGoToItem What, LBWdGoToDirection Which, int Count) - { - return new LBRange(InvokeMethod("GoTo", What, Which, Count, Missing.Value)); - } - } - public partial class LBSelection : LBComObject - { - public Object get_Information(LBWdInformation info) - { - return GetProperty("Information", info); - } - public int MoveStart(LBWdUnits Unit, int Count) - { - return InvokeMethod("MoveStart", Unit, Count) as int? ?? 0; - } - public int MoveEnd(LBWdUnits Unit, int Count) - { - return InvokeMethod("MoveEnd", Unit, Count) as int? ?? 0; - } - public int EndKey(LBWdUnits Unit, bool Extend) - { - return InvokeMethod("EndKey", Unit, Extend) as int? ?? 0; - } - public bool LastWasUpper - { - get - { - LBRange myRange = Range; - int start = myRange.Start - 1; - while (start >= 0) - { - myRange.Start = start; - myRange.End = start + 1; - string previous = LBDocumentClass.GetRangeText(myRange); - if (Regex.IsMatch(previous, "[A-Z]")) return true; - if (Regex.IsMatch(previous, "[a-z]")) return false; - start = start - 1; - } - return false; - } - } - } - public partial class LBInlineShapes : LBComObjectList /* Collection */ - { - public LBInlineShape AddPicture(string FileName, LBRange Range) - { - return new LBInlineShape(InvokeMethod("AddPicture", FileName, false, true, Range)); - } - } - public partial class LBShapes : LBComObjectList /* Collection */ - { - public LBShape AddPicture(string FileName, float Left, float Top, LBRange Anchor) - { - return new LBShape(InvokeMethod("AddPicture", FileName, false, true, Left, Top, Missing.Value, Missing.Value, Anchor)); - } - public LBShape AddPicture(string FileName, float Left, float Top) - { - return new LBShape(InvokeMethod("AddPicture", FileName, false, true, Left, Top, Missing.Value, Missing.Value, Missing.Value)); - } - } - public enum LBMsoTriState - { - msoCTrue = 1, - msoFalse = 0, - msoTriStateMixed = -2, - msoTriStateToggle = -3, - msoTrue = -1 - } - //public partial class ProcessKiller - //{ - // System.Diagnostics.Process _MyProcess; - // private bool _Exited = false; - // public ProcessKiller(System.Diagnostics.Process myProcess) - // { - // _MyProcess = myProcess; - // _MyProcess.Exited += new EventHandler(_MyProcess_Exited); - // _MyProcess.Kill(); - // DateTime next = DateTime.Now.AddMilliseconds(200); - // while (DateTime.Now < next) - // Application.DoEvents(); - // while (!_Exited) - // Application.DoEvents(); - // } - // void _MyProcess_Exited(object sender, EventArgs e) - // { - // Console.WriteLine("Exited"); - // _Exited = true; - // } - //} + /// + /// Checks to see if the document contains symbol characters + /// + /// + public bool HasSymbolCharacters + { + get + { + LBRange myRange = Range(); + myRange = myRange.GoTo(LBWdGoToItem.wdGoToPercent, LBWdGoToDirection.wdGoToLast, 100); + myRange.Start = 0; + int end = myRange.End; + string myText = GetRangeText(myRange); + MatchCollection problems = _RegFindSymbol.Matches(myText); + int offset = 0; + foreach (Match problem in problems) + { + myRange.Start = problem.Index + offset; + myRange.End = problem.Index + problem.Length + offset; + int newOffset = FindRangeOffset(myRange, problem, offset, end); + if (IsSymbolFont(myRange.Font.Name)) + { + Console.WriteLine("Font '{0}' has Symbols", myRange.Font.Name); + } + else + return true; + offset = newOffset; + } + return false; + } + } + readonly Regex _RegFindSymbol = new Regex("[\\uF020-\\uF07F]+"); + + /// + /// Get the Range Text with error handling. myRange.Text sometimes will get a null reference exception. + /// + /// + /// + internal static string GetRangeText(LBRange myRange) + { + string text = ""; + try + { + if (myRange.Start == myRange.End)// If Start and End equal return an empty string. + text = ""; + else + text = myRange.Text; + } + catch (Exception ex) + { + Console.WriteLine("GetRangeText {0} - {1}", ex.GetType().Name, ex.Message); + } + return text; + } + /// + /// Looks for the problem string and adjusts the range as necessary + /// + /// + /// + /// + /// + /// + private int FindRangeOffset(LBRange myRange, Match problem, int offset, int end) + { + // try to find the string + string text = GetRangeText(myRange); + if (text != problem.Value) + { + // Get the entire text starting at the offset of the first match + myRange.Start = problem.Index + offset; + myRange.End = end; + text = GetRangeText(myRange); + while (!text.StartsWith(problem.Value)) + { + int newStart = text.IndexOf(problem.Value);// Find the string if it is not at the beginning + myRange.Start += myRange.Start == newStart ? newStart + 1 : newStart; // adjust the starting location + text = GetRangeText(myRange);// get the text to check + } + myRange.End = myRange.Start + problem.Length; // assume that the end should be the start plus the length + text = GetRangeText(myRange); + while (text.Length < problem.Length) // If the result is too short increase the length + { + myRange.End += (problem.Length - text.Length); + text = GetRangeText(myRange); + } + } + return myRange.Start - problem.Index; + } + /// + /// ReplaceSymbolCharacters processes the string returned and changes any symbols (0xF0??) to normal characters + /// + /// + /// + private static string ReplaceSymbolCharacters(string str) + { + StringBuilder results = new StringBuilder(); + foreach (char c in str) + { + if ((c & 0xFF00) == 0xF000) + results.Append((char)(c & 0xFF)); + else + results.Append((char)(c)); + } + return results.ToString(); + } + /// + /// Close the document + /// + /// Save Changes + public void Close(bool SaveChanges) => InvokeMethod("Close", SaveChanges, Missing.Value, Missing.Value); + } + public partial class LBFind + { + public void ReplaceAll() + { + this.Execute(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, + Missing.Value, Missing.Value, Missing.Value, Missing.Value, LBWdReplace.wdReplaceAll, Missing.Value, + Missing.Value, Missing.Value, Missing.Value); + } + } + public partial class LBFontClass : LBComObject + { + public int TextColor + { + get { return (int)GetProperty("Color"); } + set { SetProperty("Color", value); } + } + } + public partial class LBRange : LBComObject + { + public object get_Information(LBWdInformation info) => GetProperty("Information", info); + public LBRange GoTo(LBWdGoToItem What, LBWdGoToDirection Which, int Count) => new LBRange(InvokeMethod("GoTo", What, Which, Count, Missing.Value)); + } + public partial class LBSelection : LBComObject + { + public object get_Information(LBWdInformation info) => GetProperty("Information", info); + public int MoveStart(LBWdUnits Unit, int Count) => InvokeMethod("MoveStart", Unit, Count) as int? ?? 0; + public int MoveEnd(LBWdUnits Unit, int Count) => InvokeMethod("MoveEnd", Unit, Count) as int? ?? 0; + public int EndKey(LBWdUnits Unit, bool Extend) => InvokeMethod("EndKey", Unit, Extend) as int? ?? 0; + public bool LastWasUpper + { + get + { + LBRange myRange = Range; + int start = myRange.Start - 1; + while (start >= 0) + { + myRange.Start = start; + myRange.End = start + 1; + string previous = LBDocumentClass.GetRangeText(myRange); + if (Regex.IsMatch(previous, "[A-Z]")) return true; + if (Regex.IsMatch(previous, "[a-z]")) return false; + start--; + } + return false; + } + } + } + public partial class LBInlineShapes : LBComObjectList /* Collection */ + { + public LBInlineShape AddPicture(string FileName, LBRange Range) => new LBInlineShape(InvokeMethod("AddPicture", FileName, false, true, Range)); + } + public partial class LBShapes : LBComObjectList /* Collection */ + { + public LBShape AddPicture(string FileName, float Left, float Top, LBRange Anchor) => new LBShape(InvokeMethod("AddPicture", FileName, false, true, Left, Top, Missing.Value, Missing.Value, Anchor)); + public LBShape AddPicture(string FileName, float Left, float Top) => new LBShape(InvokeMethod("AddPicture", FileName, false, true, Left, Top, Missing.Value, Missing.Value, Missing.Value)); + } + public enum LBMsoTriState + { + msoCTrue = 1, + msoFalse = 0, + msoTriStateMixed = -2, + msoTriStateToggle = -3, + msoTrue = -1 + } } diff --git a/PROMS/LBWordLibrary/LBWordLibrary.csproj b/PROMS/LBWordLibrary/LBWordLibrary.csproj index 8164fb19..577c35e5 100644 --- a/PROMS/LBWordLibrary/LBWordLibrary.csproj +++ b/PROMS/LBWordLibrary/LBWordLibrary.csproj @@ -79,6 +79,7 @@ + diff --git a/PROMS/LBWordLibrary/OutlookLBComObject.cs b/PROMS/LBWordLibrary/OutlookLBComObject.cs index c459dcdc..ac2bdacc 100644 --- a/PROMS/LBWordLibrary/OutlookLBComObject.cs +++ b/PROMS/LBWordLibrary/OutlookLBComObject.cs @@ -1,64 +1,45 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Reflection; namespace LBOutlookLibrary { public abstract partial class LBComObject { - private Object _Item; - internal Object Item + private object _Item; + internal object Item { get { return _Item; } set { _Item = value; - if (value != null) _MyType = _Item.GetType(); + if (value != null) MyType = _Item.GetType(); } } - private Type _MyType; - public Type MyType - { - get { return _MyType; } - set { _MyType = value; } - } - protected LBComObject() { } + + public Type MyType { get; set; } + protected LBComObject() { } protected LBComObject(string ProgID) { Type objClassType; objClassType = Type.GetTypeFromProgID(ProgID); Item = Activator.CreateInstance(objClassType); } - protected LBComObject(Object item) - { - Item = item; - } - private Object DoInvokeMember(string name, Object[] parameters, BindingFlags bf, Binder b) + protected LBComObject(object item) => Item = item; + private object DoInvokeMember(string name, object[] parameters, BindingFlags bf, Binder b) { try { - return _MyType.InvokeMember(name, bf, b, _Item, parameters); + return MyType.InvokeMember(name, bf, b, _Item, parameters); } catch (Exception ex) { - throw new Exception(string.Format("LBComObject.DoInvokeMember {0}.{1}", _MyType.Name, name), ex); + throw new Exception(string.Format("LBComObject.DoInvokeMember {0}.{1}", MyType.Name, name), ex); } - return null; } - protected void SetProperty(string propertyName, params Object[] parameters) - { - DoInvokeMember(propertyName, parameters, BindingFlags.SetProperty, null); - } - protected Object GetProperty(string propertyName) - { - return DoInvokeMember(propertyName, null, BindingFlags.GetProperty, null); - } - protected Object GetProperty(string propertyName, params Object[] parameters) - { - return DoInvokeMember(propertyName, parameters, BindingFlags.GetProperty, null); - } - protected Object InvokeMethod(string methodName, params Object[] parameters) + protected void SetProperty(string propertyName, params object[] parameters) => DoInvokeMember(propertyName, parameters, BindingFlags.SetProperty, null); + protected object GetProperty(string propertyName) => DoInvokeMember(propertyName, null, BindingFlags.GetProperty, null); + protected object GetProperty(string propertyName, params object[] parameters) => DoInvokeMember(propertyName, parameters, BindingFlags.GetProperty, null); + protected object InvokeMethod(string methodName, params object[] parameters) { if (parameters != null) FixParameters(parameters); @@ -71,45 +52,15 @@ namespace LBOutlookLibrary if (parameters[i] is LBComObject) parameters[i] = (parameters[i] as LBComObject).Item; } - protected Object InvokeMethod(string methodName) - { - return InvokeMethod(methodName, null); - } - } - public class LBComObjectList : LBComObject - where TList : LBComObjectList - where TItem : LBComObject, new() - { - //public new(Object item):base(item){} - public TItem Add() - { - TItem tmp = new TItem(); - tmp.Item = InvokeMethod("Add"); - return tmp; - } - //public TItem this[int item] - //{ - // get - // { - // TItem tmp = new TItem(); - // tmp.Item = GetProperty("Item", item); - // return tmp; - // } - //} - } + protected object InvokeMethod(string methodName) => InvokeMethod(methodName, null); + } public partial class LBApplicationClass : LBComObject { public LBApplicationClass() : base("Outlook.Application") { } - public LBApplicationClass(Object item) : base(item) { } - public System.Object CreateItem(LBOlItemType ItemType) - { - return InvokeMethod("CreateItem", ItemType); - } - public void Quit() - { - InvokeMethod("Quit"); - } - } + public LBApplicationClass(object item) : base(item) { } + public object CreateItem(LBOlItemType ItemType) => InvokeMethod("CreateItem", ItemType); + public void Quit() => InvokeMethod("Quit"); + } public enum LBOlItemType { olMailItem = 0, @@ -124,13 +75,13 @@ namespace LBOutlookLibrary public partial class LBMailItem : LBComObject { public LBMailItem() { } - public LBMailItem(Object item) : base(item) { } + public LBMailItem(object item) : base(item) { } } public partial class LBMailItemClass : LBComObject { public LBMailItemClass() { } - public LBMailItemClass(Object item) : base(item) { } - public String Body + public LBMailItemClass(object item) : base(item) { } + public string Body { get { return (GetProperty("Body").ToString()); } set { SetProperty("Body", value); } @@ -140,29 +91,20 @@ namespace LBOutlookLibrary get { return (LBOlBodyFormat)GetProperty("BodyFormat"); } set { SetProperty("BodyFormat", value); } } - public LBAttachments Attachments - { - get { return new LBAttachments(GetProperty("Attachments")); } - } - public String Subject + public LBAttachments Attachments => new LBAttachments(GetProperty("Attachments")); + public string Subject { get { return (GetProperty("Subject").ToString()); } set { SetProperty("Subject", value); } } - public LBRecipients Recipients - { - get { return new LBRecipients(GetProperty("Recipients")); } - } - public String To + public LBRecipients Recipients => new LBRecipients(GetProperty("Recipients")); + public string To { get { return (GetProperty("To").ToString()); } set { SetProperty("To", value); } } - public void Send() - { - InvokeMethod("Send"); - } - } + public void Send() => InvokeMethod("Send"); + } public enum LBOlBodyFormat { olFormatUnspecified = 0, @@ -173,79 +115,40 @@ namespace LBOutlookLibrary public partial class LBAttachments : LBComObject { public LBAttachments() { } - public LBAttachments(Object item) : base(item) { } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public LBAttachment Item - { - get { return new LBAttachment(GetProperty("Item")); } - } - public LBAttachment Add(object Source) - { - return new LBAttachment(InvokeMethod("Add", Source, Missing.Value, Missing.Value, Missing.Value)); - } - public LBAttachment Add(object Source, object Type, object Position, object DisplayName) + public LBAttachments(object item) : base(item) { } + public int Count => (GetProperty("Count") as int? ?? 0); + public new LBAttachment Item => new LBAttachment(GetProperty("Item")); + public LBAttachment Add(object Source) => new LBAttachment(InvokeMethod("Add", Source, Missing.Value, Missing.Value, Missing.Value)); + public LBAttachment Add(object Source, object Type, object Position, object DisplayName) { return new LBAttachment(InvokeMethod("Add", Source, Type, Position, DisplayName)); } - public void Remove(int Index) - { - InvokeMethod("Remove", Index); - } - } + public void Remove(int Index) => InvokeMethod("Remove", Index); + } public partial class LBRecipients : LBComObject { public LBRecipients() { } - public LBRecipients(Object item) : base(item) { } - public int Count - { - get { return (GetProperty("Count") as int? ?? 0); } - } - public LBRecipient Item - { - get { return new LBRecipient(GetProperty("Item")); } - } - public LBRecipient Add(string Name) - { - return new LBRecipient(InvokeMethod("Add", Name)); - } - public void Remove(int Index) - { - InvokeMethod("Remove", Index); - } - public Boolean ResolveAll() - { - return InvokeMethod("ResolveAll") as Boolean? ?? false; - } - } + public LBRecipients(object item) : base(item) { } + public int Count => (GetProperty("Count") as int? ?? 0); + public new LBRecipient Item => new LBRecipient(GetProperty("Item")); + public LBRecipient Add(string Name) => new LBRecipient(InvokeMethod("Add", Name)); + public void Remove(int Index) => InvokeMethod("Remove", Index); + public bool ResolveAll() => InvokeMethod("ResolveAll") as bool? ?? false; + } public partial class LBAttachment : LBComObject { public LBAttachment() { } - public LBAttachment(Object item) : base(item) { } - public LBOlAttachmentType Type - { - get { return (LBOlAttachmentType)GetProperty("Type"); } - } - } + public LBAttachment(object item) : base(item) { } + public LBOlAttachmentType Type => (LBOlAttachmentType)GetProperty("Type"); + } public partial class LBRecipient : LBComObject { public LBRecipient() { } - public LBRecipient(Object item) : base(item) { } - public String Address - { - get { return (GetProperty("Address").ToString()); } - } - public String Name - { - get { return (GetProperty("Name").ToString()); } - } - public Boolean Resolve() - { - return InvokeMethod("Resolve") as Boolean? ?? false; - } - } + public LBRecipient(object item) : base(item) { } + public string Address => (GetProperty("Address").ToString()); + public string Name => (GetProperty("Name").ToString()); + public bool Resolve() => InvokeMethod("Resolve") as bool? ?? false; + } public enum LBOlAttachmentType { olByValue = 1, diff --git a/PROMS/LBWordLibrary/OutlookLBComObjectExt.cs b/PROMS/LBWordLibrary/OutlookLBComObjectExt.cs index 20bd38c1..4cfda7fe 100644 --- a/PROMS/LBWordLibrary/OutlookLBComObjectExt.cs +++ b/PROMS/LBWordLibrary/OutlookLBComObjectExt.cs @@ -1,21 +1,13 @@ using System; -using System.Collections.Generic; -using System.Text; namespace LBOutlookLibrary { public partial class LBApplicationClass { - public LBMailItemClass CreateMailItem() - { - return new LBMailItemClass(CreateItem(LBOlItemType.olMailItem)); - } - } + public LBMailItemClass CreateMailItem() => new LBMailItemClass(CreateItem(LBOlItemType.olMailItem)); + } public partial class LBMailItemClass { - public void AddAttachment(string filename) - { - Attachments.Add(filename, LBOlAttachmentType.olByValue, Type.Missing, Type.Missing); - } - } + public void AddAttachment(string filename) => Attachments.Add(filename, LBOlAttachmentType.olByValue, Type.Missing, Type.Missing); + } } diff --git a/PROMS/LBWordLibrary/RegHive.cs b/PROMS/LBWordLibrary/RegHive.cs index f4bb27b0..cd0a5991 100644 --- a/PROMS/LBWordLibrary/RegHive.cs +++ b/PROMS/LBWordLibrary/RegHive.cs @@ -49,19 +49,13 @@ namespace Read64bitRegistryFrom32bitApp ref uint lpType, System.Text.StringBuilder lpData, ref uint lpcbData); - #endregion - #endregion + #endregion + #endregion - #region Functions - static public string GetRegKey64Value(UIntPtr inHive, String inKeyName, String inPropertyName) - { - return GetRegKey64Value(inHive, inKeyName, RegSAM.WOW64_64Key, inPropertyName); - } - static public string GetRegKey32Value(UIntPtr inHive, String inKeyName, String inPropertyName) - { - return GetRegKey64Value(inHive, inKeyName, RegSAM.WOW64_32Key, inPropertyName); - } - static public string GetRegKey64Value(UIntPtr inHive, String inKeyName, RegSAM in32or64key, String inPropertyName) + #region Functions + static public string GetRegKey64Value(UIntPtr inHive, string inKeyName, string inPropertyName) => GetRegKey64Value(inHive, inKeyName, RegSAM.WOW64_64Key, inPropertyName); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "inHive kept to match dll signature")] + static public string GetRegKey64Value(UIntPtr inHive, string inKeyName, RegSAM in32or64key, string inPropertyName) { int hkey = 0; try @@ -80,15 +74,10 @@ namespace Read64bitRegistryFrom32bitApp if (0 != hkey) RegCloseKey(hkey); } } - static public bool CheckRegKey64Valid(UIntPtr inHive, String inKeyName) - { - return CheckRegKey64Valid(inHive, inKeyName, RegSAM.WOW64_64Key); - } - static public bool GetRegKey32Valid(UIntPtr inHive, String inKeyName) - { - return CheckRegKey64Valid(inHive, inKeyName, RegSAM.WOW64_32Key); - } - static public bool CheckRegKey64Valid(UIntPtr inHive, String inKeyName, RegSAM in32or64key) + static public bool CheckRegKey64Valid(UIntPtr inHive, string inKeyName) => CheckRegKey64Valid(inHive, inKeyName, RegSAM.WOW64_64Key); + static public bool GetRegKey32Valid(UIntPtr inHive, string inKeyName) => CheckRegKey64Valid(inHive, inKeyName, RegSAM.WOW64_32Key); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "inHive kept to match dll signature")] + static public bool CheckRegKey64Valid(UIntPtr inHive, string inKeyName, RegSAM in32or64key) { int hkey = 0; try @@ -103,8 +92,5 @@ namespace Read64bitRegistryFrom32bitApp } } #endregion - - #region Enums - #endregion } } \ No newline at end of file diff --git a/PROMS/ReferencedObjects/LibSource/RODBInterface/SqlRODB.cs b/PROMS/ReferencedObjects/LibSource/RODBInterface/SqlRODB.cs index fb03f1d2..8c654004 100644 --- a/PROMS/ReferencedObjects/LibSource/RODBInterface/SqlRODB.cs +++ b/PROMS/ReferencedObjects/LibSource/RODBInterface/SqlRODB.cs @@ -50,7 +50,7 @@ namespace RODBInterface SqlConnection cn = new SqlConnection(SqlConnectionStr); try { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); if (OnlyConnectOnce && ROAPP_SqlConnectionOnce == null) ROAPP_SqlConnectionOnce = cn; return cn; } diff --git a/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusBarFrm.cs b/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusBarFrm.cs index 6828458b..580fc949 100644 --- a/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusBarFrm.cs +++ b/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusBarFrm.cs @@ -19,11 +19,6 @@ *********************************************************************************************/ using System; -using System.Drawing; -using System.Collections; -using System.ComponentModel; -using System.Windows.Forms; -//using ROProfiler; //don't forget to add VlnProfiler to the reference list namespace VlnStatus { @@ -35,11 +30,6 @@ namespace VlnStatus private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Label lblBar; private System.Windows.Forms.Label StatMsg; -// private string strLblLast=""; - /// - /// Required designer variable. - /// - private System.ComponentModel.Container components = null; public StatusBarFrm() { @@ -61,21 +51,6 @@ namespace VlnStatus Text = StatusBoxTitle; } - /// - /// Clean up any resources being used. - /// - protected override void Dispose( bool disposing ) - { - if( disposing ) - { - if(components != null) - { - components.Dispose(); - } - } - base.Dispose( disposing ); - } - #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify @@ -190,14 +165,6 @@ namespace VlnStatus { lblBar.Text = (Math.Round((decimal)(progressBar1.Value * 100) / progressBar1.Maximum)).ToString(); lblBar.Text += "% Complete"; -// if( lblBar.Text != strLblLast) -// { -// Profiler.Start("UpdateLabel"); - lblBar.Refresh(); -// lblBar.Update(); -// Profiler.End("UpdateLabel"); -// } -// strLblLast = lblBar.Text; } public string StatusMessage @@ -209,10 +176,7 @@ namespace VlnStatus set { StatMsg.Text = value; -// Profiler.Start("StatusMessage"); StatMsg.Refresh(); -// StatMsg.Update(); -// Profiler.End("StatusMessage"); } } diff --git a/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusMessageFrm.cs b/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusMessageFrm.cs index 386d145c..c983a868 100644 --- a/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusMessageFrm.cs +++ b/PROMS/ReferencedObjects/LibSource/VlnStatus/StatusMessageFrm.cs @@ -17,12 +17,6 @@ * Added overbounds check *********************************************************************************************/ -using System; -using System.Drawing; -using System.Collections; -using System.ComponentModel; -using System.Windows.Forms; - namespace VlnStatus { /// @@ -31,10 +25,6 @@ namespace VlnStatus public class StatusMessageFrm : System.Windows.Forms.Form { private System.Windows.Forms.Label lblStatMsg; - /// - /// Required designer variable. - /// - private System.ComponentModel.Container components = null; public StatusMessageFrm() { @@ -54,21 +44,6 @@ namespace VlnStatus Text = StatTitle; } - /// - /// Clean up any resources being used. - /// - protected override void Dispose( bool disposing ) - { - if( disposing ) - { - if(components != null) - { - components.Dispose(); - } - } - base.Dispose( disposing ); - } - #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify diff --git a/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusBar.cs b/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusBar.cs index a7a4e2cd..ac47b954 100644 --- a/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusBar.cs +++ b/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusBar.cs @@ -33,7 +33,7 @@ namespace VlnStatus /// public class VlnStatusBar { - StatusBarFrm StatBar; + readonly StatusBarFrm StatBar; private int Cnt; // Create a status window with the default title of "Status" @@ -53,8 +53,6 @@ namespace VlnStatus // Increament the the status bar by the passed in value. public void PerformStep(int val) { -// StatBar.Value = val; -// Cnt = val; BarValue = val; StatBar.PerformStep(); } @@ -62,7 +60,6 @@ namespace VlnStatus // Increament the the status bar by one public void PerformStep() { -// StatBar.Value = StatBar.Value + 1; Cnt++; BarValue = Cnt; StatBar.PerformStep(); diff --git a/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusMessage.cs b/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusMessage.cs index e0221ee8..ff26ca8c 100644 --- a/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusMessage.cs +++ b/PROMS/ReferencedObjects/LibSource/VlnStatus/VlnStatusMessage.cs @@ -13,8 +13,6 @@ * Added overbounds check *********************************************************************************************/ -using System; - namespace VlnStatus { /// @@ -28,7 +26,7 @@ namespace VlnStatus /// public class VlnStatusMessage { - StatusMessageFrm StatusMessageBox; + readonly StatusMessageFrm StatusMessageBox; // Create a status window with the default title of "Status" public VlnStatusMessage() diff --git a/PROMS/RoAccessToSql/GlobalSuppressions.cs b/PROMS/RoAccessToSql/GlobalSuppressions.cs new file mode 100644 index 00000000..6c4a515e --- /dev/null +++ b/PROMS/RoAccessToSql/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")] \ No newline at end of file diff --git a/PROMS/RoAccessToSql/Program.cs b/PROMS/RoAccessToSql/Program.cs index 20a37fc6..e73cb61f 100644 --- a/PROMS/RoAccessToSql/Program.cs +++ b/PROMS/RoAccessToSql/Program.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using System.Windows.Forms; namespace RoAccessToSql diff --git a/PROMS/RoAccessToSql/RoAccessToSql.cs b/PROMS/RoAccessToSql/RoAccessToSql.cs index afe5a3ae..a44589c1 100644 --- a/PROMS/RoAccessToSql/RoAccessToSql.cs +++ b/PROMS/RoAccessToSql/RoAccessToSql.cs @@ -1,16 +1,10 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Data; using System.IO; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.Data.OleDb; -using Volian.Base.Library; [assembly: log4net.Config.XmlConfigurator(Watch = true)] @@ -33,25 +27,11 @@ namespace RoAccessToSql public partial class RoAccessToSql : Form { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private string _MSAccessPath = null; - public string MSAccessPath - { - get { return _MSAccessPath; } - set { _MSAccessPath = value; } - } - private string _SqlServerName = null; - public string SqlServerName - { - get { return _SqlServerName; } - set { _SqlServerName = value; } - } - private string _SqlDatabaseName = null; - public string SqlDatabaseName - { - get { return _SqlDatabaseName; } - set { _SqlDatabaseName = value; } - } - bool _Initializing = false; + + public string MSAccessPath { get; set; } = null; + public string SqlServerName { get; set; } = null; + public string SqlDatabaseName { get; set; } = null; + readonly bool _Initializing = false; public RoAccessToSql(string[] args) { @@ -66,7 +46,7 @@ namespace RoAccessToSql } else if (parm.StartsWith("/sqldb=")) { - SqlDatabaseName = parm.Substring(7) + "_RO"; + SqlDatabaseName = $"{parm.Substring(7)}_RO"; } else if (parm.StartsWith("/server=")) { @@ -92,7 +72,7 @@ namespace RoAccessToSql if (UserInRoEditor()) this.Close(); tbSqlDbName.Text = SqlDatabaseName; _TmpFileForConnectStr = Path.GetTempPath(); - _TmpFileForConnectStr = _TmpFileForConnectStr + @"\PromsConnect.txt"; + _TmpFileForConnectStr += @"\PromsConnect.txt"; File.Delete(_TmpFileForConnectStr); _Initializing = false; } @@ -100,10 +80,10 @@ namespace RoAccessToSql private bool UserInRoEditor() { FileInfo fiown = null; - FileStream fsown = null; - // The following code was taken from the roeditor. It uses the 'RoEditor.own' file to assure that - // no one is in the roeditor. This file is located in the microsoft access database directory. - try + FileStream fsown; + // The following code was taken from the roeditor. It uses the 'RoEditor.own' file to assure that + // no one is in the roeditor. This file is located in the microsoft access database directory. + try { string filename = MSAccessPath + @"\RoEditor.own"; fiown = new FileInfo(filename); @@ -119,7 +99,7 @@ namespace RoAccessToSql fsown = fiown.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); TextReader tr1 = new StreamReader(fsown); string who1 = tr1.ReadToEnd(); - MessageBox.Show(ex.Message + "\r\n\r\n" + who1, "RO Editor In Use", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show($"{ex.Message}\r\n\r\n{who1}", "RO Editor In Use", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } fsown = fiown.Open(FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); TextReader tr = new StreamReader(fsown); @@ -142,8 +122,8 @@ namespace RoAccessToSql tw.WriteLine("Current User: {0}, Date and Time Started: {1}", Environment.UserName.ToUpper(), DateTime.Now.ToString("MM/dd/yyyy @ hh:mm")); tw.Flush(); } - catch (IOException ex) - { + catch (IOException) + { fsown = fiown.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); TextReader tr = new StreamReader(fsown); string who = tr.ReadToEnd(); @@ -154,25 +134,20 @@ namespace RoAccessToSql } return false; } - static string _ErrorLogFileName; - public static string ErrorLogFileName - { - get { return _ErrorLogFileName; } - set { _ErrorLogFileName = value; } - } - // make error log file name (uses same logic as proms error log) - static bool ChangeLogFileName(string AppenderName, string NewFilename) + + public static string ErrorLogFileName { get; set; } + // make error log file name (uses same logic as proms error log) + static bool ChangeLogFileName(string AppenderName, string NewFilename) { log4net.Repository.ILoggerRepository RootRep; RootRep = log4net.LogManager.GetRepository(); foreach (log4net.Appender.IAppender iApp in RootRep.GetAppenders()) { if (iApp.Name.CompareTo(AppenderName) == 0 - && iApp is log4net.Appender.FileAppender) - { - log4net.Appender.FileAppender fApp = (log4net.Appender.FileAppender)iApp; + && iApp is log4net.Appender.FileAppender fApp) + { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - fApp.File = folderPath + @"\VEPROMS\" + (Volian.Base.Library.VlnSettings.GetCommand("prefix", "") + "_").TrimStart("_".ToCharArray()) + NewFilename; + fApp.File = $@"{folderPath}\VEPROMS\{($"{Volian.Base.Library.VlnSettings.GetCommand("prefix", "")}_").TrimStart("_".ToCharArray())}{NewFilename}"; ErrorLogFileName = fApp.File; fApp.ActivateOptions(); return true; @@ -189,7 +164,7 @@ namespace RoAccessToSql if (Directory.Exists(fbd.SelectedPath)) tbAccessPath.Text = fbd.SelectedPath; else - MessageBox.Show("Path doesn't exist " + tbAccessPath.Text); + MessageBox.Show($"Path doesn't exist {tbAccessPath.Text}"); } } // Convert the data @@ -212,7 +187,7 @@ namespace RoAccessToSql { DateTime dtSunday = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek)); - ChangeLogFileName("LogFileAppender", SqlDatabaseName + " " + dtSunday.ToString("yyyyMMdd") + " ErrorLog.txt"); + ChangeLogFileName("LogFileAppender", $"{SqlDatabaseName} {dtSunday:yyyyMMdd} ErrorLog.txt"); _MyLog.InfoFormat("\r\nSession Beginning\r\n<===={0}[SQL:{1:yyMM.ddHH}]====== User: {2}/{3} Started {4} ===============>{5}" , Application.ProductVersion, RevDate, DateTime.Now, Environment.UserDomainName, Environment.UserName, DateTime.Now.ToString("dddd MMMM d, yyyy h:mm:ss tt"), ""); } @@ -229,7 +204,7 @@ namespace RoAccessToSql if (sqlConnection.State == ConnectionState.Open) { // now try to open access db: - string strDatabaseConnectionCommand = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=" + MSAccessPath + "\\ROMaster.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"; + string strDatabaseConnectionCommand = $"Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source={MSAccessPath}\\ROMaster.mdb;Mode=Share Deny None;Extended Properties=\"\";Jet OLEDB:System database=\"\";Jet OLEDB:Registry Path=\"\";Jet OLEDB:Database Password=\"\";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"; using (OleDbConnection accessConnection = new OleDbConnection(strDatabaseConnectionCommand)) { try @@ -251,13 +226,13 @@ namespace RoAccessToSql } else { - _MyLog.Error("SQL Connection is not open. Check connection string: " + tbSqlDbName.Text); - MessageBox.Show("Check connection string: " + tbSqlDbName.Text, "SQL Connection is not open."); + _MyLog.Error($"SQL Connection is not open. Check connection string: {tbSqlDbName.Text}"); + MessageBox.Show($"Check connection string: {tbSqlDbName.Text}", "SQL Connection is not open."); } } catch (SqlException ex) { - _MyLog.Error("SQL Connection is not open. Check connection string: " + tbSqlDbName.Text); + _MyLog.Error($"SQL Connection is not open. Check connection string: {tbSqlDbName.Text}"); MessageBox.Show(ex.Message, "Unknown error when migrating RO data from MS Access to SQL"); } } @@ -274,11 +249,10 @@ namespace RoAccessToSql lastTimeDbs = ProgressBarUpdate(pBarDbs, null, 0, 1, 0, 0, lastTimeDbs, false); lastTimeRos = ProgressBarUpdate(pBarROs, null, 0, maxCntRo, 0, 0, lastTimeRos, false); lastTimeDbs = ProgressBarUpdate(pBarDbs, "ROMaster Table", 0, 5, 0, 1, lastTimeDbs, false); - OleDbDataReader reader = null; - OleDbCommand command = new OleDbCommand("select * from ROMaster", accessConnection); - reader = command.ExecuteReader(); - // Do access's romaster table first so that the list of other tables to process is found. While doing this, migrate this table's data. - int cntRo = 0; + OleDbCommand command = new OleDbCommand("select * from ROMaster", accessConnection); + OleDbDataReader reader = command.ExecuteReader(); + // Do access's romaster table first so that the list of other tables to process is found. While doing this, migrate this table's data. + int cntRo = 0; int cntDb = 0; int maxCntDb = 0; while (reader.Read()) // reading from Access Database @@ -303,13 +277,12 @@ namespace RoAccessToSql maxCntDb++; } } - lastTimeRos = ProgressBarUpdate(pBarROs, "ROMaster", 0, maxCntRo, maxCntRo, 1, lastTimeRos, true); + ProgressBarUpdate(pBarROs, "ROMaster", 0, maxCntRo, maxCntRo, 1, lastTimeRos, true); lastTimeDbs = ProgressBarUpdate(pBarDbs, null, 0, maxCntDb, 0, 0, lastTimeDbs, false); reader.Close(); - reader = null; - - // now migrate all the tables that were found - foreach (string tableName in allTables) + + // now migrate all the tables that were found + foreach (string tableName in allTables) { lastTimeRos = DateTime.Now; cntRo = 0; @@ -318,7 +291,7 @@ namespace RoAccessToSql lastTimeRos = ProgressBarUpdate(pBarROs, null, 0, maxCntRo, 0, 0, lastTimeRos, true); lastTimeDbs = ProgressBarUpdate(pBarDbs, allTablesText[cntDb], 0, maxCntDb, cntDb, 1, lastTimeDbs, false); command = null; - command = new OleDbCommand("select * from " + tableName, accessConnection); + command = new OleDbCommand($"select * from {tableName}", accessConnection); reader = command.ExecuteReader(); while (reader.Read()) // read all of the records from the current access table { @@ -338,7 +311,7 @@ namespace RoAccessToSql reader = null; lastTimeRos = ProgressBarUpdate(pBarROs, tableName, 0, maxCntRo, maxCntRo, 1, lastTimeRos, false); } - lastTimeDbs = ProgressBarUpdate(pBarDbs, allTablesText[maxCntDb - 1], 0, maxCntDb, maxCntDb, 1, lastTimeDbs, false); + ProgressBarUpdate(pBarDbs, allTablesText[maxCntDb - 1], 0, maxCntDb, maxCntDb, 1, lastTimeDbs, false); pBarDbs.Text = "Referenced Object Tables Migration Completed"; pBarROs.Text = "Referenced Objects Migration Completed"; btnConvert.Enabled = false; @@ -357,7 +330,7 @@ namespace RoAccessToSql string dt = string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now); string strInsert = "INSERT INTO ROMaster (RecID, RecType, ModDateTime, Info) "; // note that '8' for rectype flags database converted: - strInsert = strInsert + " VALUES ('09999999', 8, '" + dt + "', '" + _SqlConnectStr + "');"; + strInsert = $"{strInsert} VALUES ('09999999', 8, '{dt}', '{_SqlConnectStr}');"; OleDbCommand command = new OleDbCommand(strInsert, accessConnection); reader = command.ExecuteReader(); if (reader.Read()) return; @@ -367,7 +340,7 @@ namespace RoAccessToSql MessageBox.Show(e.Message, "Error on insert to flag migration completed"); } } - private string _TmpFileForConnectStr = null; + private readonly string _TmpFileForConnectStr = null; private void WriteSqlPathToTempFile() { System.IO.File.WriteAllText(_TmpFileForConnectStr, _SqlConnectStr); @@ -375,13 +348,12 @@ namespace RoAccessToSql // the following is used to update the progress bars, it finds how many records are in a table. private int GetRecordCountForTable(string tableName, OleDbConnection accessConnection) { - OleDbDataReader reader = null; - int retcnt = 100; + int retcnt = 100; try { - OleDbCommand command = new OleDbCommand("SELECT COUNT (RecID) as cnt FROM " + tableName, accessConnection); - reader = command.ExecuteReader(); - if (reader.Read()) + OleDbCommand command = new OleDbCommand($"SELECT COUNT (RecID) as cnt FROM {tableName}", accessConnection); + OleDbDataReader reader = command.ExecuteReader(); + if (reader.Read()) { retcnt = reader.GetInt32(0); } @@ -393,7 +365,8 @@ namespace RoAccessToSql } return retcnt; } - DateTime ProgressBarUpdate(DevComponents.DotNetBar.Controls.ProgressBarX pbi, string msg, int min, int max, int progress, int flag, DateTime lastUpdateDisplay, bool doTimeCheck) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping min for Debugging")] + DateTime ProgressBarUpdate(DevComponents.DotNetBar.Controls.ProgressBarX pbi, string msg, int min, int max, int progress, int flag, DateTime lastUpdateDisplay, bool doTimeCheck) { if (flag == 0) // setup pbi.Maximum = max; @@ -412,11 +385,13 @@ namespace RoAccessToSql { try { - SqlCommand command = new SqlCommand(); - command.Connection = sqlConnection; - command.CommandType = CommandType.StoredProcedure; - command.CommandText = "insertAllRectypes"; - command.Parameters.AddWithValue("@RecType", RecType); + SqlCommand command = new SqlCommand + { + Connection = sqlConnection, + CommandType = CommandType.StoredProcedure, + CommandText = "insertAllRectypes" + }; + command.Parameters.AddWithValue("@RecType", RecType); if (AccPageID == null || AccPageID == "") command.Parameters.AddWithValue("@AccPageID", string.Empty); else @@ -428,9 +403,8 @@ namespace RoAccessToSql command.Parameters.AddWithValue("@ModDateTime", ModDateTime); using (SqlDataReader reader = command.ExecuteReader()) { - bool success = true; - } - command = null; + } + command = null; } catch (Exception ex) { @@ -438,32 +412,15 @@ namespace RoAccessToSql _MyLog.Error(msg, ex); } } - private void btnExit_Click(object sender, EventArgs e) - { - this.Close(); - } - // the user selected the button to test the sql connection string - private void btnTestConnect_Click(object sender, EventArgs e) - { - TestConnection(true); - } - // the RevDate & RevDescription are found in a stored procedure, vesp_GetSQLCodeRevision, in the sql database. These get updated each - // time a revision is made to the sql database using ROFixes.sql script. - private static DateTime _RevDate = DateTime.MinValue; - public static DateTime RevDate - { - get { return _RevDate; } - set { _RevDate = value; } - } - private static string _RevDescription = "Unknown"; - public static string RevDescription - { - get { return _RevDescription; } - set { _RevDescription = value; } - } - // This is called to test the sql connection, either from the button when pressed by user, or from the convert button, before - // the conversion is done. See below for what is checked - private bool TestConnection(bool notifyUser) + private void btnExit_Click(object sender, EventArgs e) => this.Close(); + // the user selected the button to test the sql connection string + private void btnTestConnect_Click(object sender, EventArgs e) => TestConnection(true); + + public static DateTime RevDate { get; set; } = DateTime.MinValue; + public static string RevDescription { get; set; } = "Unknown"; + // This is called to test the sql connection, either from the button when pressed by user, or from the convert button, before + // the conversion is done. See below for what is checked + private bool TestConnection(bool notifyUser) { // The following conditions must be true in order to migrate the ro data to sql. Only the first condition can be // tested in this executable since the roall database is interfaced to by the roeditor & the program that migrates the data. @@ -485,12 +442,14 @@ namespace RoAccessToSql connection.Open(); if (connection.State == ConnectionState.Open) { - // now see if there is an roall table - SqlCommand command = new SqlCommand(); - command.Connection = connection; - command.CommandType = CommandType.Text; - command.CommandText = "(SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ROALL]') AND type in (N'U'))"; - using (SqlDataReader reader = command.ExecuteReader()) + // now see if there is an roall table + SqlCommand command = new SqlCommand + { + Connection = connection, + CommandType = CommandType.Text, + CommandText = "(SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ROALL]') AND type in (N'U'))" + }; + using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { @@ -509,11 +468,13 @@ namespace RoAccessToSql { // now see if there are stored procedures: command = null; // reset command - command = new SqlCommand(); - command.Connection = connection; - command.CommandType = CommandType.Text; - command.CommandText = "(SELECT count(*) FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteByROTable]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)"; - using (SqlDataReader reader = command.ExecuteReader()) + command = new SqlCommand + { + Connection = connection, + CommandType = CommandType.Text, + CommandText = "(SELECT count(*) FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[deleteByROTable]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)" + }; + using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { @@ -533,11 +494,13 @@ namespace RoAccessToSql { // now test that the roall table is empty: command = null; // reset command - command = new SqlCommand(); - command.Connection = connection; - command.CommandType = CommandType.Text; - command.CommandText = "SELECT count(*) FROM roall"; - using (SqlDataReader reader = command.ExecuteReader()) + command = new SqlCommand + { + Connection = connection, + CommandType = CommandType.Text, + CommandText = "SELECT count(*) FROM roall" + }; + using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { @@ -557,16 +520,18 @@ namespace RoAccessToSql { // now test that the database version is ok command = null; // reset command - command = new SqlCommand(); - command.Connection = connection; - command.CommandType = CommandType.StoredProcedure; - command.CommandText = "vesp_GetSQLCodeRevision"; - using (SqlDataReader reader = command.ExecuteReader()) + command = new SqlCommand + { + Connection = connection, + CommandType = CommandType.StoredProcedure, + CommandText = "vesp_GetSQLCodeRevision" + }; + using (SqlDataReader reader = command.ExecuteReader()) { if (reader.Read()) { - _RevDate = reader.GetDateTime(0); - _RevDescription = reader.GetString(1); + RevDate = reader.GetDateTime(0); + RevDescription = reader.GetString(1); dbsuc = true; } else @@ -582,13 +547,13 @@ namespace RoAccessToSql } catch (SqlException ex) { - if (notifyUser) MessageBox.Show("Connection failed: " + ex, "Connection Failed"); + if (notifyUser) MessageBox.Show($"Connection failed: {ex}", "Connection Failed"); } } } catch (Exception ex) { - if (notifyUser) MessageBox.Show("Connection failed: " + ex, "Connection Failed"); + if (notifyUser) MessageBox.Show($"Connection failed: {ex}", "Connection Failed"); } if (notifyUser && success) MessageBox.Show("You have been successfully connected to the database!", "Connection Succeeded"); diff --git a/PROMS/RoAccessToSql/RoAccessToSql.csproj b/PROMS/RoAccessToSql/RoAccessToSql.csproj index d956be8a..99b22330 100644 --- a/PROMS/RoAccessToSql/RoAccessToSql.csproj +++ b/PROMS/RoAccessToSql/RoAccessToSql.csproj @@ -66,6 +66,7 @@ + Form diff --git a/PROMS/TablePicker/TablePicker.cs b/PROMS/TablePicker/TablePicker.cs index 92369edb..551cb53d 100644 --- a/PROMS/TablePicker/TablePicker.cs +++ b/PROMS/TablePicker/TablePicker.cs @@ -1,7 +1,4 @@ -using System; using System.Drawing; -using System.Collections; -using System.ComponentModel; using System.Windows.Forms; namespace Accentra.Controls @@ -11,11 +8,6 @@ namespace Accentra.Controls /// public class TablePicker : System.Windows.Forms.Form { - /// - /// Required designer variable. - /// - private System.ComponentModel.Container components = null; - public TablePicker() { // Activates double buffering @@ -29,21 +21,6 @@ namespace Accentra.Controls InitializeComponent(); } - /// - /// Clean up any resources being used. - /// - protected override void Dispose( bool disposing ) - { - if( disposing ) - { - if(components != null) - { - components.Dispose(); - } - } - base.Dispose( disposing ); - } - #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify @@ -75,82 +52,41 @@ namespace Accentra.Controls } #endregion - private Pen BeigePen = new Pen(Color.Beige, 1); - private Brush BeigeBrush = System.Drawing.Brushes.Beige; - private Brush GrayBrush = System.Drawing.Brushes.Gray; - private Brush BlackBrush = System.Drawing.Brushes.Black; - private Brush WhiteBrush = System.Drawing.Brushes.White; + private readonly Brush BlackBrush = System.Drawing.Brushes.Black; + private readonly Brush WhiteBrush = System.Drawing.Brushes.White; - private Brush Jbrush = System.Drawing.Brushes.LightBlue; - //private Brush Jbrush = System.Drawing.Brushes.LightSteelBlue; - //private Brush Jbrush = System.Drawing.Brushes.SteelBlue; - //private Brush Jbrush = System.Drawing.Brushes.PowderBlue; + private readonly Brush Jbrush = System.Drawing.Brushes.LightBlue; - private Pen BorderPen = new Pen(SystemColors.ControlDark); - private Pen BluePen = new Pen(Color.SlateGray, 1); + private readonly Pen BorderPen = new Pen(SystemColors.ControlDark); + private readonly Pen BluePen = new Pen(Color.SlateGray, 1); private string DispText = "Esc to Cancel"; // Display text - private int DispHeight = 40;//20; // Display ("Table 1x1", "Cancel") - private Font DispFont = new Font("Tahoma", 8.25F); - private int SquareX = 20; // Width of squares - private int SquareY = 20; // Height of squares + private readonly int DispHeight = 40; // Display ("Table 1x1", "Cancel") + private readonly Font DispFont = new Font("Tahoma", 8.25F); + private readonly int SquareX = 20; // Width of squares + private readonly int SquareY = 20; // Height of squares private int SquareQX = 3; // Number of visible squares (X) private int SquareQY = 3; // Number of visible squares (Y) private int SelQX = 1; // Number of selected squares (x) private int SelQY = 1; // Number of selected squares (y) - private bool bHiding = false; - private bool bCancel = true; // Determines whether to Cancel + public int MaxRows { get; set; } = -1; - // Added my Volian 4/27/11 - private int _MaxRows = -1; + public int MaxCols { get; set; } = -1; - public int MaxRows - { - get { return _MaxRows; } - set { _MaxRows = value; } - } - private int _MaxCols = -1; + /// + /// Returns the number of columns, or the horizontal / X count, + /// of the selection. + /// + public int SelectedColumns => SelQX; - public int MaxCols - { - get { return _MaxCols; } - set { _MaxCols = value; } - } + /// + /// Returns the number of rows, or the vertical / Y count, + /// of the selection. + /// + public int SelectedRows => SelQY; - /// - /// Similar to - /// == , - /// but is used as a state value before the form - /// is hidden and cancellation is finalized. - /// - public bool Cancel { - get { - return bCancel; - } - } - - /// - /// Returns the number of columns, or the horizontal / X count, - /// of the selection. - /// - public int SelectedColumns { - get { - return SelQX; - } - } - - /// - /// Returns the number of rows, or the vertical / Y count, - /// of the selection. - /// - public int SelectedRows { - get { - return SelQY; - } - } - - private void TablePicker_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { + private void TablePicker_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; // First, increment the number of visible squares if the @@ -162,8 +98,8 @@ namespace Accentra.Controls if (SquareQX < 7) SquareQX = 7; if (SquareQY < 5) SquareQY = 5; - if (_MaxRows > 0 && SquareQY > _MaxRows) SquareQY = _MaxRows; - if (_MaxCols > 0 && SquareQX > _MaxCols) SquareQX = _MaxCols; + if (MaxRows > 0 && SquareQY > MaxRows) SquareQY = MaxRows; + if (MaxCols > 0 && SquareQX > MaxCols) SquareQX = MaxCols; // Second, expand the dimensions of this form according to the // number of visible squares. @@ -177,14 +113,7 @@ namespace Accentra.Controls // the text is left-justified, only the Y (vertical) position // is calculated. int dispY = ((SquareY - 1) * SquareQY) + SquareQY + 4; - //if (this.Cancel) { - // DispText = "Esc Key to Cancel"; - //} else { - // DispText = SelQX.ToString() + " by " + SelQY.ToString() + " Table"; - //} - //DispText = SelQX.ToString() + " by " + SelQY.ToString() + " Table\nEsc Key to Cancel"; - //DispText = SelQY.ToString() + " Row"+((SelQY>1)?"s by ":" by ") + SelQX.ToString() + " Column"+((SelQX>1)?"s\nEsc Key to Cancel":"\nEsc Key to Cancel"); - DispText = SelQY.ToString() + " Row" + ((SelQY > 1) ? "s" : "") + " " + SelQX.ToString() + " Column" + ((SelQX > 1) ? "s" : "")+ "\nEsc to Cancel"; + DispText = $"{SelQY} Row{((SelQY > 1) ? "s" : "")} {SelQX} Column{((SelQX > 1) ? "s" : "")}\nEsc to Cancel"; g.DrawString(DispText, DispFont, BlackBrush, 3, dispY + 2); // Draw each of the squares and fill with the default color. @@ -198,7 +127,6 @@ namespace Accentra.Controls // Go back and paint the squares with selection colors. for (int x=0; x private void TablePicker_Deactivate(object sender, System.EventArgs e) { - // bCancel = true - // and DialogResult = DialogResult.Cancel - // were previously already set in MouseLeave. - - //this.Hide(); } /// @@ -242,42 +165,24 @@ namespace Accentra.Controls /// escaped (canceling) state. /// private void TablePicker_MouseLeave(object sender, System.EventArgs e) { - //if (!bHiding) bCancel = true; - //this.DialogResult = DialogResult.Cancel; - //this.Invalidate(); if (this.DialogResult == DialogResult.None) this.DialogResult = DialogResult.Cancel; } - /// - /// Cancels the prior cancellation caused by MouseLeave. - /// - private void TablePicker_MouseEnter(object sender, System.EventArgs e) { - //bHiding = false; - //bCancel = false; - //this.DialogResult = DialogResult.OK; - this.Invalidate(); - } + /// + /// Cancels the prior cancellation caused by MouseLeave. + /// + private void TablePicker_MouseEnter(object sender, System.EventArgs e) => this.Invalidate(); - /// - /// Detects that the user made a selection by clicking. - /// - private void TablePicker_Click(object sender, System.EventArgs e) { - //bHiding = true; // Not the same as Visible == false - // // because bHiding suggests that the control - // // is still "active" (not canceled). - //this.Hide(); - this.DialogResult = DialogResult.OK; - } + /// + /// Detects that the user made a selection by clicking. + /// + private void TablePicker_Click(object sender, System.EventArgs e) => this.DialogResult = DialogResult.OK; - private void TablePicker_KeyPress(object sender, KeyPressEventArgs e) + private void TablePicker_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Escape) { - //bHiding = true; // Not the same as Visible == false - //// because bHiding suggests that the control - //// is still "active" (not canceled). - //this.Hide(); this.DialogResult = DialogResult.Cancel; } } diff --git a/PROMS/VEPROMS User Interface/AboutVEPROMS.cs b/PROMS/VEPROMS User Interface/AboutVEPROMS.cs index 394d7f06..11b9c239 100644 --- a/PROMS/VEPROMS User Interface/AboutVEPROMS.cs +++ b/PROMS/VEPROMS User Interface/AboutVEPROMS.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; using System.Windows.Forms; using System.Reflection; using Volian.Controls.Library; @@ -24,7 +21,7 @@ namespace VEPROMS string connectionString = Database.VEPROMS_Connection; Match mServer = Regex.Match(connectionString, ".*Data Source=([^;]*).*"); _SQLServerName = (mServer.Success) ? mServer.Groups[1].Value : "unknown"; - if (_SQLServerName.StartsWith(@".\")) _SQLServerName = @"Local \ " + _SQLServerName.Substring(2); + if (_SQLServerName.StartsWith(@".\")) _SQLServerName = $@"Local \ {_SQLServerName.Substring(2)}"; } return _SQLServerName; } @@ -37,7 +34,7 @@ namespace VEPROMS { if (_DatabaseName == null) { - _DatabaseName = string.Format("{0}[SQL:{1:yyMM.ddHH}]", Database.ActiveDatabase, Database.RevDate); + _DatabaseName = $"{Database.ActiveDatabase}[SQL:{Database.RevDate:yyMM.ddHH}]"; } return _DatabaseName; } @@ -55,26 +52,16 @@ namespace VEPROMS DateTime buildDateTime = new System.IO.FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; // If the AssemblyConfiguration is "DEMO" then we are running a Demo version string demoTxt = VlnSettings.DemoMode ? "(Demo)": VlnSettings.DebugMode ? "(Debug)" : "(Production)"; - // C2018-015 made this information static so we can use in meta files - //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); - //string databaseName = string.Format("{0}[SQL:{1:yyMM.ddHH}]", Database.ActiveDatabase, Database.RevDate); - this.Text = String.Format("About {0}", AssemblyTitle + " " + demoTxt); - this.labelProductName.Text = AssemblyProduct; - this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); - this.labelVersionDateTime.Text = String.Format("Build Date: {0}", buildDateTime.ToString()); - this.labelCopyright.Text = String.Format("Copyright © {0}. All Rights Reserved.", buildDateTime.Year.ToString()); - this.labelCompanyName.Text = AssemblyCompany; -// this.textBoxDescription.Text = AssemblyDescription; - this.labelCompanyName.Links[0].LinkData = "Volian Enterprises Inc."; - this.labelCompanyName.Links.Add(0,23,"www.volian.com"); - //this.labelServer.Text = string.Format("SQL Server: {0}", server); - this.labelServer.Text = string.Format("SQL Server: {0}", SQLServerName); // C2018-015 use static for this info. - //if (databaseName == null) databaseName = Regex.Replace(connectionString, "^.*Initial Catalog=([^;]*);.*$", "$1", RegexOptions.IgnoreCase); - //this.labelDatabase.Text = string.Format("Database: {0}", databaseName); - this.labelDatabase.Text = string.Format("Database: {0}", DatabaseName); // C2018-015 use static for this info. + Text = $"About {AssemblyTitle} {demoTxt}"; + labelProductName.Text = AssemblyProduct; + labelVersion.Text = $"Version {AssemblyVersion}"; + labelVersionDateTime.Text = $"Build Date: {buildDateTime}"; + labelCopyright.Text = $"Copyright © {buildDateTime.Year}. All Rights Reserved."; + labelCompanyName.Text = AssemblyCompany; + labelCompanyName.Links[0].LinkData = "Volian Enterprises Inc."; + labelCompanyName.Links.Add(0,23,"www.volian.com"); + labelServer.Text = $"SQL Server: {SQLServerName}"; // C2018-015 use static for this info. + labelDatabase.Text = $"Database: {DatabaseName}"; // C2018-015 use static for this info. } #region Assembly Attribute Accessors @@ -99,24 +86,12 @@ namespace VEPROMS } } - public string AssemblyVersion - { - get - { - return Assembly.GetExecutingAssembly().GetName().Version.ToString(); - } - } + public string AssemblyVersion => Assembly.GetExecutingAssembly().GetName().Version.ToString(); - // C2018-009 used to print the PROMS version number at the top of each PDF page - public static string PROMSVersion - { - get - { - return Assembly.GetExecutingAssembly().GetName().Version.ToString(); - } - } + // C2018-009 used to print the PROMS version number at the top of each PDF page + public static string PROMSVersion => Assembly.GetExecutingAssembly().GetName().Version.ToString(); - public string AssemblyDescription + public string AssemblyDescription { get { @@ -162,7 +137,7 @@ namespace VEPROMS private void labelCompanyName_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Determine which link was clicked within the LinkLabel. - this.labelCompanyName.Links[0].Visited = true; + labelCompanyName.Links[0].Visited = true; // Display the appropriate link based on the value of the // LinkData property of the Link object. @@ -171,18 +146,17 @@ namespace VEPROMS System.Diagnostics.Process.Start(target); // this should start the default web browser } - private void logoPictureBox_Click(object sender, EventArgs e) - { - System.Diagnostics.Process.Start(labelCompanyName.Links[0].LinkData as string); // this should start the default web browser - } + private void logoPictureBox_Click(object sender, EventArgs e) => System.Diagnostics.Process.Start(labelCompanyName.Links[0].LinkData as string); // this should start the default web browser - private void btnViewEULA_Click(object sender, EventArgs e) + private void btnViewEULA_Click(object sender, EventArgs e) { - string EulaFile = string.Format(@"\{0}", VlnSettings.EULAfile); + string EulaFile = $@"\{VlnSettings.EULAfile}"; string strEULA = System.Environment.CurrentDirectory + EulaFile; - frmViewTextFile ViewFile = new frmViewTextFile(strEULA,RichTextBoxStreamType.PlainText); - ViewFile.Text = "End-User License Agreement"; - ViewFile.ShowDialog(); + frmViewTextFile ViewFile = new frmViewTextFile(strEULA, RichTextBoxStreamType.PlainText) + { + Text = "End-User License Agreement" + }; + ViewFile.ShowDialog(); } } diff --git a/PROMS/VEPROMS User Interface/BookMarks.cs b/PROMS/VEPROMS User Interface/BookMarks.cs deleted file mode 100644 index c27d388f..00000000 --- a/PROMS/VEPROMS User Interface/BookMarks.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using VEPROMS.CSLA.Library; - -namespace VEPROMS -{ - public class BookMarks - { - public string Name; - public VETreeNode Node; - - public BookMarks() - { - } - - public BookMarks(string n, VETreeNode o) - { - Name = n; - Node = o; - } - - public BookMarks(VETreeNode o) - { - Name = o.Text; - Node = o; - } - - public override string ToString() - { - return Name; - } - } -} diff --git a/PROMS/VEPROMS User Interface/DlgAnnotationsSelect.cs b/PROMS/VEPROMS User Interface/DlgAnnotationsSelect.cs index c27bba37..a7648b16 100644 --- a/PROMS/VEPROMS User Interface/DlgAnnotationsSelect.cs +++ b/PROMS/VEPROMS User Interface/DlgAnnotationsSelect.cs @@ -1,11 +1,6 @@ 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; using VEPROMS.CSLA.Library; @@ -14,10 +9,7 @@ namespace VEPROMS // C2025-027 Annotation Type Filtering public partial class dlgAnnotationsSelect : Form { - public dlgAnnotationsSelect() - { - InitializeComponent(); - } + public dlgAnnotationsSelect() => InitializeComponent(); public dlgAnnotationsSelect(string userid) { @@ -25,30 +17,13 @@ namespace VEPROMS UserID = userid; } - private int _MyItemID; - public int MyItemID - { - get { return _MyItemID; } - set { _MyItemID = value; } - } + public int MyItemID { get; set; } + public string UserID { get; set; } - private string _UserID; - public string UserID - { - get { return _UserID; } - set { _UserID = value; } - } - - private void btnSelect_Click(object sender, EventArgs e) - { - MoveSelectedItems(lstUnselected, lstSelected); - } + private void btnSelect_Click(object sender, EventArgs e) => MoveSelectedItems(lstUnselected, lstSelected); // Move selected items to lstUnselected. - private void btnDeselect_Click(object sender, EventArgs e) - { - MoveSelectedItems(lstSelected, lstUnselected); - } + private void btnDeselect_Click(object sender, EventArgs e) => MoveSelectedItems(lstSelected, lstUnselected); // Move selected items from one ListBox to another. private void MoveSelectedItems(ListBox lstFrom, ListBox lstTo) @@ -90,39 +65,21 @@ namespace VEPROMS } // Enable and disable buttons. - private void lst_SelectedIndexChanged(object sender, EventArgs e) - { - SetButtonsEditable(); - } + private void lst_SelectedIndexChanged(object sender, EventArgs e) => SetButtonsEditable(); // Save selected list to DB. - private void btnUpdate_Click(object sender, EventArgs e) - { - saveChanges(); - } + private void btnUpdate_Click(object sender, EventArgs e) => saveChanges(); public class AnnotataionItem { - private string _NameStr; - private int _TypeID; + private readonly string _NameStr; + private readonly int _TypeID; public AnnotataionItem(string NameStr, int TypeID) { - this._NameStr = NameStr; - this._TypeID = TypeID; - } - public string NameStr - { - get - { - return _NameStr; - } - } - public int TypeID - { - get - { - return _TypeID; - } + _NameStr = NameStr; + _TypeID = TypeID; } + public string NameStr => _NameStr; + public int TypeID => _TypeID; } // Enable and disable buttons. @@ -167,16 +124,16 @@ namespace VEPROMS if (result == DialogResult.Yes) { saveChanges(); - this.Close(); + Close(); } else { - this.Close(); + Close(); } } else { - this.Close(); + Close(); } } diff --git a/PROMS/VEPROMS User Interface/DlgCloseTabsOrExit.cs b/PROMS/VEPROMS User Interface/DlgCloseTabsOrExit.cs index abbe0ccd..2314696b 100644 --- a/PROMS/VEPROMS User Interface/DlgCloseTabsOrExit.cs +++ b/PROMS/VEPROMS User Interface/DlgCloseTabsOrExit.cs @@ -1,12 +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 VEPROMS { @@ -16,19 +8,10 @@ namespace VEPROMS { private bool _Cancel = true; - public bool Cancel - { - get { return _Cancel; } - } + public bool Cancel => _Cancel; - private bool _ExitPROMS; - - public bool ExitPROMS - { - get { return _ExitPROMS; } - set { _ExitPROMS = value; } - } - public DlgCloseTabsOrExit(bool isMainWindow, bool hasChildWindows) + public bool ExitPROMS { get; set; } + public DlgCloseTabsOrExit(bool isMainWindow, bool hasChildWindows) { InitializeComponent(); if (!isMainWindow) @@ -46,22 +29,22 @@ namespace VEPROMS private void BtnClsTab_Click(object sender, EventArgs e) { _Cancel = false; - _ExitPROMS = false; - this.Hide(); + ExitPROMS = false; + Hide(); } private void BtnExitPROMS_Click(object sender, EventArgs e) { _Cancel = false; - _ExitPROMS = true; - this.Hide(); + ExitPROMS = true; + Hide(); } private void btnCancel_Click(object sender, EventArgs e) { _Cancel = true; - _ExitPROMS = false; - this.Hide(); + ExitPROMS = false; + Hide(); } } } diff --git a/PROMS/VEPROMS User Interface/DlgPrintProcedure.cs b/PROMS/VEPROMS User Interface/DlgPrintProcedure.cs index a4f04f9b..20ed61d5 100644 --- a/PROMS/VEPROMS User Interface/DlgPrintProcedure.cs +++ b/PROMS/VEPROMS User Interface/DlgPrintProcedure.cs @@ -1,29 +1,21 @@ 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; using VEPROMS.CSLA.Library; using Volian.Print.Library; -//using Volian.Controls.Library; using Volian.Base.Library; using JR.Utils.GUI.Forms; +using System.Linq; namespace VEPROMS { public partial class DlgPrintProcedure : DevComponents.DotNetBar.Office2007Form { - public bool SaveLinks - { - get - { - return swtbtnPDFLinks.Value; - } - } - public int RemoveTrailingHardReturnsAndManualPageBreaks + public bool SaveLinks => swtbtnPDFLinks.Value; + public int RemoveTrailingHardReturnsAndManualPageBreaks { get { @@ -36,38 +28,19 @@ namespace VEPROMS return 3; } } - private string _Prefix = ""; // RHM20150506 Multiline ItemID TextBox - public string Prefix - { - get { return _Prefix; } - set { _Prefix = value; } - } - public bool OpenAfterCreate // RHM20150506 Multiline ItemID TextBox + // RHM20150506 Multiline ItemID TextBox + public string Prefix { get; set; } = ""; + public bool OpenAfterCreate // RHM20150506 Multiline ItemID TextBox { get { return cbxOpenAfterCreate2.Checked; } set { cbxOpenAfterCreate2.Checked = value; } } - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } - private bool _Automatic; - public bool Automatic - { - get { return _Automatic; } - set { _Automatic = value; } - } - private int _prtSectID = -1; - public int PrtSectID - { - get { return _prtSectID; } - set { _prtSectID = value; } - } - private bool _OverwritePDF; - public bool OverwritePDF + public SessionInfo MySessionInfo { get; set; } + public bool Automatic { get; set; } + public int PrtSectID { get; set; } = -1; + + public bool OverwritePDF { get { return cbxOverwritePDF2.Checked; } set { cbxOverwritePDF2.Checked = value; } @@ -85,18 +58,17 @@ namespace VEPROMS swtbtnPDFdtPrefixSuffix.Value = swtbtnPDFdtPrefixSuffix.Enabled = _AllowDateTimePrefixSuffix; } } - private DateTime _PrefixSuffixDTS = DateTime.Now; // C2018-033 date/time used for the date/time PDF file prefix and suffix + private readonly DateTime _PrefixSuffixDTS = DateTime.Now; // C2018-033 date/time used for the date/time PDF file prefix and suffix private bool _DateTimePrefixSuffixPrintingAllProcedures = true; // C2018-033 to control adding the Date/Time Prefix/Suffix to PFD name when printing All procedures private bool _IncludeWordSecTextInMetafile = true; // C2018-023 so that we can turn off including Word attachment text in metafile private void RunAutomatic() { cbxDebugPagination.Checked = true; cbxDebugText.Checked = true; - cbxMetaFile.Checked = true; // C2018-004 create meta file for baseline compares + cbxMetaFile.Checked = true; // C2018-004 create meta file for baseline compares _IncludeWordSecTextInMetafile = true; Application.DoEvents(); string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray()); - bool ranAuto = false; foreach (string parameter in parameters) { if (parameter.ToUpper() == "/NT") @@ -111,11 +83,11 @@ namespace VEPROMS _IncludeWordSecTextInMetafile = false; // C2018-023 turn off putting Word attachment text in the meta file for baseline compares } CreatePDFs(); - this.Close(); + Close(); } - private DocVersionInfo _DocVersionInfo = null; - private bool _AllProcedures; - private DocVersionConfig _DocVersionConfig; + private readonly DocVersionInfo _DocVersionInfo = null; + private readonly bool _AllProcedures; + private readonly DocVersionConfig _DocVersionConfig; public string RevNum { get { return txbRevNum.Text; } @@ -143,11 +115,8 @@ namespace VEPROMS return RevNum + "/" + RevDate; } } - public string ProcNum - { - get { return MyProcedure.DisplayNumber; } - } - public string PDFPath + public string ProcNum => MyProcedure.DisplayNumber; + public string PDFPath { get {// B2018-069 Revert to Temporary for Baseline testing if (PromsPrinter.BaselineTesting) @@ -179,7 +148,7 @@ namespace VEPROMS private bool _CreateButtonClicked = false; // B2020-062 control the toggle of date/time prefix/suffix on pdf file name public DlgPrintProcedure(DocVersionInfo dvi, bool automatic) { - _Automatic = automatic; + Automatic = automatic; InitializeComponent(); _AllProcedures = true; _DocVersionConfig = dvi.DocVersionConfig; @@ -201,14 +170,12 @@ namespace VEPROMS btnCreatePDF.Text = "Create PDFs"; HandleDocVersionSettings(); PrepForAllOrOne(false); - // don't open all PDFs if doing All Procedures - //cbxOpenAfterCreate2.Checked = dvi.DocVersionConfig.Print_AlwaysViewPDFAfterCreate; // C2018-033 added the Prefix / Suffix switch to the expand Additional Settings check expPrnSetting.Expanded = swtbtnBlankPgsForDuplex.Value || swtbtnChgBar.Value || swtbtnGeneratePlacekeeper.Value || swtbtnPDFLinks.Value || swtbtnPROMSVersion.Value || swtbtnWaterMark.Value || swtbtnPDFdtPrefixSuffix.Value; } public DlgPrintProcedure(DocVersionInfo dvi) { - _Automatic = false; + Automatic = false; InitializeComponent(); _AllProcedures = true; _DocVersionConfig = dvi.DocVersionConfig; @@ -249,21 +216,12 @@ namespace VEPROMS // C2021-063 make the Generate Alarm Point List text checkbox visable in the format flag is set. cbxAlmPtTxt.Visible = !oneProcedure && MyProcedure.ActiveFormat.PlantFormat.FormatData.PrintData.ChkBoxToGeneratePointListText; } - private string _UnitNumber; - public string UnitNumber - { - get { return _UnitNumber; } - set { _UnitNumber = value; } - } - private int _UnitIndex; - public int UnitIndex - { - get { return _UnitIndex; } - set { _UnitIndex = value; } - } - // C2018-012 - Code Cleanup - redesigned the Print Dialog to include a sliding panel and remplaced check boxes with ON/OFF switches - public DlgPrintProcedure(ProcedureInfo pi) + public string UnitNumber { get; set; } + public int UnitIndex { get; set; } + + // C2018-012 - Code Cleanup - redesigned the Print Dialog to include a sliding panel and remplaced check boxes with ON/OFF switches + public DlgPrintProcedure(ProcedureInfo pi) { InitializeComponent(); _AllProcedures = false; @@ -354,31 +312,9 @@ namespace VEPROMS swtbtnWaterMark.Value = false; else swtbtnWaterMark.Value = true; - // Auto Duplexing on/off - Auto duplex was used only by Point Beach formats These buttons were removed from the dialog - // There was not print coding to support this format flag - //if ((_MyProcedure.ActiveParent as DocVersionInfo).ActiveFormat.PlantFormat.FormatData.PrintData.AllowDuplex) - //{ - // lblAutoDuplexing.Visible = true; - // btnDuplxOff.Visible = true; - // btnDuplxOn.Visible = true; - // if (_DocVersionConfig.Print_DisableDuplex) - // btnDuplxOff.PerformClick(); - // else - // btnDuplxOn.PerformClick(); - //} - //else - //{ - // lblAutoDuplexing.Visible = false; - // btnDuplxOff.Visible = false; - // btnDuplxOn.Visible = false; - //} SetCompareVisibility(); - - // default to using OriginalPageBreaks (16bit page breaks) if App.config is set - // to true: - //cbxOrPgBrk.Visible = VlnSettings.OriginalPageBreak && VlnSettings.DebugMode; - cbxOrPgBrk.Visible = false; //per Harry + cbxOrPgBrk.Visible = false; //per Harry cbxOrPgBrk.Checked = false; } @@ -416,13 +352,7 @@ namespace VEPROMS private Timer _MyTimer; public void SetupForProcedure() // RHM20150506 Multiline ItemID TextBox { - if(_DocVersionInfo == null)this.Text = "Create PDF for " + ProcNum; - // get list of previous pdf files - // if no previous pdf file, then get path from frmVersionProperties - // dlgSelectFile.InitialDirectory = pdf path from frmVersionProperties - //cbxPDF.Text = string.Format(@"{0}\{1}.pdf", _PDFPath, _ProcNum); - // General 2 settings - //txbPDFLocation.Text = _PDFPath; + if(_DocVersionInfo == null)Text = "Create PDF for " + ProcNum; BuildPDFFileName(); ProcedureConfig pc = _MyProcedure.MyConfig as ProcedureConfig; // C2025-033 set which Child procedure is being printed used for PageStyle items @@ -434,7 +364,7 @@ namespace VEPROMS if (pc != null) { //C2021-062 use the save rev number for all procedures if set, or just use the rev number in the current procedure config - RevNum = (_NewRevForAllProcs == null) ? pc.Print_Rev : _NewRevForAllProcs; + RevNum = _NewRevForAllProcs ?? pc.Print_Rev; RevDate = pc.Print_RevDate; //== null || pc.Print_RevDate=="" ? DateTime.Today : Convert.ToDateTime(pc.Print_RevDate); ReviewDate = pc.Print_ReviewDate; // == null ? DateTime.Today : Convert.ToDateTime(pc.Print_ReviewDate); //Now check the format flags to determine if/how the Rev string should be parsed. @@ -498,11 +428,6 @@ namespace VEPROMS else swtbtnWaterMark.Value = false; // set to None at folder level so set Watermark switch to the off position - //ppCmbxChgBarPos.DataSource = EnumDetail.Details(); - //ppCmbxChgBarPos.DisplayMember = "Description"; - //ppCmbxChgBarPos.ValueMember = "EValue"; - //ppCmbxChgBarPos.SelectedIndex = (int)MyProcedure.MyDocVersion.DocVersionConfig.Print_ChangeBarLoc; - ppCmbxChgBarTxtType.DataSource = EnumDetail.Details(); ppCmbxChgBarTxtType.DisplayMember = "Description"; ppCmbxChgBarTxtType.ValueMember = "EValue"; @@ -515,7 +440,7 @@ namespace VEPROMS bool usesRevDate = _MyProcedure.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate || _MyProcedure.ActiveFormat.PlantFormat.FormatData.PrintData.RevDateWithForwardSlash; if (_MyProcedure.Sections != null) { - foreach (SectionInfo mysection in _MyProcedure.Sections) + foreach (SectionInfo mysection in _MyProcedure.Sections.OfType()) hasReviewDate |= mysection.ActiveFormat.PlantFormat.HasPageListToken("{REVIEWDATE}"); } // Only the New HLP format and the MYA format use this @@ -535,9 +460,8 @@ namespace VEPROMS if (MyProcedure == null) return; string PDFFilePrefix = _DocVersionConfig.Print_PDFFilePrefix; string PDFFileSuffix = _DocVersionConfig.Print_PDFFileSuffix; - string PDFFileName = ""; - PDFDTPrefix dtPre = _DocVersionConfig.Print_PDFdtFilePrefix; - PDFDTSuffix dtSuf = _DocVersionConfig.Print_PDFdtFileSuffix; + PDFDTPrefix dtPre = _DocVersionConfig.Print_PDFdtFilePrefix; + PDFDTSuffix dtSuf = _DocVersionConfig.Print_PDFdtFileSuffix; if (dtPre != PDFDTPrefix.None) PDFFilePrefix = ""; // incase user entered prefix text but then selected a date/time (in working draft properties) if (dtSuf != PDFDTSuffix.None) PDFFileSuffix = ""; // incase user entered suffix text but then selected a date/time (in working draft properties) // B2020-062 control the toggle of date/time prefix/suffix on pdf file name @@ -556,19 +480,17 @@ namespace VEPROMS if (dtSuf != PDFDTSuffix.None) PDFFileSuffix = "_" + (_PrefixSuffixDTS.ToString(dtSuf.ToString())).Replace("__", " ").Replace("_", "-"); } - if (ProcNum == string.Empty) - //txbPDFName.Text = this.UnitNumber + ".pdf"; - PDFFileName = this.UnitNumber; - else - //txbPDFName.Text = string.Format("{0}.pdf", _MyProcedure.PDFNumber); - PDFFileName = string.Format("{0}", _MyProcedure.PDFNumber); - //if (txbPDFName.Text.StartsWith("*")) - // txbPDFName.Text = txbPDFName.Text.Replace("*", this.UnitNumber); - if ((PDFFileName ?? "") == "") PDFFileName = "NoProcNumber"; + string PDFFileName; + if (ProcNum == string.Empty) + PDFFileName = UnitNumber; + else + PDFFileName = string.Format("{0}", _MyProcedure.PDFNumber); + + if ((PDFFileName ?? "") == "") PDFFileName = "NoProcNumber"; if (PDFFileName.StartsWith("*")) - PDFFileName = PDFFileName.Replace("*", this.UnitNumber); + PDFFileName = PDFFileName.Replace("*", UnitNumber); if (PDFFileName.Contains("?")) PDFFileName = PDFFileName.Replace("?", "_"); // for wcn sys/BM-2xxA??, etc - txbPDFName.Text = PDFFilePrefix + PDFFileName + PDFFileSuffix + ".pdf"; + txbPDFName.Text = $"{PDFFilePrefix}{PDFFileName}{PDFFileSuffix}.pdf"; } // C2018-033 Enable/disable the switch to control whether to add Prefix and/or Suffix to PDF file name @@ -585,12 +507,9 @@ namespace VEPROMS swtbtnPDFdtPrefixSuffix.Enabled = hasPrefixSuffix; } - private void btnCancel_Click(object sender, EventArgs e) - { - this.Close(); - } + private void btnCancel_Click(object sender, EventArgs e) => Close(); - private void swtbtnChgBar_ValueChanged(object sender, EventArgs e) + private void swtbtnChgBar_ValueChanged(object sender, EventArgs e) { // C2019-031 - disable the override change bar grouping when default change bar is set to format default or no change bar cbxOvrrideDefChgBars.Checked = false; // uncheck the override change bar check box inside the grouping @@ -714,7 +633,7 @@ namespace VEPROMS StringBuilder sb = new StringBuilder(); if (MySessionInfo != null) { - foreach (ProcedureInfo myProc in _DocVersionInfo.Procedures) + foreach (ProcedureInfo myProc in _DocVersionInfo.Procedures.OfType()) { string message = string.Empty; if (!MySessionInfo.CanCheckOutItem(myProc.ItemID, CheckOutType.Procedure, ref message)) @@ -742,15 +661,14 @@ namespace VEPROMS pbPDFsStatus.Maximum = n; pbPDFsStatus.Visible = true; VlnSvgPageHelper.CountInApplProcs = 1; // B2021-127: BNPPalr - Auto set of serial #, skip Front Matter as per PAL 11/1/21 (set to 1 not 0) - this.Text = string.Format("Processing {0}", _DocVersionInfo.MyFolder.Name); - foreach (ProcedureInfo myProc in _DocVersionInfo.Procedures) + Text = string.Format("Processing {0}", _DocVersionInfo.MyFolder.Name); + foreach (ProcedureInfo myProc in _DocVersionInfo.Procedures.OfType()) { string locpdfname = null; // get pdf file name for later merge code MyProcedure = myProc; - // C2021-019: Override Watermark Text, 'waterMarkText' will have whatever watermark text should be printed - ProcedureConfig procConfig = MyProcedure.MyConfig as ProcedureConfig; - string waterMarkTextOverride = ""; - if (procConfig != null) waterMarkTextOverride = procConfig.GetValue("PSI", "WATERMARKOVERRIDE"); + // C2021-019: Override Watermark Text, 'waterMarkText' will have whatever watermark text should be printed + string waterMarkTextOverride = ""; + if (MyProcedure.MyConfig is ProcedureConfig procConfig) waterMarkTextOverride = procConfig.GetValue("PSI", "WATERMARKOVERRIDE"); // C2020-002 paper size is now set in the format files - default is Letter Volian.Print.Library.Rtf2Pdf.PaperSize = myProc.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize; if (myProc.Sections != null) @@ -772,13 +690,6 @@ namespace VEPROMS pbPDFsStatus.TextVisible = true; pbPDFsStatus.Text = string.Format("Creating PDF for {0} ({1} of {2})", myProc.DisplayNumber, ++i, n); pbPDFsStatus.Value = i; - // this.Text = string.Format("Create PDF for {0} ({1} of {2})", myProc.DisplayNumber, ++i, n); - - // B2021-102 we now get this information in frmPDFStatusForm() - //MyProcedure = ProcedureInfo.GetItemAndChildrenByUnit(MyProcedure.ItemID, 0, MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave); - // C2018-015 add the procedure tree path and the procedure number and title to the meta file - //if (BaselineMetaFile.IsOpen && i == 1) BaselineMetaFile.WriteLine("!! {0}", MyProcedure.SearchDVPath.Replace("\a", " | ")); - //if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0} | {1}", MyProcedure.DisplayNumber, MyProcedure.DisplayText); string myPDFPath = GetMultiunitPDFPath(); _MergedPdfPath = myPDFPath; // If Slave, need its subdirectory/unit path for merging @@ -814,14 +725,7 @@ namespace VEPROMS pbPDFsStatus.TextVisible = true; pbPDFsStatus.Text = string.Format("Creating PDF for {0} ({1} of {2})", myProc.DisplayNumber, ++i, n); pbPDFsStatus.Value = i; - // this.Text = string.Format("Create PDF for {0} ({1} of {2})", myProc.DisplayNumber, ++i, n); - - // B2021-102 we now get this information in frmPDFStatusForm() - //MyProcedure = ProcedureInfo.GetItemAndChildrenByUnit(MyProcedure.ItemID, 0, MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave); - // C2018-015 add the procedure tree path and the procedure number and title to the meta file - //if (BaselineMetaFile.IsOpen && i == 1) BaselineMetaFile.WriteLine("!! {0}", MyProcedure.SearchDVPath.Replace("\a", " | ")); - //if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0} | {1}", MyProcedure.DisplayNumber, MyProcedure.DisplayText); - + // RHM 20120925 Overlay the bottom of the dialog so that cancel button is covered. // B2016-249 Output Procedure to folder associated with Parent Child // B2021-102 put in the using for better memory management @@ -850,18 +754,9 @@ namespace VEPROMS pbPDFsStatus.TextVisible = true; pbPDFsStatus.Text = string.Format("Creating PDF for {0} ({1} of {2})", myProc.DisplayNumber, ++i, n); pbPDFsStatus.Value = i; - // this.Text = string.Format("Create PDF for {0} ({1} of {2})", myProc.DisplayNumber, ++i, n); // RHM 20120925 Overlay the bottom of the dialog so that cancel button is covered. int profileDepth1 = ProfileTimer.Push(">>>> GetItemAndChildren"); - // B2021-102 we now get this information in frmPDFStatusForm() - //if (MyProcedure.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier || MyProcedure.ActiveFormat.PlantFormat.FormatData.TransData.UseSpecificTransitionModifier) - // MyProcedure = ProcedureInfo.GetItemAndChildrenByUnit(MyProcedure.ItemID, 0, MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave); - //else - // MyProcedure = ProcedureInfo.GetItemAndChildren(MyProcedure.ItemID); - //// C2018-015 add the procedure tree path and the procedure number and title to the meta file - //if (BaselineMetaFile.IsOpen && i == 1) BaselineMetaFile.WriteLine("!! {0}", MyProcedure.SearchDVPath.Replace("\a", " | ")); - //if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0} | {1}", MyProcedure.DisplayNumber, MyProcedure.DisplayText); - + ProfileTimer.Pop(profileDepth1); // B2021-102 put in the using for better memory management // B2016-249 Output Procedure to folder associated with Parent Child @@ -934,12 +829,12 @@ namespace VEPROMS private void CreateDebugFiles() { if (cbxDebugPagination.Checked) - Volian.Base.Library.DebugPagination.Open(PDFPath + "\\DebugPagination.txt"); // RHM 20120925 Corrected spelling + Volian.Base.Library.DebugPagination.Open($"{PDFPath}\\DebugPagination.txt"); // RHM 20120925 Corrected spelling if (cbxDebugText.Checked) - Volian.Base.Library.DebugText.Open(PDFPath + "\\DebugText.txt"); + Volian.Base.Library.DebugText.Open($"{PDFPath}\\DebugText.txt"); if (cbxMetaFile.Checked) // C2018-004 create meta file for baseline compares { - Volian.Base.Library.BaselineMetaFile.Open(PDFPath + "\\DebugMeta.txt"); + Volian.Base.Library.BaselineMetaFile.Open($"{PDFPath}\\DebugMeta.txt"); // C2018-015 add the PROMS Version, SQL Server, and Database to top of the meta file Volian.Base.Library.BaselineMetaFile.WriteLine("!! Ver {0} {1} {2}", AboutVEPROMS.PROMSVersion, AboutVEPROMS.SQLServerName, AboutVEPROMS.DatabaseName); // C2018-023 set as to whether we are going to include the Word attment text in the baseline metafile @@ -975,7 +870,7 @@ namespace VEPROMS if (MyProcedure.MyDocVersion.MultiUnitCount > 1) { VlnSvgPageHelper.CountInApplProcs = 1; - foreach (ProcedureInfo pi in MyProcedure.MyDocVersion.Procedures) + foreach (ProcedureInfo pi in MyProcedure.MyDocVersion.Procedures.OfType()) { if (pi.ItemID == MyProcedure.ItemID) break; bool includeProc = pi.ApplInclude(SelectedSlave); @@ -991,24 +886,14 @@ namespace VEPROMS string waterMarkText = (swtbtnWaterMark.Value) ? cbxWaterMark.Text : "None" ; // B2018-124 use text of watermark form drop down list instead of enum value string watermarkColor = "Blue"; // this is the default watermark color frmPDFStatusForm.SetUnitWatermark(MyProcedure, ref waterMarkText, ref watermarkColor); //C2022-004 Unit Designator Watermark - ProcedureConfig procConfig = MyProcedure.MyConfig as ProcedureConfig; - string waterMarkTextOverride = ""; - if (procConfig != null) waterMarkTextOverride = procConfig.GetValue("PSI", "WATERMARKOVERRIDE"); // C2021-019: override watermark text + string waterMarkTextOverride = ""; + if (MyProcedure.MyConfig is ProcedureConfig procConfig) waterMarkTextOverride = procConfig.GetValue("PSI", "WATERMARKOVERRIDE"); // C2021-019: override watermark text if (swtbtnWaterMark.Value && waterMarkTextOverride != null && waterMarkTextOverride != "") waterMarkText = waterMarkTextOverride; // Determine change bar settings. First get from config & then see if override from dialog. // Also check that format allows override. ChangeBarDefinition cbd = DetermineChangeBarSettings(); int profileDepth2 = ProfileTimer.Push(">>>> CreatePdf.GetItemAndChildren"); - // B2021-088 moved this if/else to frmPDFStatusForm() so that the Approval logic will have access to this logic - //if (MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave > 0 || MyProcedure.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier || MyProcedure.ActiveFormat.PlantFormat.FormatData.TransData.UseSpecificTransitionModifier) - // MyProcedure = ProcedureInfo.GetItemAndChildrenByUnit(MyProcedure.ItemID, 0, MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave); - //else - // MyProcedure = ProcedureInfo.GetItemAndChildren(MyProcedure.ItemID); - // C2018-015 add the procedure tree path and the procedure number and title to the meta file - //if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0}", MyProcedure.SearchDVPath.Replace("\a"," | ")); - //if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0} | {1}", MyProcedure.DisplayNumber, MyProcedure.DisplayText); - // B2022-088: Find Doc Ro button not working in Word Sections // Initialize Print Cache MSWordToPDF.RoPrintCache = new Dictionary(); @@ -1045,7 +930,7 @@ namespace VEPROMS MyProcedure.MyDocVersion.DocVersionConfig.SelectedSlave = 0; MyProcedure.SelectedChildToPrint = 0; // B2023-035 reset - this.Close(); + Close(); ShowDebugFiles(); ProfileTimer.Pop(profileDepth); ProfileTimer.ShowTimerTable(); @@ -1121,22 +1006,19 @@ namespace VEPROMS DoCreatePDF(); } - public void QPCreatePDF() - { - DoCreatePDF(); - } + public void QPCreatePDF() => DoCreatePDF(); - private void DoCreatePDF() + private void DoCreatePDF() { if (_AllProcedures) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime dtStart = DateTime.Now; _MultiunitPdfLocation = cbxMultiunitPdfLocation.SelectedItem.ToString(); PromsPrinter.ClearTransPageNumProblems(); CreatePDFs(); PromsPrinter.ReportTransPageNumProblems(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; if (_MergedPfd == null) { if (VlnSettings.DebugMode) @@ -1149,7 +1031,7 @@ namespace VEPROMS { MessageBox.Show("Completed Successfully", "Print All Procedures", MessageBoxButtons.OK, MessageBoxIcon.Information); } - this.Close(); + Close(); } } else @@ -1158,14 +1040,14 @@ namespace VEPROMS // B2017-009 If the selected item is null don't add a folder if (cbxMultiunitPdfLocation.SelectedItem != null) _MultiunitPdfLocation = cbxMultiunitPdfLocation.SelectedItem.ToString(); - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; _CreateButtonClicked = true; // B2020-062 control the toggle of date/time prefix/suffix on pdf file name CreatePDF(); _CreateButtonClicked = false; - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } } - private bool _Initializing = false; + private readonly bool _Initializing = false; private void btnPdfLocation_Click(object sender, EventArgs e) { @@ -1191,12 +1073,9 @@ namespace VEPROMS ppTxbxChangeBarUserMsgOne.Enabled = enabled; ppTxbxChangeBarUserMsgTwo.Enabled = enabled; } - private void cbxOvrrideDefChgBars_CheckStateChanged(object sender, EventArgs e) - { - SetCustomControls(cbxOvrrideDefChgBars.Checked); - } + private void cbxOvrrideDefChgBars_CheckStateChanged(object sender, EventArgs e) => SetCustomControls(cbxOvrrideDefChgBars.Checked); - private void rbCustom_Click(object sender, EventArgs e) + private void rbCustom_Click(object sender, EventArgs e) { SetCustomControls(true); // Make Custom controls visible @@ -1218,24 +1097,22 @@ namespace VEPROMS // B2024-058 Add validation for Revision Date field of the Print dialog private bool validateDate(TextBox txtDate) { - DateTime dDate; - if (!(txtDate.Text == "")) - { - - if (DateTime.TryParse(txtDate.Text, out dDate)) - { - return true; - } - else - { - string txtDate2 = txtDate.Text; - string message = String.Format("Date {0} in wrong format" + System.Environment.NewLine + "Correct the revision date.", txtDate2); - string txtTitle = "Invalid Format"; - MessageBox.Show(message, txtTitle); - return false; - } - } - return true; + if (!(txtDate.Text == "")) + { + if (DateTime.TryParse(txtDate.Text, out _)) + { + return true; + } + else + { + string txtDate2 = txtDate.Text; + string message = String.Format("Date {0} in wrong format" + System.Environment.NewLine + "Correct the revision date.", txtDate2); + string txtTitle = "Invalid Format"; + MessageBox.Show(message, txtTitle); + return false; + } + } + return true; } private void txbRevDate_Enter(object sender, EventArgs e) @@ -1243,8 +1120,6 @@ namespace VEPROMS txbDate = txbRevDate; grpDateSelector.Text = "Select Revision Date"; grpDateSelector.Visible = calDateSelector.Visible = true; - //C2021-007 position the calendar to the current RevDate or if no RevDate, position to today's date - DateTime dDate; // B2024-058 Add validation for Revision Date field of the Print dialog if (!validateDate(txbDate)) { @@ -1259,17 +1134,16 @@ namespace VEPROMS private void txbRevDate_Leave(object sender, EventArgs e) { if (_Initializing) return; - if (this.ActiveControl == calDateSelector) + if (ActiveControl == calDateSelector) { txbRevDate.Focus(); //B2018-059 keep the calendar open until a different field on the print dialog is selected return; } txbDate = null; grpDateSelector.Visible = calDateSelector.Visible = false; - // save the RevDate to the procedure's config. - ProcedureConfig pc = MyProcedure.MyConfig as ProcedureConfig; - if (pc == null) return; - pc.Print_RevDate = txbRevDate.Text; + // save the RevDate to the procedure's config. + if (!(MyProcedure.MyConfig is ProcedureConfig pc)) return; + pc.Print_RevDate = txbRevDate.Text; using (Item itm = Item.Get(MyProcedure.ItemID)) { itm.MyContent.Config = MyProcedure.MyConfig.ToString(); @@ -1283,10 +1157,9 @@ namespace VEPROMS if (_Initializing) return; txbDate = null; grpDateSelector.Visible = calDateSelector.Visible = false; - // save the ReviewDate to the procedure's config. - ProcedureConfig pc = MyProcedure.MyConfig as ProcedureConfig; - if (pc == null) return; - pc.Print_ReviewDate = txbReviewDate.Text; + // save the ReviewDate to the procedure's config. + if (!(MyProcedure.MyConfig is ProcedureConfig pc)) return; + pc.Print_ReviewDate = txbReviewDate.Text; using (Item itm = Item.Get(MyProcedure.ItemID)) { itm.MyContent.Config = MyProcedure.MyConfig.ToString(); @@ -1326,10 +1199,9 @@ namespace VEPROMS // C2021-062 used to save rev number information when all procedures are printed or merged private void SaveRevNumToProcedureConfig(string newrevnum) { - // save the RevNum to the procedure's config. - ProcedureConfig pc = MyProcedure.MyConfig as ProcedureConfig; - if (pc == null) return; - pc.Print_Rev = newrevnum; + // save the RevNum to the procedure's config. + if (!(MyProcedure.MyConfig is ProcedureConfig pc)) return; + pc.Print_Rev = newrevnum; using (Item itm = Item.Get(MyProcedure.ItemID)) { itm.MyContent.Config = MyProcedure.MyConfig.ToString(); @@ -1341,22 +1213,16 @@ namespace VEPROMS { if (expPrnSetting.Expanded) { - this.Size = new Size(this.Size.Width + (expPrnSetting.Size.Width - expPrnSetting.TitlePanel.Size.Height), this.Size.Height); + Size = new Size(Size.Width + (expPrnSetting.Size.Width - expPrnSetting.TitlePanel.Size.Height), Size.Height); // B2018-137 set the visability of Generate Placekeeper swtbtnGeneratePlacekeeper.Visible = lblGeneratePlacekeeper.Visible = ((MyProcedure.ActiveFormat.PlantFormat.FormatData.PurchaseOptions & E_PurchaseOptions.AutoPlacekeeper) == E_PurchaseOptions.AutoPlacekeeper); } - //else - // this.Size = new Size(this.Size.Width-(expPrnSetting.Size.Width-expPrnSetting.TitlePanel.Size.Height), this.Size.Height); - //Refresh(); } private void expPrnSetting_ExpandedChanging(object sender, DevComponents.DotNetBar.ExpandedChangeEventArgs e) - { + { if (expPrnSetting.Expanded) - //this.Size = new Size(this.Size.Width+(expPrnSetting.Size.Width-expPrnSetting.TitlePanel.Size.Height), this.Size.Height); - //else - this.Size = new Size(this.Size.Width-(expPrnSetting.Size.Width-expPrnSetting.TitlePanel.Size.Height), this.Size.Height); - //Refresh(); + Size = new Size(Size.Width-(expPrnSetting.Size.Width-expPrnSetting.TitlePanel.Size.Height), Size.Height); } @@ -1395,15 +1261,15 @@ namespace VEPROMS DoCreatePDF(); // create indivitual pdfs if (_MergedPdfPath != null && _MergedPdfPath != PDFPath) PDFPath = _MergedPfd.Folder = _MergedPdfPath; // C2021-063 pass in whether to generate Alarm Point List text when a merge is done - if (!_MergedPfd.DoTheMerge(PromsPrinter.MergedLandscapePages,cbxAlmPtTxt.Checked)) return; // merge them together. + if (!_MergedPfd.DoTheMerge(cbxAlmPtTxt.Checked)) return; // merge them together. // if the property to show the file after printing is set (on the version dialog), display it. Otherwise do a dialog to let user know it's done if (_DocVersionConfig.Print_MergedPdfsViewAfter) { if (_MergedPfd.MergedPdfs != null && _MergedPfd.MergedPdfs.Count > 0) { System.Diagnostics.Process sdp = System.Diagnostics.Process.Start(_MergedPfd.MergedFileName); - if (sdp != null) // B2020-055 if the current .NET version does not recognize the program used to display the PDF, it will return a NULL (ex. Microsoft Edge) - sdp.WaitForInputIdle(); + // B2020-055 if the current .NET version does not recognize the program used to display the PDF, it will return a NULL (ex. Microsoft Edge) + sdp?.WaitForInputIdle(); } } else if (VlnSettings.DebugMode) @@ -1416,7 +1282,7 @@ namespace VEPROMS { FlexibleMessageBox.Show("Completed Successfully", "Print All and Merge Procedures", MessageBoxButtons.OK, MessageBoxIcon.Information); } - this.Close(); + Close(); } private void cbxAssignRevToAllMergedPrcs_CheckedChanged(object sender, EventArgs e) @@ -1428,10 +1294,5 @@ namespace VEPROMS _NewRevForAllProcs = null; } - - //private void cbxDebug_CheckedChanged(object sender, EventArgs e) - //{ - // cbxCmpPRMSpfd.Visible = cbxDebug.Checked; - //} } } diff --git a/PROMS/VEPROMS User Interface/GlobalSuppressions.cs b/PROMS/VEPROMS User Interface/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/VEPROMS User Interface/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/VEPROMS User Interface/Program.cs b/PROMS/VEPROMS User Interface/Program.cs index f21f5b86..d5b006bf 100644 --- a/PROMS/VEPROMS User Interface/Program.cs +++ b/PROMS/VEPROMS User Interface/Program.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Windows.Forms; -using Volian.Base.Library; namespace VEPROMS { diff --git a/PROMS/VEPROMS User Interface/ShortcutLists.cs b/PROMS/VEPROMS User Interface/ShortcutLists.cs index 04d67f85..d789475e 100644 --- a/PROMS/VEPROMS User Interface/ShortcutLists.cs +++ b/PROMS/VEPROMS User Interface/ShortcutLists.cs @@ -1,12 +1,5 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.IO; using System.Windows.Forms; -using DevComponents.DotNetBar; namespace VEPROMS { diff --git a/PROMS/VEPROMS User Interface/VEPROMS_UI.csproj b/PROMS/VEPROMS User Interface/VEPROMS_UI.csproj index f9ed6495..1f8bee14 100644 --- a/PROMS/VEPROMS User Interface/VEPROMS_UI.csproj +++ b/PROMS/VEPROMS User Interface/VEPROMS_UI.csproj @@ -154,18 +154,12 @@ AboutVEPROMS.cs - Form dlgAnnotationsSelect.cs - - True - True - dlgAnnotationsSelect.resx - Form @@ -349,6 +343,7 @@ frmVersionsProperties.cs + Designer diff --git a/PROMS/VEPROMS User Interface/VlnWeb.cs b/PROMS/VEPROMS User Interface/VlnWeb.cs index bccd40cb..08047b69 100644 --- a/PROMS/VEPROMS User Interface/VlnWeb.cs +++ b/PROMS/VEPROMS User Interface/VlnWeb.cs @@ -1,9 +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 VEPROMS diff --git a/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs b/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs index fa07de4f..56682572 100644 --- a/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs +++ b/PROMS/VEPROMS User Interface/dlgApproveProcedure.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; @@ -21,11 +20,7 @@ namespace VEPROMS public partial class dlgApproveProcedure : Form { public event DisplayConsistencyReportEvent ConsistencyPrintRequest; - private void OnConsistencyPrintRequest(ConsistencyReportArgs args) - { - if (ConsistencyPrintRequest != null) - ConsistencyPrintRequest(this, args); - } + private void OnConsistencyPrintRequest(ConsistencyReportArgs args) => ConsistencyPrintRequest?.Invoke(this, args); private bool CanApprove { get { return btnApprove2.Enabled; } @@ -37,12 +32,8 @@ namespace VEPROMS tsslStatus.Text = value ? "" : "Need to correct the Rev Numbers marked with Question Marks"; } } - private int _ApplicabilityIndex = 0; - public int ApplicabilityIndex - { - get { return _ApplicabilityIndex; } - set { _ApplicabilityIndex = value; } - } + + public int ApplicabilityIndex { get; set; } = 0; private SessionInfo _MySessionInfo; public SessionInfo MySessionInfo { @@ -53,23 +44,19 @@ namespace VEPROMS _MyApproval.MySessionInfo = _MySessionInfo; } } - private ApprovalInfo _MyApproval; - private DocVersionInfo _MyDocVersion; - frmVEPROMS _MyFrmVEPROMS = null; - public frmVEPROMS MyFrmVEPROMS - { - get { return _MyFrmVEPROMS; } - set { _MyFrmVEPROMS = value; } - } - private bool _initializing = false; // C2018-008 redesign of user interface + private readonly ApprovalInfo _MyApproval; + private readonly DocVersionInfo _MyDocVersion; + + public frmVEPROMS MyFrmVEPROMS { get; set; } = null; + private readonly bool _initializing = false; // C2018-008 redesign of user interface public dlgApproveProcedure(DocVersionInfo myDocVersion, frmVEPROMS myFrmVEPROMS) // approve all procedures { MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing _MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing ApplicabilityIndex = myDocVersion.DocVersionConfig.SelectedSlave; _MyApproval.SavedSlave = ApplicabilityIndex; - this.ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); - this.ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); + ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); + ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); _MyDocVersion = myDocVersion; _MyDocVersion.ResetProcedures(); // B2021-035: Pasted, modified number and deleted procedures not refreshed so missing from list InitializeComponent(); @@ -77,7 +64,7 @@ namespace VEPROMS _MyApproval.StatusUpdated -= new ApprovalStatusChangeEvent(_MyApproval_StatusUpdated); _MyApproval.StatusUpdated += new ApprovalStatusChangeEvent(_MyApproval_StatusUpdated); SetupComboBoxes(); - foreach (ProcedureInfo pi in myDocVersion.Procedures) + foreach (ProcedureInfo pi in myDocVersion.Procedures.OfType()) { bool includeProc = pi.ApplInclude(ApplicabilityIndex); // C2021-027: Procedure level PC/PC if (includeProc) @@ -98,31 +85,8 @@ namespace VEPROMS private void FlexGridAddEvents() { - //fgProcs.ChangeEdit += new EventHandler(fgProcs_ChangeEdit); - //Console.WriteLine(fgProcs.ComboBoxEditor.GetType().Name); - //Console.WriteLine(fgProcs.Editor.GetType().Name); - //fgProcs.ImeModeChanged += new EventHandler(fgProcs_ImeModeChanged); - //fgProcs.LeaveEdit += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_LeaveEdit); - //fgProcs.SetupEditor += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_SetupEditor); - //fgProcs.StartEdit += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_StartEdit); - //fgProcs.ValidateEdit += new C1.Win.C1FlexGrid.ValidateEditEventHandler(fgProcs_ValidateEdit); fgProcs.ComboCloseUp -= new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_ComboCloseUp); fgProcs.ComboCloseUp += new C1.Win.C1FlexGrid.RowColEventHandler(fgProcs_ComboCloseUp); - //fgProcs.MouseDown += new MouseEventHandler(fgProcs_MouseDown); - //fgProcs.MouseUp += new MouseEventHandler(fgProcs_MouseUp); - } - - void fgProcs_MouseUp(object sender, MouseEventArgs e) - { - C1.Win.C1FlexGrid.HitTestInfo hti = fgProcs.HitTest(e.X, e.Y); - //Console.WriteLine("fgProcs_MouseUp X={0},Y={1},Row={2},Col={3}", e.X, e.Y, hti.Row, hti.Column); - } - - void fgProcs_MouseDown(object sender, MouseEventArgs e) - { - C1.Win.C1FlexGrid.HitTestInfo hti = fgProcs.HitTest(e.X, e.Y); - //Console.WriteLine("fgProcs_MouseDown X={0},Y={1},Row={2},Col={3}", e.X, e.Y, hti.Row, hti.Column); - } void fgProcs_ComboCloseUp(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) @@ -134,46 +98,6 @@ namespace VEPROMS //Console.WriteLine("fgProcs_ComboCloseUp row: {0}, col: {1}, val: {2}, etostring: {3}", e.Row, e.Col, fgProcs[e.Row, e.Col], e.ToString()); } - void fgProcs_ValidateEdit(object sender, C1.Win.C1FlexGrid.ValidateEditEventArgs e) - { - //Console.WriteLine("fgProcs_ValidateEdit"); - } - - void fgProcs_StartEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) - { - - object val = fgProcs[e.Row, e.Col]; - DateTime dt = (DateTime)val; - if (dt != null) - dt = dt.AddHours(1); - fgProcs[e.Row, e.Col] = dt; - //Console.WriteLine("fgProcs_StartEdit val: {0}, dt: {1}", val, dt); - } - - void fgProcs_SetupEditor(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) - { - //Console.WriteLine("fgProcs_SetupEditor"); - } - - void fgProcs_LeaveEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) - { - object val = fgProcs[e.Row, e.Col]; - DateTime dt = (DateTime)val; - if (dt != null && dt.Hour != 0) - dt = dt.AddHours(-1); - fgProcs[e.Row, e.Col] = dt; - //Console.WriteLine("fgProcs_LeaveEdit val: {0}, dt: {1}, mouserow={2}, mousecol={3}", val, dt, fgProcs.MouseRow, fgProcs.MouseCol); - } - - void fgProcs_ImeModeChanged(object sender, EventArgs e) - { - //Console.WriteLine("fgProcs_ImeModeChanged"); - } - - void fgProcs_ChangeEdit(object sender, EventArgs e) - { - //Console.WriteLine("fgProcs_ChangeEdit"); - } //C2020-036 returns a string of duplicate procedure numbers separated by newlines for use in FlexibleMessageBox private string dupProcList { @@ -183,12 +107,13 @@ namespace VEPROMS if (dpl.Count > 0) { foreach (string pn in dpl) - rtn += pn + "\n"; + rtn += $"{pn}\n"; rtn = rtn.TrimEnd('\n'); } return rtn; } } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private List dpl = new List(); //C2020-036 used to create list duplicate procedure numbers private bool InitializePanelSelect() @@ -196,7 +121,7 @@ namespace VEPROMS if (clbMore.Items.Count == 0) { dpl.Clear(); - foreach (ProcedureInfo pi in _MyDocVersion.Procedures) + foreach (ProcedureInfo pi in _MyDocVersion.Procedures.OfType()) { bool includeProc = pi.ApplInclude(ApplicabilityIndex); // C2021-027: Procedure level PC/PC if (includeProc) @@ -245,22 +170,22 @@ namespace VEPROMS lblViewPDF.Enabled = false; if (_MyApproval.MyProcedures.Count == 1) { - this.Text = "Approve " + _MyApproval.MyProcedures[0].ProcInfo.DisplayNumber; + Text = "Approve " + _MyApproval.MyProcedures[0].ProcInfo.DisplayNumber; swtbtViewPDF.Value = false; swtbtViewPDF.Enabled = true; lblViewPDF.Enabled = true; } else if (_MyApproval.MyProcedures.Count == _MyDocVersion.Procedures.Count) - this.Text = "Approve All Procedures"; + Text = "Approve All Procedures"; else - this.Text = "Approve Selected Procedures"; + Text = "Approve Selected Procedures"; } private void InitializePanelApprove() { setupLablesAndSwitches(); // C2018-008 redesign of user interface SetupMyApproval(); } - + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private Dictionary tmpProcedures = new Dictionary(); private ProcedureInfo GetProcedureInfoByKey(string key) { @@ -277,12 +202,13 @@ namespace VEPROMS return tmpProcedures[GetDisplayNumberOnly(key)]; } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "selectsome Kept for Legacy - To give Constructor a different Signature")] public dlgApproveProcedure(DocVersionInfo myDocVersion, bool selectSome, frmVEPROMS myFrmVEPROMS) // approve some procedures { MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing _MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing - this.ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); - this.ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); + ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); + ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); _MyDocVersion = myDocVersion; _MyDocVersion.ResetProcedures(); // B2021-035: Pasted, modified number and deleted procedures not refreshed so missing from list InitializeComponent(); @@ -303,8 +229,8 @@ namespace VEPROMS { MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing _MyApproval = new ApprovalInfo(myFrmVEPROMS);// Save frmVEPROMS for Import to shutoff SessionPing - this.ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); - this.ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); + ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); + ConsistencyPrintRequest += new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); _MyDocVersion = myProcedure.MyDocVersion; _MyDocVersion.ResetProcedures(); // B2021-035: Pasted, modified number and deleted procedures not refreshed so missing from list ApplicabilityIndex = _MyDocVersion.DocVersionConfig.SelectedSlave; // B2022-033 set the child being approved or workflow so other procedure list can populate @@ -328,12 +254,7 @@ namespace VEPROMS } _initializing = false; } - private bool ProcedureSetHasDuplicateProcedureNumbers() - { - bool hasDuplicateProcNums = false; - return hasDuplicateProcNums; - } void _MyApproval_StatusUpdated(ApprovalInfo sender, ApprovalMessageArgs e) { tsslMsg2.Text = e.MyStatus; @@ -342,33 +263,16 @@ namespace VEPROMS private void SetupMyApproval() { approvalInfoBindingSource.DataSource = _MyApproval; - //if(_MyApproval.MyProcedures.Count == 1) - // lblOldRevNumber.Text = _MyApproval.RevNumber; - //else if (_MyApproval.MyProcedures.Count > 1) - // lblMaxRevNumber1.Text = GetMaxRevNumber(); - _MyApproval.RevType = 1; // C2018-008 redesign of user interface //(revTypeBindingSource.Current as RevType).TypeID; + _MyApproval.RevType = 1; // C2018-008 redesign of user interface _MyApproval.RevStage = (stageInfoBindingSource.Current == null) ? 0 : (stageInfoBindingSource.Current as StageInfo).StageID;// C2018-008 redesign of user interface approvalInfoBindingSource.ResetBindings(false); approvalProcedureBindingSource.DataSource = _MyApproval.MyProcedures; approvalProcedureBindingSource.ResetBindings(false); - //this.ConsistencyPrintRequest -= new DisplayConsistencyReportEvent(dlgApproveProcedure_ConsistencyPrintRequest); - } - - private string GetMaxRevNumber() - { - string mrn = string.Empty; - foreach (ApprovalProcedure ap in _MyApproval.MyProcedures) - { - int k = _MyApproval.FancyShmancyRevCompare(mrn, ap.RevNumber); - if (k < 0) - mrn = ap.RevNumber; - } - return mrn; } void dlgApproveProcedure_ConsistencyPrintRequest(object sender, ConsistencyReportArgs args) { - foreach (ProcedureInfo pi in args.MyItems) + foreach (ProcedureInfo pi in args.MyItems.OfType()) pi.IsSelected = _MyApproval.ProcedureExists(pi); PDFConsistencyCheckReport rpt = new PDFConsistencyCheckReport(args.ReportName, args.MyItems, args.MyDocVersion); //B2020-020 needed to pass in DocVersion to get paper size from format rpt.BuildReport(); @@ -389,20 +293,12 @@ namespace VEPROMS private void btnApprove_Click(object sender, EventArgs e) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; if(!_MyApproval.Approve(new Point(Left,Bottom),cmbRevisionStage2.Text)) // C2021-020 pass in the revision stage name - this.DialogResult = DialogResult.None; - this.Cursor = Cursors.Default; + DialogResult = DialogResult.None; + Cursor = Cursors.Default; } - // C2018-008 redesign of user interface - // -- Note that the Revison Type data source is still connected (revTypeBindingSource) - commented out for documentatin purposes - //private void cmbRevisionType_SelectedIndexChanged(object sender, EventArgs e) - //{ - // RevType rt = cmbRevisionType2.SelectedItem as RevType; - // _MyApproval.RevType = rt.TypeID; - //} - private void cmbRevisionStage_SelectedIndexChanged(object sender, EventArgs e) { StageInfo si = cmbRevisionStage2.SelectedItem as StageInfo; @@ -431,7 +327,6 @@ namespace VEPROMS SetupComboBoxes(); for (int i = 0; i < clbMore.Items.Count; i++) { - string xyz = clbMore.Items[i].ToString(); ProcedureInfo pi = GetProcedureInfoByKey(clbMore.Items[i].ToString()); if (clbMore.GetItemChecked(i)) { @@ -449,10 +344,7 @@ namespace VEPROMS RefreshCount(); // B2021-015: select/clear all not populating left panel & count not refreshed. } - private void btnCheck_Click(object sender, EventArgs e) - { - UpdateClbMore(); - } + private void btnCheck_Click(object sender, EventArgs e) => UpdateClbMore(); private ItemInfoList _MyItemInfoList; private void UpdateClbMore() @@ -485,7 +377,7 @@ namespace VEPROMS if (info.Contains(" - (")) clbMore.Items[i] = info.Substring(0, info.IndexOf(" - (")); } - foreach (ProcedureInfo npi in _MyItemInfoList) + foreach (ProcedureInfo npi in _MyItemInfoList.OfType()) { string info = string.Format("{0} - ({1})", npi.DisplayNumber, npi.MyDifferenceReasons); //checked list box @@ -506,7 +398,7 @@ namespace VEPROMS for (int i = 0; i < clbMore.Items.Count; i++) { if (!clbMore.Items[i].ToString().Contains(" - (")) - clbMore.Items[i] = clbMore.Items[i].ToString() + " - (none)"; + clbMore.Items[i] = $"{clbMore.Items[i]} - (none)"; } Application.DoEvents(); clbMore.Enabled = btnAll.Enabled = btnClear.Enabled = true; @@ -523,10 +415,7 @@ namespace VEPROMS } } // B2021-015: select/clear all not populating left panel & count not refreshed. - private void RefreshCount() - { - lblMore.Text = string.Format("{0} Procedures, {1} Selected", clbMore.Items.Count, clbMore.CheckedItems.Count); - } + private void RefreshCount() => lblMore.Text = string.Format("{0} Procedures, {1} Selected", clbMore.Items.Count, clbMore.CheckedItems.Count); void ItemInfoList_ConsistencyCheckUpdated(object sender, ItemInfoListCCEventArgs args) { @@ -572,14 +461,12 @@ namespace VEPROMS if (clbMore.Items[itemIndex] != null) { SuperTooltipInfo stti = sttMore.GetSuperTooltip(clbMore); - //string headerText = tmpProcedures[xyz].DisplayNumber; - //string bodyText = tmpProcedures[xyz].MyDifferencesText; stti.HeaderText = GetProcedureInfoByKey(clbMore.Items[itemIndex].ToString()).DisplayNumber; stti.BodyText = GetProcedureInfoByKey(clbMore.Items[itemIndex].ToString()).MyDifferencesText; stti.FooterVisible = false; using (Graphics g = CreateGraphics()) { - SizeF sf = g.MeasureString(stti.BodyText, this.Font); + SizeF sf = g.MeasureString(stti.BodyText, Font); stti.CustomSize = new Size(10 + sf.ToSize().Width, 0); } sttMore.ShowTooltip(sender); @@ -611,10 +498,7 @@ namespace VEPROMS } - private void btnReportMore_Click(object sender, EventArgs e) - { - OnConsistencyPrintRequest(new ConsistencyReportArgs(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\MyConsistency.pdf", _MyItemInfoList, _MyDocVersion)); //B2020-020 needed to pass in DocVersion to get paper size from format - } + private void btnReportMore_Click(object sender, EventArgs e) => OnConsistencyPrintRequest(new ConsistencyReportArgs(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\MyConsistency.pdf", _MyItemInfoList, _MyDocVersion)); //B2020-020 needed to pass in DocVersion to get paper size from format private void fgProcs_AfterEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) { @@ -724,19 +608,16 @@ namespace VEPROMS private void expAddProcConChk_ExpandedChanged(object sender, ExpandedChangeEventArgs e) // C2018-008 redesign of user interface { if (expAddProcConChk.Expanded) - this.Size = new Size(this.Size.Width + (expAddProcConChk.Size.Width - expAddProcConChk.TitlePanel.Size.Height), this.Size.Height); + Size = new Size(Size.Width + (expAddProcConChk.Size.Width - expAddProcConChk.TitlePanel.Size.Height), Size.Height); } private void expAddProcConChk_ExpandedChanging(object sender, ExpandedChangeEventArgs e) // C2018-008 redesign of user interface { if (expAddProcConChk.Expanded) - this.Size = new Size(this.Size.Width - (expAddProcConChk.Size.Width - expAddProcConChk.TitlePanel.Size.Height), this.Size.Height); + Size = new Size(Size.Width - (expAddProcConChk.Size.Width - expAddProcConChk.TitlePanel.Size.Height), Size.Height); } - private void fgProcs_AfterDataRefresh(object sender, ListChangedEventArgs e) - { - btnApprove2.Enabled = CanApprove && tsslStatus.Text.Length == 0; // B2016-057 If did un-successful Auto Increament Rev Number, then don't enable Approve (Do Work Flow) button - } + private void fgProcs_AfterDataRefresh(object sender, ListChangedEventArgs e) => btnApprove2.Enabled = CanApprove && tsslStatus.Text.Length == 0; // B2016-057 If did un-successful Auto Increament Rev Number, then don't enable Approve (Do Work Flow) button // C2020-040 automatically update left panel when tree item in right panel is selected or deselected private void clbMore_SelectedIndexChanged(object sender, EventArgs e) @@ -758,18 +639,11 @@ namespace VEPROMS } private void clbMore_MouseLeave(object sender, EventArgs e) //C2020-045 - added switch to control if pop-ups are displayed in procedure list - { - sttMore.Enabled = true; - } +=> sttMore.Enabled = true; } public class ApprovalProcedure { - private ProcedureInfo _ProcInfo; - public ProcedureInfo ProcInfo - { - get { return _ProcInfo; } - set { _ProcInfo = value; } - } + public ProcedureInfo ProcInfo { get; set; } private string _RevNumber; public string RevNumber { @@ -779,37 +653,17 @@ namespace VEPROMS if (value.Trim() != _RevNumber) { _RevNumber = value.Trim(); - //_RevDate = DateTime.Now; // commented out for bug fix B2013-012 } } } - private DateTime _RevDate; - public DateTime RevDate - { - get { return _RevDate; } - set { _RevDate = value; } - } + + public DateTime RevDate { get; set; } // added RevNumAndDate to handle the use use of the DoRevDate flag // this fixes bug B2013-011 where Today's date would print on the approved procedures (Westinghouse data) // instead of the the Revision Date assigned to the procedure. - public string RevNumAndDate - { - get - { - if (_ProcInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate) - return RevNumber + "/" + RevDate.ToString("M/d/yyyy"); - else - return RevNumber; - } - } - public string DisplayNumber - { - get { return _ProcInfo.DisplayNumber; } - } - public override string ToString() - { - return string.Format("{0}\t{1}\t{2:M/d/yyyy}", _ProcInfo.DisplayNumber, _RevNumber, _RevDate); - } + public string RevNumAndDate => ProcInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate ? $"{RevNumber}/{RevDate:M/d/yyyy}" : RevNumber; + public string DisplayNumber => ProcInfo.DisplayNumber; + public override string ToString() => string.Format("{0}\t{1}\t{2:M/d/yyyy}", ProcInfo.DisplayNumber, _RevNumber, RevDate); public ApprovalProcedure(ProcedureInfo proc) { proc.ProcedureConfig.SelectedSlave = proc.MyDocVersion.DocVersionConfig.SelectedSlave; @@ -818,105 +672,42 @@ namespace VEPROMS string sRevDate = proc.ProcedureConfig.Print_RevDate; if (sRevDate == string.Empty) sRevDate = DateTime.Now.ToString("M/d/y"); - DateTime revDate; - if (!DateTime.TryParse(sRevDate, out revDate)) revDate = DateTime.Now; + if (!DateTime.TryParse(sRevDate, out DateTime revDate)) revDate = DateTime.Now; RevDate = revDate; } } public class ApprovalMessageArgs : EventArgs { - public ApprovalMessageArgs(string msg) - { - _MyStatus = msg; - } - private string _MyStatus; - public string MyStatus - { - get { return _MyStatus; } - set { _MyStatus = value; } - } + public ApprovalMessageArgs(string msg) => MyStatus = msg; + + public string MyStatus { get; set; } } public delegate void ApprovalStatusChangeEvent(ApprovalInfo sender, ApprovalMessageArgs e); public class ApprovalInfo { - frmVEPROMS _MyFrmVEPROMS = null; - public frmVEPROMS MyFrmVEPROMS - { - get { return _MyFrmVEPROMS; } - set { _MyFrmVEPROMS = value; } - } + public frmVEPROMS MyFrmVEPROMS { get; set; } = null; public event ApprovalStatusChangeEvent StatusUpdated; - public void OnStatusUpdated(ApprovalInfo sender, ApprovalMessageArgs e) - { - if (StatusUpdated != null) - StatusUpdated(sender, e); - } - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } - private int _RevType; - public int RevType - { - get { return _RevType; } - set { _RevType = value; } - } - private string _RevNumber; - public string RevNumber - { - get { return _RevNumber; } - set { _RevNumber = value; } - } - private Nullable _RevDate; - public Nullable RevDate + public void OnStatusUpdated(ApprovalInfo sender, ApprovalMessageArgs e) => StatusUpdated?.Invoke(sender, e); + + public SessionInfo MySessionInfo { get; set; } + public int RevType { get; set; } + public string RevNumber { get; set; } + private DateTime? _RevDate; + public DateTime? RevDate { get { return _RevDate == null ? _RevDate : _RevDate.Value; } set { _RevDate = value; } } - private int _RevStage; - public int RevStage - { - get { return _RevStage; } - set { _RevStage = value; } - } - private string _RevNote; - public string RevNote - { - get { return _RevNote; } - set { _RevNote = value; } - } - private bool _ViewPDF; - public bool ViewPDF - { - get { return _ViewPDF; } - set { _ViewPDF = value; } - } - private string _MsgNumber; - public string MsgNumber - { - get { return _MsgNumber; } - set { _MsgNumber = value; } - } - private string _MsgDate; - public string MsgDate - { - get { return _MsgDate; } - set { _MsgDate = value; } - } - private bool _CanIncrement; - public bool CanIncrement - { - get { return _CanIncrement; } - set { _CanIncrement = value; } - } + + public int RevStage { get; set; } + public string RevNote { get; set; } + public bool ViewPDF { get; set; } + public string MsgNumber { get; set; } + public string MsgDate { get; set; } + public bool CanIncrement { get; set; } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private List _MyProcedures; - public List MyProcedures - { - get { return _MyProcedures; } - //set { _MyProcedures = value; } - } + public List MyProcedures => _MyProcedures; //B2026-058 - If approving multiple procedures at the same time with a multiunit set and one of the procedures is open, PROMS sometimes loses that it is set for an individual unit. // this will save the SectedSlave in case a refresh causes it to get lost @@ -927,10 +718,6 @@ namespace VEPROMS MyFrmVEPROMS = myFrmVEPROMS;// Save frmVEPROMS for Import to shutoff SessionPing _MyProcedures = new List(); } - private static string FormatRev(Match m) - { - return "".PadLeft(5 - m.Groups[1].Value.Length, '0') + m.Groups[1].Value; - } public void AddProcedure(ProcedureInfo proc) { ApprovalProcedure ap = new ApprovalProcedure(proc); @@ -963,64 +750,11 @@ namespace VEPROMS public void Refresh() { bool ok = true; - int rv = 0; foreach (ApprovalProcedure ap in MyProcedures) { - ok = ok && int.TryParse(ap.RevNumber, out rv); + ok = ok && int.TryParse(ap.RevNumber, out int rv); } - _CanIncrement = ok; - //if (MyProcedures.Count == 1) - //{ - // ProcedureInfo pi = _MyProcedures[0].ProcInfo; - // RevNumber = pi.ProcedureConfig.Print_Rev == string.Empty ? "0" : pi.ProcedureConfig.Print_Rev; - // DateTime revdate = pi.ProcedureConfig.Print_RevDate == string.Empty ? DateTime.Now : DateTime.TryParse(pi.ProcedureConfig.Print_RevDate, out revdate) ? revdate : DateTime.Now; - // RevDate = revdate; - // RevNote = string.Empty; - // ViewPDF = false; - //} - //else if (MyProcedures.Count > 1) - //{ - // Regex myRegEx = new Regex("^([0-9]{1,5})"); - // SortedList printRevs = new SortedList(); - // SortedList printRevDates = new SortedList(); - // string printRev = string.Empty; - // foreach (ApprovalProcedure pi in MyProcedures) - // { - // printRev = myRegEx.Replace(pi.RevNumber, new MatchEvaluator(FormatRev)); - // printRev = printRev == string.Empty ? "0" : printRev; - // if (printRev != string.Empty) - // if (!printRevs.ContainsKey(printRev)) - // printRevs.Add(printRev, pi.ProcInfo); - // if (pi.RevDate != null) - // if (!printRevDates.ContainsKey(pi.RevDate.ToString())) - // printRevDates.Add(pi.RevDate.ToString(), pi.ProcInfo); - // } - // if (printRevs.Count > 1) - // { - // ProcedureInfo pi = printRevs[printRevs.Keys[printRevs.Count - 1]]; - // RevNumber = "*"; - // MsgNumber = "Multiple Revision Numbers found. Enter asterisk (*) to use current revision numbers or plus sign (+) to increment revision numbers"; - // } - // else if (printRevs.Count == 1) - // { - // ProcedureInfo pi = printRevs[printRevs.Keys[printRevs.Count - 1]]; - // RevNumber = pi.ProcedureConfig.Print_Rev; - // MsgNumber = string.Empty; - // } - // if (printRevDates.Count > 1) - // { - // RevDate = null; - // MsgDate = "Multiple Revision Dates found. Use current revision dates or manually assign revision date by selecting a date"; - // } - // else if (printRevDates.Count == 1) - // { - // ProcedureInfo pi = printRevDates[printRevDates.Keys[printRevDates.Count - 1]]; - // RevDate = DateTime.Parse(pi.ProcedureConfig.Print_RevDate); - // MsgDate = string.Empty; - // } - // else if (printRevDates.Count == 0) - // RevDate = DateTime.Now; - //} + CanIncrement = ok; } public void DeleteProcedure(ProcedureInfo pi) { @@ -1036,10 +770,7 @@ namespace VEPROMS Refresh(); } } - public bool CanApprove - { - get { return _RevType > 0 && _RevNumber != string.Empty && _RevStage > 0; } - } + public bool CanApprove => RevType > 0 && RevNumber != string.Empty && RevStage > 0; public int FancyShmancyRevCompare(string s1, string s2) { if (s1 == s2) @@ -1164,13 +895,13 @@ namespace VEPROMS if (MessageBox.Show(sb.ToString(),string.Format("Revert to {0}",nsi.Name),MessageBoxButtons.YesNo,MessageBoxIcon.Stop) == DialogResult.No) return false; } + + DialogResult doSumChgDR = FlexibleMessageBox.Show("Do you want to save the Summary of Changes along with the Approved PDF?\r\n\r\nSelecting 'Cancel' will cancel the approval process.", "Create Summary of Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);// == DialogResult.Yes; + if (doSumChgDR == DialogResult.Cancel) return false; // C2018-007: When performing more than a single procedure approval (approve all or some), only prompt once whether to include // Summary of Changes (use the following 2 flags, code using them is below) // C2022-022: Moved the prompt once for Summary of changes out of loop and allow user to cancel, go back to approval dialog - bool doSumChg = false; - DialogResult doSumChgDR = FlexibleMessageBox.Show("Do you want to save the Summary of Changes along with the Approved PDF?\r\n\r\nSelecting 'Cancel' will cancel the approval process.", "Create Summary of Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);// == DialogResult.Yes; - if (doSumChgDR == DialogResult.Cancel) return false; - doSumChg = doSumChgDR == DialogResult.Yes; + bool doSumChg = doSumChgDR == DialogResult.Yes; List procsApproved = new List(); foreach (ApprovalProcedure ap in MyProcedures) { @@ -1186,9 +917,8 @@ namespace VEPROMS //B2026-058 - If approving multiple procedures at the same time with a multiunit set and one of the procedures is open, PROMS sometimes loses that it is set for an individual unit. ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave = SavedSlave; } - procsApproved.Add(ap.ProcInfo.DisplayNumber + " " + ap.ProcInfo.DisplayText); + procsApproved.Add($"{ap.ProcInfo.DisplayNumber} {ap.ProcInfo.DisplayText}"); RevisionInfo ric = pi.MyDocVersion.DocVersionConfig.SelectedSlave > 0 ? RevisionInfo.GetCurrentByItemIDandUnitID(pi.ItemID, pi.MyDocVersion.DocVersionConfig.SelectedSlave) : RevisionInfo.GetCurrentByItemID(pi.ItemID); - // RevisionInfo rip = RevisionInfo.GetPreviousByItemID(pi.ItemID); DateTime myDTS = pi.DTS; // pi.DTS is date of last approval string cbDTS = (pi.MyConfig as ProcedureConfig).Print_ChangeBarDate; // pi.DTS was the field that was used to store the approval date before master/slave code was added. Use ChangeBarDate if it is set - this is set either manually if no approval date (from treeview menu) or @@ -1203,7 +933,6 @@ namespace VEPROMS if (ap.RevNumber == ric.RevisionNumber) { myDTS = ric.MyConfig.History_StartDate; - //UpdateProcedureDTS(pi, myDTS); } // New approval, i.e. not same revision number, use the date from the latest approved version else @@ -1211,26 +940,24 @@ namespace VEPROMS myDTS = ric.LatestVersion.DTS; // B2019-051: Extra info in Change Summary. Use the last 'approved' (ric.LatestVersion.MyStage.IsApproved==1) } } - Revision revision = null; + Revision revision; if (ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave > 0) { revision = Revision.GetByItemIDAndRevisionNumberAndUnitID(pi.ItemID, ap.RevNumber, ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave); if (revision == null) // no revision yet, need to set the StartDate & which slave { - RevisionConfig cfg = new RevisionConfig(); - cfg.History_StartDate = myDTS; // if there is a slave, date found from above code - cfg.Applicability_Index = ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave; - //cfg.Save(); + RevisionConfig cfg = new RevisionConfig + { + History_StartDate = myDTS, // if there is a slave, date found from above code + Applicability_Index = ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave + }; revision = Revision.MakeRevision(pi.ItemID, RevType, ap.RevNumber, ap.RevDate, RevNote, cfg.ToString(), now, Volian.Base.Library.VlnSettings.UserID); - // revision.MyConfig.History_StartDate = pi.DTS; - // revision.MyConfig.Save(); - // revision = revision.Save(); } else if (revision.Notes != RevNote || revision.RevisionDate != ap.RevDate) { //C2016-036 - Inform the user that an existing approved version will be replaced //C2022-016 - Improve/clarify the dialog message - if (MessageBox.Show("Replace Existing Revision " + ap.RevNumber + "?\r\n\r\nTo create a new revision, click Cancel then change\r\nthe Rev. Number.", "Replace Existing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) + if (MessageBox.Show($"Replace Existing Revision {ap.RevNumber}?\r\n\r\nTo create a new revision, click Cancel then change\r\nthe Rev. Number.", "Replace Existing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return false; revision.Notes = RevNote; revision.RevisionDate = ap.RevDate; @@ -1245,19 +972,17 @@ namespace VEPROMS // went wrong, the revision could be created but not the version. Added the count check below. if (revision == null || revision.RevisionVersionCount==0) // no revision yet, need to set the StartDate. If there is a revision, it uses the revision date as the startdate { - RevisionConfig cfg = new RevisionConfig(); - cfg.History_StartDate = pi.DTS; // todo: this should probably be myDTS, found during fix of B2019-051. - //cfg.Save(); + RevisionConfig cfg = new RevisionConfig + { + History_StartDate = pi.DTS // todo: this should probably be myDTS, found during fix of B2019-051. + }; revision = Revision.MakeRevision(pi.ItemID, RevType, ap.RevNumber, ap.RevDate, RevNote, cfg.ToString(), now, Volian.Base.Library.VlnSettings.UserID); - // revision.MyConfig.History_StartDate = pi.DTS; - // revision.MyConfig.Save(); - // revision = revision.Save(); } else if (revision.Notes != RevNote || revision.RevisionDate != ap.RevDate) { //C2016-036 - Inform the user that an existing approved version will be replaced //C2022-016 - Improve/clarify the dialog message - if (MessageBox.Show("Replace Existing Revision " + ap.RevNumber + "?\r\n\r\nTo create a new revision, click Cancel then change\r\nthe Rev. Number.", "Replace Existing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) + if (MessageBox.Show($"Replace Existing Revision {ap.RevNumber}?\r\n\r\nTo create a new revision, click Cancel then change\r\nthe Rev. Number.", "Replace Existing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) return false; revision.Notes = RevNote; revision.RevisionDate = ap.RevDate; @@ -1268,10 +993,7 @@ namespace VEPROMS //B2017-149 Allow the user to choose if they want the Summary of Changes report created during the approval process if (doSumChg) summaryBuf = CreateSummary(ref pi, summaryPDF, myDTS); DateTime currentDTS = now; - Check check = Check.MakeCheck(revision, Stage.GetJustStage(RevStage), RevisionInfo.BuildRevisionChecks(pi), currentDTS, VlnSettings.UserID); - //make pdf with promsprinter and get byte stream - // Moved to end so that Item and Content are saved at the same time - //UpdateProcedureConfig(pi, ap.RevNumber, ap.RevDate, myDTS); + _ = Check.MakeCheck(revision, Stage.GetJustStage(RevStage), RevisionInfo.BuildRevisionChecks(pi), currentDTS, VlnSettings.UserID); string watermarkColor = "Blue"; // this is the default watermark color string waterMark = Stage.GetJustStage(RevStage).IsApproved > 0 ? null : Stage.GetJustStage(RevStage).Name; // C2022-004 - BNPP if doing an approval stage, and the format file uses the UseUnitWatermarkOnApproved format flag () @@ -1281,39 +1003,14 @@ namespace VEPROMS waterMark = "Unit Designator"; frmPDFStatusForm.SetUnitWatermark(MyProcedures[0].ProcInfo, ref waterMark, ref watermarkColor); } - //ProcedureInfo myproc = pi; - //frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumber, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location); - //myproc.ChangeBarDate = myDTS; frmPDFStatusForm frm = new frmPDFStatusForm(pi, ap.RevNumAndDate, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location, pi.MyDocVersion.DocVersionConfig.Print_AddBlankPagesWhenUsingDuplexFoldouts, true, "", false, 0, false, - MyProcedures.Count > (MyProcedures[0].ProcInfo.MyDocVersion.Procedures.Count / 4), pi.MyDocVersion.DocVersionConfig.Print_DuplexBlankPageText, null, watermarkColor); // C2019-004: Allow user to define duplex lank page text at the docversion level - frm.AllowAllWatermarks = true; - frm.CloseWhenDone = !ViewPDF; - frm.DocReplace = new Dictionary(); // will hold the Word Attachments with resolved ROs + MyProcedures.Count > (MyProcedures[0].ProcInfo.MyDocVersion.Procedures.Count / 4), pi.MyDocVersion.DocVersionConfig.Print_DuplexBlankPageText, null, watermarkColor) + { + AllowAllWatermarks = true, + CloseWhenDone = !ViewPDF, + DocReplace = new Dictionary() // will hold the Word Attachments with resolved ROs + }; // C2019-004: Allow user to define duplex lank page text at the docversion level frm.ShowDialog(); - //if (ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave > 0) - //{ - // using (ProcedureInfo myproc = ProcedureInfo.GetItemAndChildrenByUnit(pi.ItemID, 0, ap.ProcInfo.MyDocVersion.DocVersionConfig.SelectedSlave)) - // { - // //frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumber, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location); - // myproc.ChangeBarDate = myDTS; - // frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumAndDate, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location); - // frm.AllowAllWatermarks = true; - // frm.CloseWhenDone = !ViewPDF; - // frm.ShowDialog(); - // } - //} - //else - //{ - // using (ProcedureInfo myproc = ProcedureInfo.GetItemAndChildren(pi.ItemID)) - // { - // //frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumber, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location); - // myproc.ChangeBarDate = myDTS; - // frmPDFStatusForm frm = new frmPDFStatusForm(myproc, ap.RevNumAndDate, /* revdate change: ap.RevDate.ToString("MM/dd/yyyy") ,*/ waterMark, false, false, ViewPDF, true, VlnSettings.TemporaryFolder, new ChangeBarDefinition(pi.MyDocVersion.MyConfig as DocVersionConfig, pi.ActiveFormat), pdfTmp, location); - // frm.AllowAllWatermarks = true; - // frm.CloseWhenDone = !ViewPDF; - // frm.ShowDialog(); - // } - //} FileInfo pdfFile = new FileInfo(pdfPath); FileStream fs = pdfFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); byte[] buf = new byte[pdfFile.Length]; @@ -1333,8 +1030,10 @@ namespace VEPROMS return false; } - dlgExportImport dlg = new dlgExportImport("Export", pi, MyFrmVEPROMS, (selectedSlave)); // "true tell export to convert ROs and Transitions to text - dlg.DocReplace = frm.DocReplace; // this tells approval to prepare an export file with resolved transitions and ROs, word sections are saved with resolved ROs during approval PDF creation and saved in DocReplace + dlgExportImport dlg = new dlgExportImport("Export", pi, MyFrmVEPROMS, (selectedSlave)) + { + DocReplace = frm.DocReplace // this tells approval to prepare an export file with resolved transitions and ROs, word sections are saved with resolved ROs during approval PDF creation and saved in DocReplace + }; // "true tell export to convert ROs and Transitions to text System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); dlg.ExportItem(xd, pi, "procedure"); frm.DocReplace = dlg.DocReplace = null; @@ -1376,21 +1075,20 @@ namespace VEPROMS } else UpdateProcedureConfig(pi, ap.RevNumber, ap.RevDate, myDTS, selectedSlave); - //UpdateProcedureDTS(pi, DateTime.Now); pi.MyDocVersion.DocVersionConfig.SelectedSlave = selectedSlave; } // C2019-019: Put out a complete message when approval is done. // C2020-024 Display a more descriptive end message if (procsApproved.Count > 0) { - string msg = ""; + string msg; if (procsApproved.Count == (MyProcedures[0]).ProcInfo.MyDocVersion.Procedures.Count) msg = "All Procedures were Approved."; else { msg = "The following procedures were approved:\n"; foreach (string prc in procsApproved) - msg += "\n" + prc; + msg += $"\n{prc}"; } FlexibleMessageBox.Show( msg, "Approve Procedure(s)", MessageBoxButtons.OK); } @@ -1434,7 +1132,7 @@ namespace VEPROMS { while (!(ex is System.Data.SqlClient.SqlException) && ex.InnerException != null) ex = ex.InnerException; - MessageBox.Show(ex.Message +"\r\n\r\nApproval will continue without the Summary of Change Report", ex.GetType().Name + " while trying to create Summary of Changes." , MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show(ex.Message +"\r\n\r\nApproval will continue without the Summary of Change Report", $"{ex.GetType().Name} while trying to create Summary of Changes.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } } @@ -1456,7 +1154,7 @@ namespace VEPROMS StringBuilder sb = new StringBuilder(); sb.AppendLine("Could not create"); sb.AppendLine(); - sb.AppendLine(pdfFile + "."); + sb.AppendLine($"{pdfFile}."); sb.AppendLine(); sb.AppendLine("If it is open, close it then press the OK button."); if (cntr >= 3) // after two tries offer additional troubleshooting information @@ -1471,18 +1169,9 @@ namespace VEPROMS return true; } - private void UpdateProcedureDTS(ProcedureInfo pi, DateTime dts) - { - using (Item itm = Item.Get(pi.ItemID)) - { - itm.DTS = dts; - itm.Save(); - } - } private void UpdateProcedureConfig(ProcedureInfo procedureInfo, string revNumber, DateTime revDate, DateTime dts, int selectedSlave) { - ProcedureConfig pc = procedureInfo.MyConfig as ProcedureConfig; - if (pc == null) return; + if (!(procedureInfo.MyConfig is ProcedureConfig pc)) return; pc.SelectedSlave = selectedSlave; pc.Print_Rev = revNumber; @@ -1492,7 +1181,6 @@ namespace VEPROMS using (Item itm = Item.Get(procedureInfo.ItemID)) { itm.MyContent.Config = pc.ToString(); - //itm.DTS = dts; itm.UserID = Volian.Base.Library.VlnSettings.UserID; itm.Save(); @@ -1515,22 +1203,12 @@ namespace VEPROMS } public class RevType { - private int _TypeID; - public int TypeID - { - get { return _TypeID; } - set { _TypeID = value; } - } - private string _TypeName; - public string TypeName - { - get { return _TypeName; } - set { _TypeName = value; } - } + public int TypeID { get; set; } + public string TypeName { get; set; } public RevType(int i, string s) { - _TypeID = i; - _TypeName = s; + TypeID = i; + TypeName = s; } } public class RevTypes : List @@ -1539,29 +1217,14 @@ namespace VEPROMS public delegate void DisplayConsistencyReportEvent(object sender, ConsistencyReportArgs args); public class ConsistencyReportArgs : EventArgs { - private string _ReportName; - public string ReportName - { - get { return _ReportName; } - set { _ReportName = value; } - } - private ItemInfoList _MyItems; - public ItemInfoList MyItems - { - get { return _MyItems; } - set { _MyItems = value; } - } - private DocVersionInfo _MyDocVersion; - public DocVersionInfo MyDocVersion - { - get { return _MyDocVersion; } - set { _MyDocVersion = value; } - } + public string ReportName { get; set; } + public ItemInfoList MyItems { get; set; } + public DocVersionInfo MyDocVersion { get; set; } public ConsistencyReportArgs(string reportName, ItemInfoList myItems, DocVersionInfo myDocVerion) { - _ReportName = reportName; - _MyItems = myItems; - _MyDocVersion = myDocVerion; //B2020-020 needed to pass in DocVersion to get paper size from format + ReportName = reportName; + MyItems = myItems; + MyDocVersion = myDocVerion; //B2020-020 needed to pass in DocVersion to get paper size from format } } } diff --git a/PROMS/VEPROMS User Interface/dlgCheckOpenTabs.cs b/PROMS/VEPROMS User Interface/dlgCheckOpenTabs.cs index e4632efd..9596e70b 100644 --- a/PROMS/VEPROMS User Interface/dlgCheckOpenTabs.cs +++ b/PROMS/VEPROMS User Interface/dlgCheckOpenTabs.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 VEPROMS @@ -21,8 +14,8 @@ namespace VEPROMS private void btnTabs_Click(object sender, EventArgs e) { - Remember = this.cbRemember.Checked; - this.Close(); + Remember = cbRemember.Checked; + Close(); } } } diff --git a/PROMS/VEPROMS User Interface/dlgCheckedOutProcedure.cs b/PROMS/VEPROMS User Interface/dlgCheckedOutProcedure.cs index f8ae9089..64ad38d4 100644 --- a/PROMS/VEPROMS User Interface/dlgCheckedOutProcedure.cs +++ b/PROMS/VEPROMS User Interface/dlgCheckedOutProcedure.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; @@ -23,36 +19,22 @@ namespace VEPROMS _MySessionInfo = SessionInfo.Get(_MyOwnerInfo.SessionID); _MyUserInfo = ui; } - private ProcedureInfo _MyProcedureInfo; - public ProcedureInfo MyProcedureInfo - { - get { return _MyProcedureInfo; } - } - private SectionInfo _MySectionInfo; - public SectionInfo MySectionInfo - { - get { return _MySectionInfo; } - } - private OwnerInfo _MyOwnerInfo; - public OwnerInfo MyOwnerInfo - { - get { return _MyOwnerInfo; } - } - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - } - private UserInfo _MyUserInfo; - public UserInfo MyUserInfo - { - get { return _MyUserInfo; } - } - StringBuilder sb = new StringBuilder(); + private readonly ProcedureInfo _MyProcedureInfo; + public ProcedureInfo MyProcedureInfo => _MyProcedureInfo; + private readonly SectionInfo _MySectionInfo; + public SectionInfo MySectionInfo => _MySectionInfo; + private readonly OwnerInfo _MyOwnerInfo; + public OwnerInfo MyOwnerInfo => _MyOwnerInfo; + private readonly SessionInfo _MySessionInfo; + public SessionInfo MySessionInfo => _MySessionInfo; + private readonly UserInfo _MyUserInfo; + public UserInfo MyUserInfo => _MyUserInfo; + private void dlgCheckedOutProcedure_Load(object sender, EventArgs e) { - if (MyProcedureInfo != null) + StringBuilder sb = new StringBuilder(); + if (MyProcedureInfo != null) sb.AppendLine(string.Format("The procedure {0} - {1}", MyProcedureInfo.DisplayNumber, MyProcedureInfo.DisplayText)); else sb.AppendLine(string.Format("The document {0}", MySectionInfo.DisplayText)); @@ -74,7 +56,8 @@ namespace VEPROMS private void btnForce_Click(object sender, EventArgs e) { - MySessionInfo.CheckInItem(MyOwnerInfo.OwnerID); + StringBuilder sb = new StringBuilder(); + MySessionInfo.CheckInItem(MyOwnerInfo.OwnerID); sb.AppendLine(); sb.AppendLine("Forced Check In has been completed"); lblInfo.Text = sb.ToString(); diff --git a/PROMS/VEPROMS User Interface/dlgExportImport.cs b/PROMS/VEPROMS User Interface/dlgExportImport.cs index 1d5208e3..6da3ab4e 100644 --- a/PROMS/VEPROMS User Interface/dlgExportImport.cs +++ b/PROMS/VEPROMS User Interface/dlgExportImport.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; -using Volian.Controls.Library; using Volian.Base.Library; using System.Xml; using System.IO; @@ -20,14 +18,9 @@ namespace VEPROMS { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - frmVEPROMS _MyFrmVEPROMS = null;// Save frmVEPROMS for Import to shutoff SessionPing - public frmVEPROMS MyFrmVEPROMS - { - get { return _MyFrmVEPROMS; } - set { _MyFrmVEPROMS = value; } - } - private bool _ConvertROsToTextDuringImport = false; + #endregion + public frmVEPROMS MyFrmVEPROMS { get; set; } = null; + private bool _ConvertROsToTextDuringImport = false; private bool _ConvertROsAndTransitionsToText = false; // set to true when Approval creates an Export file protected bool _ExportBothConvertedandNot = false; // set to true when Electronic Procedure export @@ -40,32 +33,18 @@ namespace VEPROMS //this will hold if a specific unit was selected readonly protected int _UnitIndex; - private ItemInfo _ExternalTransitionItem = null; - public ItemInfo ExternalTransitionItem - { - get { return _ExternalTransitionItem; } - set { _ExternalTransitionItem = value; } - } - private Dictionary floatFoldout; + public ItemInfo ExternalTransitionItem { get; set; } = null; + private Dictionary floatFoldout; private Dictionary importedFormat; private Dictionary existingFormat; - private Dictionary renamedUCFFormatName; // if format is renamed, this is its new name so references to it can be made - private Dictionary renamedUCFFormatId; // if format is renamed, this is its old->new formatid private int oldRODbID; private int newRODbID; private FolderInfo _MyNewFolder; - public FolderInfo MyNewFolder - { - get { return _MyNewFolder; } - } - private ProcedureInfo _MyNewProcedure; - public ProcedureInfo MyNewProcedure - { - get { return _MyNewProcedure; } - set { _MyNewProcedure = value; } - } - private string PEIPath; - private string _MyMode; + public FolderInfo MyNewFolder => _MyNewFolder; + + public ProcedureInfo MyNewProcedure { get; set; } + private string PEIPath; + private readonly string _MyMode; protected FolderInfo MyFolder = null; protected DocVersionInfo MyDocVersion = null; protected ProcedureInfo MyProcedure = null; @@ -81,7 +60,7 @@ namespace VEPROMS _MyMode = mode; MyFolder = folderInfo; InitializeComponent(); - this.Text = mode + " Dialog for " + folderInfo.Name; + Text = $"{mode} Dialog for {folderInfo.Name}"; _UnitIndex = unitIndex; if (_UnitIndex > 0) @@ -103,9 +82,9 @@ namespace VEPROMS MyDocVersion = docVersionInfo; InitializeComponent(); if (mode.ToUpper().Contains("FORMAT")) - this.Text = mode; + Text = mode; else - this.Text = mode + " Dialog for " + docVersionInfo.Name + " of " + docVersionInfo.MyFolder.Name; + Text = $"{mode} Dialog for {docVersionInfo.Name} of {docVersionInfo.MyFolder.Name}"; _UnitIndex = unitIndex; if (_UnitIndex > 0) @@ -124,7 +103,7 @@ namespace VEPROMS _MyMode = mode; MyProcedure = procedureInfo; InitializeComponent(); - this.Text = mode + " Dialog for " + procedureInfo.DisplayNumber; + Text = $"{mode} Dialog for {procedureInfo.DisplayNumber}"; _UnitIndex = unitIndex; if (_UnitIndex > 0) @@ -173,7 +152,7 @@ namespace VEPROMS ofd.InitialDirectory = PEIPath; pnlImport.BringToFront(); } - this.Height = this.Height / formsize; + Height /= formsize; } private void btnExport_Click(object sender, EventArgs e) { @@ -220,19 +199,19 @@ namespace VEPROMS string msg = "Finished Exporting:\n\n"; if (_MyMode.ToUpper().Contains("FORMAT")) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; MyStart = DateTime.Now; btnDoExport.Enabled = false; lblExportStatus.Text = "Performing Export of UC Formats"; SaveExportUCF(); TimeSpan elapsed = DateTime.Now.Subtract(MyStart); - lblExportStatus.Text = "Format Export Completed in " + elapsed.ToString(); - this.Cursor = Cursors.Default; + lblExportStatus.Text = $"Format Export Completed in {elapsed}"; + Cursor = Cursors.Default; } else if (MyFolder != null) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; MyStart = DateTime.Now; btnDoExport.Enabled = false; lblExportStatus.Text = "Performing Export"; @@ -240,7 +219,7 @@ namespace VEPROMS TimeSpan elapsed = DateTime.Now.Subtract(MyStart); lblExportStatus.Text = "Export Completed in " + elapsed.ToString(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; msg += MyFolder.Name; } else if (MyProcedure != null) @@ -281,7 +260,7 @@ namespace VEPROMS } - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; MyStart = DateTime.Now; btnDoExport.Enabled = false; lblExportStatus.Text = "Performing Export"; @@ -294,7 +273,7 @@ namespace VEPROMS xd.Save(fileLocation); TimeSpan elapsed = DateTime.Now.Subtract(MyStart); lblExportStatus.Text = "Export Completed in " + elapsed.ToString(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // added message to user when export of a procedure or procedure set has completed if (successfullExport) @@ -338,7 +317,7 @@ namespace VEPROMS bool isImported = false; bool canceledPressed = false; btnImport.Enabled = false; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; MyStart = DateTime.Now; btnDoImport.Enabled = false; lblImportStatus.Text = "Performing Import"; @@ -350,13 +329,13 @@ namespace VEPROMS { TurnChangeManagerOff.Execute(); MyFrmVEPROMS.DisablePing = true;// Turn-off SessionPing - bool result = TryToImportUCFs(ref isImported, ref canceledPressed); + bool result = TryToImportUCFs(ref isImported); MyFrmVEPROMS.DisablePing = false;// Turn-on SessionPing TurnChangeManagerOn.Execute(); if (!result) // B2019-006: let user know there was an error during import: { MessageBox.Show("Error occurred during import. Format(s) not imported."); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; btnCloseImport.Enabled = true; return; } @@ -400,7 +379,7 @@ namespace VEPROMS if (isImported) { TimeSpan elapsed = DateTime.Now.Subtract(MyStart); - lblImportStatus.Text = "Import Completed in " + elapsed.ToString(); + lblImportStatus.Text = $"Import Completed in {elapsed}"; } else { @@ -408,7 +387,7 @@ namespace VEPROMS btnDoImport.Enabled = true; } } - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; btnCloseImport.Enabled = true; if (isImported) { @@ -436,7 +415,7 @@ namespace VEPROMS } } - private bool TryToImportUCFs(ref bool isImported, ref bool canceledPressed) + private bool TryToImportUCFs(ref bool isImported) { try { @@ -450,7 +429,7 @@ namespace VEPROMS if (nl == null || nl.Count == 0) // B2019-014: Check contents of import file for compatible operation { MessageBox.Show("A Procedure export file can only be imported from the Tree View.", "Import Failed", MessageBoxButtons.OK); - this.Close(); + Close(); isImported = false; return false; } @@ -504,7 +483,7 @@ namespace VEPROMS { MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Asterisk); _MyLog.Warn("Failed during UC Formats Import", ex); - this.Close(); + Close(); isImported = false; return false; } @@ -519,7 +498,7 @@ namespace VEPROMS { MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Asterisk); _MyLog.Warn("Failed during Procedure Import", ex); - this.Close(); + Close(); return false; } } @@ -528,11 +507,9 @@ namespace VEPROMS private bool _ImportingApprovedExportFile = false; private bool ImportingApprovedExport(string fnAndPath) { - bool rtnval = false; - int idx = fnAndPath.LastIndexOf("//") + 1; + int idx = fnAndPath.LastIndexOf("//") + 1; string tmp = fnAndPath.Substring(idx); - rtnval = tmp.ToUpper().Contains("APPROVED_REV_"); - return rtnval; + return tmp.ToUpper().Contains("APPROVED_REV_"); } private bool ImportProcedure(ref bool isImported, ref bool canceledPressed) { @@ -544,15 +521,17 @@ namespace VEPROMS if (ucf != null) { MessageBox.Show("A User Control of Format export file can only be imported from Administration on the V-Button.", "Import Failed", MessageBoxButtons.OK); - this.Cursor = Cursors.Default; - this.btnImport.Enabled = true; // allow user to select a different export file to import - this.btnCloseImport.Enabled = true; // allow user to close import dialog + Cursor = Cursors.Default; + btnImport.Enabled = true; // allow user to select a different export file to import + btnCloseImport.Enabled = true; // allow user to close import dialog return false; } string rofolderpath = xd.DocumentElement.Attributes.GetNamedItem("rofolderpath").InnerText; int rodbid = int.Parse(xd.DocumentElement.Attributes.GetNamedItem("rodbid").InnerText); - int rofstid = int.Parse(xd.DocumentElement.Attributes.GetNamedItem("rofstid").InnerText); - if (MyDocVersion.DocVersionAssociationCount > 0) +#pragma warning disable IDE0059 // Unnecessary assignment of a value - rofstid for Debugging/future use + int rofstid = int.Parse(xd.DocumentElement.Attributes.GetNamedItem("rofstid").InnerText); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + if (MyDocVersion.DocVersionAssociationCount > 0) { // use current ROPath MyRODb = RODb.GetJustRoDb(MyDocVersion.DocVersionAssociations[0].MyROFst.MyRODb.RODbID); @@ -560,15 +539,17 @@ namespace VEPROMS // then ask if we should import using the current workingdraft RO Path, convert the ROs to text, or cancel the import if (MyRODb.FolderPath != rofolderpath && !_ImportingApprovedExportFile) //B2020-095 don't display dialog if importing approved procedure export file { - dlgImpHowToHandleROs dlg = new dlgImpHowToHandleROs(); - dlg.ImportedROFolder = rofolderpath; - dlg.WorkingDraftROFolder = MyRODb.FolderPath; - dlg.ShowDialog(this); + dlgImpHowToHandleROs dlg = new dlgImpHowToHandleROs + { + ImportedROFolder = rofolderpath, + WorkingDraftROFolder = MyRODb.FolderPath + }; + dlg.ShowDialog(this); if (dlg.CancelImport) { - this.Cursor = Cursors.Default; - this.btnImport.Enabled = true; // allow user to select a different export file to import - this.btnDoImport.Enabled = true; // allow user to change mind and perform the import + Cursor = Cursors.Default; + btnImport.Enabled = true; // allow user to select a different export file to import + btnDoImport.Enabled = true; // allow user to change mind and perform the import return false; // Return False to Indicate that the Import did not succeed } _ConvertROsToTextDuringImport = dlg.ConvertROsToText; @@ -612,16 +593,18 @@ namespace VEPROMS if (localROPaths.Count == 0) { MessageBox.Show("There has been no RO folder defined for this database.\r\n\r\nIn order to import a procedure, you need to assign a RO folder path.\r\n\r\nImport process will terminate."); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return false;// Return False to Indicate that the Import did not succeed } else { - this.Cursor = Cursors.Default; - dlgPickROFolder dlg = new dlgPickROFolder(); - dlg.ImportedROFolder = rofolderpath; - dlg.LocalROFolders = localROPaths; - dlg.ShowDialog(this); + Cursor = Cursors.Default; + dlgPickROFolder dlg = new dlgPickROFolder + { + ImportedROFolder = rofolderpath, + LocalROFolders = localROPaths + }; + dlg.ShowDialog(this); if ((dlg.SelectedROFolder ?? string.Empty) != string.Empty) // B2015-216 If the return value is null treat it like an empty string { MyRODb = RODb.GetByFolderPath(dlg.SelectedROFolder); @@ -645,7 +628,7 @@ namespace VEPROMS else { MessageBox.Show("Since you did not pick an existing RO folder defined for this database, the import process will terminate."); - this.Close();// Close the Import Window + Close();// Close the Import Window return false;// Return False to Indicate that the Import did not succeed } } @@ -655,9 +638,9 @@ namespace VEPROMS bool didImp = LoadFormats(xd, "procedure/formats/format"); if (!didImp) { - this.Cursor = Cursors.Default; - this.btnImport.Enabled = true; // allow user to select a different export file to import - this.btnDoImport.Enabled = true; // allow user to change mind and perform the import + Cursor = Cursors.Default; + btnImport.Enabled = true; // allow user to select a different export file to import + btnDoImport.Enabled = true; // allow user to change mind and perform the import return false; // Return False to Indicate that the Import did not succeed } // use resolvedProcNum to determine if procedure is 'unique', i.e. if the procedure number exists @@ -763,7 +746,7 @@ namespace VEPROMS ProcedureInfo lastProcedure = null; foreach (ProcedureInfo pi in MyDocVersion.Procedures.OfType()) lastProcedure = pi; - _MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure); + MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure); //update transitions AddTransitions(PendingTransitions); PendingTransitions.Save(fn); @@ -803,7 +786,7 @@ namespace VEPROMS } xd.SelectSingleNode("procedure/content/@number").InnerText = string.Format("Copy({0}) of {1}", count.ToString(), number); //add imported procedure and copy count - _MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure); + MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure); //update transitions AddTransitions(PendingTransitions); FixFloatingFoldouts(); @@ -861,7 +844,7 @@ namespace VEPROMS return false; } //add imported procedure - _MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure); + MyNewProcedure = AddProcedure(xd.DocumentElement, MyDocVersion, lastProcedure); //update transitions AddTransitions(PendingTransitions); FixFloatingFoldouts(); @@ -884,9 +867,9 @@ namespace VEPROMS bool didImp = LoadFormats(xd, "folder/formats/format"); if (!didImp) { - this.Cursor = Cursors.Default; - this.btnImport.Enabled = true; // allow user to select a different export file to import - this.btnDoImport.Enabled = true; // allow user to change mind and perform the import + Cursor = Cursors.Default; + btnImport.Enabled = true; // allow user to select a different export file to import + btnDoImport.Enabled = true; // allow user to change mind and perform the import return false; // Return False to Indicate that the Import did not succeed } string name = xd.DocumentElement.Attributes.GetNamedItem("name").InnerText; @@ -1004,7 +987,8 @@ namespace VEPROMS c.Save(); } } - Dictionary existingCopyFCName = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + Dictionary existingCopyFCName = new Dictionary(); // note that this is used when importing a folder or a procedure (procedure was added for UCF changes) private bool LoadFormats(XmlDocument xd, string xmlpath) { @@ -1015,21 +999,20 @@ namespace VEPROMS importedFormat = new Dictionary(); XmlNodeList nl = xd.SelectNodes(xmlpath); - - bool conflictingUCFdata = false; List existingFC = new List(); List importedFC = new List(); List fname = new List(); foreach (XmlNode nd in nl) { - string copyOfUCF = null; - // see if any of the imported formats are 'UCF' formats, i.e. have config data. If they are UCF, - // see if this is different that what is in the database. If it is, the user needs to decide - // whether to associate sections with existing UCF format or the new one. All UCF formats will be - // connected the same way, i.e. existing or new. - int formatid = int.Parse(nd.Attributes.GetNamedItem("formatid").InnerText); - string name = nd.Attributes.GetNamedItem("name").InnerText; + // see if any of the imported formats are 'UCF' formats, i.e. have config data. If they are UCF, + // see if this is different that what is in the database. If it is, the user needs to decide + // whether to associate sections with existing UCF format or the new one. All UCF formats will be + // connected the same way, i.e. existing or new. +#pragma warning disable IDE0059 // Unnecessary assignment of a value - formatid for Debugging/future use + int formatid = int.Parse(nd.Attributes.GetNamedItem("formatid").InnerText); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + string name = nd.Attributes.GetNamedItem("name").InnerText; string config = null; XmlNode cfg = nd.Attributes.GetNamedItem("config"); if (cfg != null) config = cfg.InnerText; @@ -1038,10 +1021,10 @@ namespace VEPROMS FormatInfo exFI = FormatInfo.Get(existingFormat[name]); if (exFI.Config != config && exFI.Config != "" && exFI.Config != null && config != "" && config != null) { - // See if there are copies of this UCF format, if so, this may match (have same config) one of those and should - // use it before stating there is conflicting data. - copyOfUCF = ContentsOfUCFExists(name, config); - if (copyOfUCF == null) + // See if there are copies of this UCF format, if so, this may match (have same config) one of those and should + // use it before stating there is conflicting data. + string copyOfUCF = ContentsOfUCFExists(name, config); + if (copyOfUCF == null) { existingFC.Add(exFI.Config); importedFC.Add(config); @@ -1069,15 +1052,16 @@ namespace VEPROMS if (pnameAttrib != null) pname = pnameAttrib.InnerText; if (pname == null) continue; - string description = null; - XmlNode descript = nd.Attributes.GetNamedItem("description"); - if (descript != null) description = descript.InnerText; - string userid = nd.Attributes.GetNamedItem("userid").InnerText; - DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); - // If the format that is being imported exists as a copy (already was imported and a 'Copy x of name' was created) and the imported and - // existing config match, use the existing (copied) format's name rather than importing it again (the dictionary was set up during - // the import formats process. - if (existingCopyFCName.ContainsKey(name)) name = existingCopyFCName[name]; + XmlNode descript = nd.Attributes.GetNamedItem("description"); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - description, userid, dts for future use + string description = descript?.InnerText; + string userid = nd.Attributes.GetNamedItem("userid").InnerText; + DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + // If the format that is being imported exists as a copy (already was imported and a 'Copy x of name' was created) and the imported and + // existing config match, use the existing (copied) format's name rather than importing it again (the dictionary was set up during + // the import formats process. + if (existingCopyFCName.ContainsKey(name)) name = existingCopyFCName[name]; // compare this imported format to the original in the database. // If format name exists, or if it has same config data, just use it. @@ -1098,11 +1082,11 @@ namespace VEPROMS // parent format will always be in there, if it is a new format, it will be added before the child. Check just in case (no null reference). if (!existingFormat.ContainsKey(pname)) break; int pid = existingFormat[pname]; - Format pformat = Format.Get(pid); + _ = Format.Get(pid); - // if the new format doesn't exist, it will be added (after these other checks). Otherwise, handle the - // various cases listed above: - if (existingFormat.ContainsKey(name)) + // if the new format doesn't exist, it will be added (after these other checks). Otherwise, handle the + // various cases listed above: + if (existingFormat.ContainsKey(name)) { @@ -1221,7 +1205,6 @@ namespace VEPROMS { int oldid = int.Parse(nd.Attributes.GetNamedItem("old").InnerText); int newid = int.Parse(nd.Attributes.GetNamedItem("new").InnerText); - //if (!Old2NewContent.ContainsKey(oldid)) Old2NewLibDoc.Add(oldid, newid); } File.Delete(fn); @@ -1362,8 +1345,8 @@ namespace VEPROMS } private void ExportFormats(FormatInfoList fil, XmlElement xn, string nodename, bool doElement) { - XmlElement xe = null; - if (doElement) xe = xn.OwnerDocument.CreateElement(nodename); + XmlElement xe; + if (doElement) xe = xn.OwnerDocument.CreateElement(nodename); else xe = xn; foreach (FormatInfo fi in fil) ExportFormat(xe, fi, "format"); @@ -1489,7 +1472,7 @@ namespace VEPROMS { pbExportProcedure.Value = 0; pbExportProcedure.Maximum = dvi.Procedures.Count; - lblExportProcedure.Text = pbExportProcedure.Maximum.ToString() + " Procedures"; + lblExportProcedure.Text = $"{pbExportProcedure.Maximum} Procedures"; foreach (ItemInfo ii in dvi.Procedures) { XmlDocument xd = new XmlDocument(); @@ -1641,14 +1624,14 @@ namespace VEPROMS private void ExportItem(XmlElement xn, ItemInfo ii, string nodename) { - /* + /* ItemID PreviousID ContentID DTS */ - XmlElement xe = null; - if (xn.Name == "procedure") + XmlElement xe; + if (xn.Name == "procedure") xe = xn; else { @@ -2434,12 +2417,9 @@ namespace VEPROMS } } - private void AddTransitions() - { - AddTransitions(PendingTransitions); - } + private void AddTransitions() => AddTransitions(PendingTransitions); - private void AddTransitions(XmlDocument xd) + private void AddTransitions(XmlDocument xd) { /* Content @@ -2459,7 +2439,7 @@ namespace VEPROMS type,id,toid,rangeid */ XmlNodeList nl = xd.SelectNodes("//transition"); - lblImportStatus.Text = string.Format("Updating {0} Tranistions", nl.Count.ToString()); + lblImportStatus.Text = $"Updating {nl.Count} Tranistions"; foreach (XmlNode nd in nl) { @@ -2522,9 +2502,8 @@ namespace VEPROMS } else //transition to existing itemid (external) { - bool forceConvertToText = false; - int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText); - int isrange = int.Parse(nd.Attributes.GetNamedItem("isrange").InnerText); + int transitionid = int.Parse(nd.Attributes.GetNamedItem("transitionid").InnerText); + int isrange = int.Parse(nd.Attributes.GetNamedItem("isrange").InnerText); string config = nd.Attributes.GetNamedItem("config").InnerText; string userid = nd.Attributes.GetNamedItem("userid").InnerText; DateTime dts = DateTime.Parse(nd.Attributes.GetNamedItem("dts").InnerText); @@ -2538,43 +2517,44 @@ namespace VEPROMS fromid = Old2NewContent[fromid]; Content cc = Content.Get(fromid); Transition tt = Transition.MakeTransition(cc, Item.Get(toid), Item.Get(rangeid), isrange, trantype, config, dts, userid); - - if (tt.TransitionID < 0) - { - forceConvertToText = true; - _DidProcessTransitions |= cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText); // B2017-076 FixTransitionText will tell us if transitions were processed/changed - cc.Save(); - nd.InnerText = "done"; - } - else - { - transitionid = tt.TransitionID; - string replacewith; - - if (isrange == 0) - replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); - else - replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); - - cc.Text = cc.Text.Replace(lookfor, replacewith); - if (cc.MyGrid != null && !string.IsNullOrEmpty(cc.MyGrid.Data)) - { - cc.MyGrid.Data = cc.MyGrid.Data.Replace(lookfor, replacewith); - } + bool forceConvertToText; + if (tt.TransitionID < 0) + { + forceConvertToText = true; + _DidProcessTransitions |= cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText); // B2017-076 FixTransitionText will tell us if transitions were processed/changed + cc.Save(); + nd.InnerText = "done"; + } + else + { + transitionid = tt.TransitionID; + string replacewith; - // B2016-176, B2016-197 - external transitions should be converted to text - forceConvertToText = true; - _DidProcessTransitions |= cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText); // B2017-076 FixTransitionText will tell us if transitions were processed/changed - // B2017=003 make sure any grid changes are saved. - // done here because FixTransitionText() could update the transitions in the grid - if (cc.MyGrid != null && cc.MyGrid.Data != "") - cc.MyGrid.Save(); - cc.Save(); - nd.InnerText = "done"; - _DidConvertTransitionsToText |= (forceConvertToText && _DidProcessTransitions); // B2016-225 - notify user when transitions are converted to text - } - } + if (isrange == 0) + replacewith = string.Format("#Link:Transition:{0} {1} {2}", trantype, transitionid, toid); + else + replacewith = string.Format("#Link:TransitionRange:{0} {1} {2} {3}", trantype, transitionid, toid, rangeid); + + cc.Text = cc.Text.Replace(lookfor, replacewith); + + if (cc.MyGrid != null && !string.IsNullOrEmpty(cc.MyGrid.Data)) + { + cc.MyGrid.Data = cc.MyGrid.Data.Replace(lookfor, replacewith); + } + + // B2016-176, B2016-197 - external transitions should be converted to text + forceConvertToText = true; + _DidProcessTransitions |= cc.FixTransitionText(TransitionInfo.Get(tt.TransitionID), forceConvertToText); // B2017-076 FixTransitionText will tell us if transitions were processed/changed + // B2017=003 make sure any grid changes are saved. + // done here because FixTransitionText() could update the transitions in the grid + if (cc.MyGrid != null && cc.MyGrid.Data != "") + cc.MyGrid.Save(); + cc.Save(); + nd.InnerText = "done"; + _DidConvertTransitionsToText |= (forceConvertToText && _DidProcessTransitions); // B2016-225 - notify user when transitions are converted to text + } + } } } } @@ -2620,7 +2600,6 @@ namespace VEPROMS if (formatID >= importedFormat.Count) return null; // formatID not found, use default file name formatName = importedFormat[formatID]; // for backwards compatibility with older export files } - if (renamedUCFFormatName != null && renamedUCFFormatName.ContainsKey(formatFileName)) formatName = renamedUCFFormatName[formatName]; formatID = existingFormat[formatName]; return Format.Get(formatID); } @@ -2668,9 +2647,11 @@ namespace VEPROMS MyRODb = AddRODb(xrodb); ROFst rofst = AddROFst(xrofst); - DocVersionAssociation dva = dv.DocVersionAssociations.Add(rofst); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - dva kept for side effect code + DocVersionAssociation dva = dv.DocVersionAssociations.Add(rofst); +#pragma warning restore IDE0059 // Unnecessary assignment of a value - dv.Save(); + dv.Save(); } return DocVersionInfo.Get(dv.VersionID); @@ -2905,9 +2886,11 @@ namespace VEPROMS foreach (XmlNode nd in xn.SelectNodes("rousage")) { string rousageid = nd.Attributes.GetNamedItem("rousageid").InnerText; - string roid = nd.Attributes.GetNamedItem("roid").InnerText; +#pragma warning disable IDE0059 // Unnecessary assignment of a value - roid for Debugging/future use + string roid = nd.Attributes.GetNamedItem("roid").InnerText; +#pragma warning restore IDE0059 // Unnecessary assignment of a value - string findLink = @""; + string findLink = @""; content.Text = content.Text.Replace("\v0 \v Close(); - private void btnCloseImport_Click(object sender, EventArgs e) - { - this.Close(); - } + private void btnCloseImport_Click(object sender, EventArgs e) => Close(); - //unset the unit (SelectedSlave) - private void RemoveUnit_OnClose(object sender, EventArgs e) + //unset the unit (SelectedSlave) + private void RemoveUnit_OnClose(object sender, EventArgs e) { if (MyProcedure != null) { diff --git a/PROMS/VEPROMS User Interface/dlgExportImportEP.cs b/PROMS/VEPROMS User Interface/dlgExportImportEP.cs index 5730bbe5..9ef6e26a 100644 --- a/PROMS/VEPROMS User Interface/dlgExportImportEP.cs +++ b/PROMS/VEPROMS User Interface/dlgExportImportEP.cs @@ -19,7 +19,7 @@ namespace VEPROMS private readonly AnnotationTypeInfo _AnnotationType; private readonly string multiseparator = ","; - private static Regex _ROAccPageTokenPattern = new Regex("[<][^<>-]+-[^<>]+[>]"); + private static readonly Regex _ROAccPageTokenPattern = new Regex("[<][^<>-]+-[^<>]+[>]"); public dlgExportImportEP(string mode, FolderInfo folderInfo, frmVEPROMS myFrmVEPROMS, int annotationTypeId, int unitIndex = 0) : base(mode, folderInfo, myFrmVEPROMS, ( unitIndex)) { @@ -261,10 +261,8 @@ namespace VEPROMS { string rodbpath = rodb.FolderPath; - string rocval = roc.value; - if (rocval == null) rocval = Array.Find(roc.children, x => x.value.Contains('.')).value; - - if (rocval == null) return ""; + string rocval = roc.value ?? Array.Find(roc.children, x => x.value.Contains('.')).value; + if (rocval == null) return ""; string imgname; if (isMulti) { diff --git a/PROMS/VEPROMS User Interface/dlgImpHowToHandleROs.cs b/PROMS/VEPROMS User Interface/dlgImpHowToHandleROs.cs index 4c50eb09..7a7f5310 100644 --- a/PROMS/VEPROMS User Interface/dlgImpHowToHandleROs.cs +++ b/PROMS/VEPROMS User Interface/dlgImpHowToHandleROs.cs @@ -1,54 +1,23 @@ 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; namespace VEPROMS { public partial class dlgImpHowToHandleROs : Form { - private string _ImportedROFolder; - public string ImportedROFolder - { - get { return _ImportedROFolder; } - set { _ImportedROFolder = value; } - } - private string _WorkingDraftROFolder; - public string WorkingDraftROFolder - { - get { return _WorkingDraftROFolder; } - set { _WorkingDraftROFolder = value; } - } - private bool _CancelImport = true; // default to truen in case the dialog is closed with the red X in the upper right corner - public bool CancelImport - { - get { return _CancelImport; } - } - private bool _ConvertROsToText = false; - public bool ConvertROsToText - { - get { return _ConvertROsToText; } - } - public dlgImpHowToHandleROs() - { - InitializeComponent(); - } + public string ImportedROFolder { get; set; } + public string WorkingDraftROFolder { get; set; } + private bool _CancelImport = true; // default to truen in case the dialog is closed with the red X in the upper right corner + public bool CancelImport => _CancelImport; + private bool _ConvertROsToText = false; + public bool ConvertROsToText => _ConvertROsToText; + public dlgImpHowToHandleROs() => InitializeComponent(); - private void dlgImpHowToHandleROs_Load(object sender, EventArgs e) - { - rtbROPathInfo.Text = string.Format("The current Working Draft RO folder path is:\n\n {0}\n\nThe procedure you are trying to import is from a database that has the RO folder path:\n\n {1}\n\nSelect from the options below on how to handle the RO values when importing this procedure.", _WorkingDraftROFolder, _ImportedROFolder); - } + private void dlgImpHowToHandleROs_Load(object sender, EventArgs e) => rtbROPathInfo.Text = string.Format("The current Working Draft RO folder path is:\n\n {0}\n\nThe procedure you are trying to import is from a database that has the RO folder path:\n\n {1}\n\nSelect from the options below on how to handle the RO values when importing this procedure.", WorkingDraftROFolder, ImportedROFolder); - private void btnUseCurrentROs_Click(object sender, EventArgs e) - { - _ConvertROsToText = _CancelImport = false; - } + private void btnUseCurrentROs_Click(object sender, EventArgs e) => _ConvertROsToText = _CancelImport = false; - private void btnROsToText_Click(object sender, EventArgs e) + private void btnROsToText_Click(object sender, EventArgs e) { _CancelImport = false; _ConvertROsToText = true; @@ -60,9 +29,6 @@ namespace VEPROMS _ConvertROsToText = false; } - private void dlgImpHowToHandleROs_Resize(object sender, EventArgs e) - { - rtbROPathInfo.Refresh(); - } - } + private void dlgImpHowToHandleROs_Resize(object sender, EventArgs e) => rtbROPathInfo.Refresh(); + } } diff --git a/PROMS/VEPROMS User Interface/dlgMSWordMessage.cs b/PROMS/VEPROMS User Interface/dlgMSWordMessage.cs index 5f26d7f7..103aec33 100644 --- a/PROMS/VEPROMS User Interface/dlgMSWordMessage.cs +++ b/PROMS/VEPROMS User Interface/dlgMSWordMessage.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; using VEPROMS.CSLA.Library; using Volian.Base.Library; @@ -38,7 +31,7 @@ namespace VEPROMS usersettings.SetUserSetting_MSWord_Summary_Prompt(false); } - this.Close(); + Close(); } } diff --git a/PROMS/VEPROMS User Interface/dlgManageSecurity.cs b/PROMS/VEPROMS User Interface/dlgManageSecurity.cs index 83b0a1db..e90a9a8a 100644 --- a/PROMS/VEPROMS User Interface/dlgManageSecurity.cs +++ b/PROMS/VEPROMS User Interface/dlgManageSecurity.cs @@ -1,12 +1,7 @@ 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.Base.Library; using Volian.Controls.Library; using System.Linq; @@ -26,11 +21,8 @@ namespace VEPROMS private List myMembershipInfoList; private Folder myFolder; - public dlgManageSecurity() - { - InitializeComponent(); - } - private void dlgManageSecurity_Load(object sender, EventArgs e) + public dlgManageSecurity() => InitializeComponent(); + private void dlgManageSecurity_Load(object sender, EventArgs e) { //load all folders myFolder = Folder.Get(1); @@ -331,10 +323,12 @@ namespace VEPROMS private void addUserToolStripMenuItem_Click(object sender, EventArgs e) { User u = User.MakeUser("[Enter New UserID]", "", "", "", "", "", "", "", "", "", "", DateTime.Now, ""); - frmManageUser frm = new frmManageUser("add"); - frm.MyUser = u; - frm.Text = "Enter New UserID"; //C2026-002 Change Title bar on Add/Edit User - if (frm.ShowDialog(this) == DialogResult.OK) + frmManageUser frm = new frmManageUser("add") + { + MyUser = u, + Text = "Enter New UserID" //C2026-002 Change Title bar on Add/Edit User + }; + if (frm.ShowDialog(this) == DialogResult.OK) { u = frm.MyUser; u.Save(); @@ -362,9 +356,11 @@ namespace VEPROMS UserInfo ui = myUserInfoList[lstUsers.SelectedIndex]; using (User u = User.Get(ui.UID)) { - frmManageUser frm = new frmManageUser("edit"); - frm.MyUser = u; - if (frm.ShowDialog(this) == DialogResult.OK) + frmManageUser frm = new frmManageUser("edit") + { + MyUser = u + }; + if (frm.ShowDialog(this) == DialogResult.OK) { frm.MyUser.Save(); @@ -505,12 +501,14 @@ namespace VEPROMS pnlGroups.Controls.Clear(); foreach (GroupInfo gi in myGroupInfoList) { - RadioButton rb = new RadioButton(); - rb.Text = gi.GroupName; - rb.Parent = pnlGroups; - rb.Dock = DockStyle.Top; - rb.Tag = gi; - rb.CheckedChanged -= new EventHandler(rb_CheckedChanged); + RadioButton rb = new RadioButton + { + Text = gi.GroupName, + Parent = pnlGroups, + Dock = DockStyle.Top, + Tag = gi + }; + rb.CheckedChanged -= new EventHandler(rb_CheckedChanged); rb.CheckedChanged += new EventHandler(rb_CheckedChanged); pnlGroups.Controls.Add(rb); rb.BringToFront(); diff --git a/PROMS/VEPROMS User Interface/dlgPhoneList.cs b/PROMS/VEPROMS User Interface/dlgPhoneList.cs index 8ea9b42d..c7b58f51 100644 --- a/PROMS/VEPROMS User Interface/dlgPhoneList.cs +++ b/PROMS/VEPROMS User Interface/dlgPhoneList.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 VEPROMS.CSLA.Library; @@ -11,8 +6,8 @@ namespace VEPROMS { public partial class dlgPhoneList : Form { - private DocVersionConfig _docVersionConfig; - private string _origPhoneList; + private readonly DocVersionConfig _docVersionConfig; + private readonly string _origPhoneList; public dlgPhoneList(DocVersionConfig dvc) { _docVersionConfig = dvc; diff --git a/PROMS/VEPROMS User Interface/dlgPickROFolder.cs b/PROMS/VEPROMS User Interface/dlgPickROFolder.cs index cf5f3e2d..a9d20b56 100644 --- a/PROMS/VEPROMS User Interface/dlgPickROFolder.cs +++ b/PROMS/VEPROMS User Interface/dlgPickROFolder.cs @@ -1,57 +1,24 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.Windows.Forms; namespace VEPROMS { public partial class dlgPickROFolder : Form { - private string _ImportedROFolder; - public string ImportedROFolder - { - get { return _ImportedROFolder; } - set { _ImportedROFolder = value; } - } - private List _LocalROFolders; - public List LocalROFolders - { - get { return _LocalROFolders; } - set { _LocalROFolders = value; } - } - private string _SelectedROFolder; - public string SelectedROFolder - { - get { return _SelectedROFolder; } - set { _SelectedROFolder = value; } - } - public dlgPickROFolder() - { - InitializeComponent(); - } + public string ImportedROFolder { get; set; } + public List LocalROFolders { get; set; } + public string SelectedROFolder { get; set; } + public dlgPickROFolder() => InitializeComponent(); - private void dlgPickROFolder_Load(object sender, EventArgs e) + private void dlgPickROFolder_Load(object sender, EventArgs e) { - lblImportRO.Text = string.Format("The procedure you are trying to import was exported from a database that had the following RO folder path:\r\n\r\n{0}\r\n\r\nSelect from the following RO Folders that exist in the database you are trying to import this procedure into so that the import process can continue", _ImportedROFolder); + lblImportRO.Text = string.Format("The procedure you are trying to import was exported from a database that had the following RO folder path:\r\n\r\n{0}\r\n\r\nSelect from the following RO Folders that exist in the database you are trying to import this procedure into so that the import process can continue", ImportedROFolder); clbLocalROFolders.DataSource = LocalROFolders; } - private void clbLocalROFolders_SelectedIndexChanged(object sender, EventArgs e) - { - if (clbLocalROFolders.CheckedItems.Count > 0) - { - btnOkay.Enabled = true; - } - else - btnOkay.Enabled = false; - } + private void clbLocalROFolders_SelectedIndexChanged(object sender, EventArgs e) => btnOkay.Enabled = clbLocalROFolders.CheckedItems.Count > 0; - private void btnOkay_Click(object sender, EventArgs e) - { - SelectedROFolder = clbLocalROFolders.CheckedItems[0].ToString(); - } - } + private void btnOkay_Click(object sender, EventArgs e) => SelectedROFolder = clbLocalROFolders.CheckedItems[0].ToString(); + } } \ No newline at end of file diff --git a/PROMS/VEPROMS User Interface/dlgPrintAllApprovedProcedures.cs b/PROMS/VEPROMS User Interface/dlgPrintAllApprovedProcedures.cs index 1ad0e58b..f187ddcb 100644 --- a/PROMS/VEPROMS User Interface/dlgPrintAllApprovedProcedures.cs +++ b/PROMS/VEPROMS User Interface/dlgPrintAllApprovedProcedures.cs @@ -1,24 +1,19 @@ 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; using System.IO; using VEPROMS.CSLA.Library; using JR.Utils.GUI.Forms; +using System.Linq; namespace VEPROMS { public partial class dlgPrintAllApprovedProcedures : DevComponents.DotNetBar.Office2007Form { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private StringBuilder NotApproved; - private DocVersionInfo _DocVersionInfo = null; - private int unitId = 0; + private readonly StringBuilder NotApproved; + private readonly DocVersionInfo _DocVersionInfo = null; + private readonly int unitId = 0; public dlgPrintAllApprovedProcedures(DocVersionInfo dvi) { InitializeComponent(); @@ -43,7 +38,7 @@ namespace VEPROMS // if SelectedSlave is > 0 then we are printing Approved Child Procedures and // subtract one from the index (unitId) into the list of child names (UnitNames) if (unitId > 0) - rtnstr += "\\" + _DocVersionInfo.UnitNames[unitId - 1]; // append Child name to path + rtnstr += $"\\{_DocVersionInfo.UnitNames[unitId - 1]}"; // append Child name to path return rtnstr; } @@ -91,7 +86,7 @@ namespace VEPROMS int pdfCount = 0; DeleteExistingPDFs(); // delete existing PDFs in the target folder // Get the Child index for Parent/Child procedure - if not Parent/Child this will be zero - foreach (ProcedureInfo myProc in _DocVersionInfo.Procedures) + foreach (ProcedureInfo myProc in _DocVersionInfo.Procedures.OfType()) { RevisionInfoList ril = RevisionInfoList.GetByItemID(myProc.ItemID); if (ril.Count == 0) @@ -144,7 +139,7 @@ namespace VEPROMS _MyLog.Error("Print All Approved PDFs", ex);// save error in PROMS error log MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error); } - this.Close(); // close dialog + Close(); // close dialog } private void SaveApprovedPDFToFolder(RevisionInfo revInfo,string PDFName) { @@ -168,10 +163,6 @@ namespace VEPROMS { DirectoryInfo di = new DirectoryInfo(txbApprovedPDFsPath.Text); FileInfo[] fis; - //DirectoryInfo[] diAry = di.GetDirectories(txbApprovedPDFsPath.Text); - //DirectoryInfo di_fmtgen; - // remove all of the PDF fils - //di_fmtgen = diAry[0]; try { fis = di.GetFiles("*.pdf"); @@ -189,14 +180,8 @@ namespace VEPROMS } } - private void txbApprovedPDFsPath_TextChanged(object sender, EventArgs e) - { - btnPrntAllAprv.Enabled = txbApprovedPDFsPath.Text.Length > 0; - } + private void txbApprovedPDFsPath_TextChanged(object sender, EventArgs e) => btnPrntAllAprv.Enabled = txbApprovedPDFsPath.Text.Length > 0; - private void btnCancel_Click(object sender, EventArgs e) - { - this.Close(); - } - } + private void btnCancel_Click(object sender, EventArgs e) => Close(); + } } diff --git a/PROMS/VEPROMS User Interface/dlgSetChangeBarStartDate.cs b/PROMS/VEPROMS User Interface/dlgSetChangeBarStartDate.cs index 1ccd47a5..593fab36 100644 --- a/PROMS/VEPROMS User Interface/dlgSetChangeBarStartDate.cs +++ b/PROMS/VEPROMS User Interface/dlgSetChangeBarStartDate.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Data; using System.Text; using System.Windows.Forms; @@ -29,7 +28,7 @@ namespace VEPROMS if (tmp[0] == null || tmp[0] == "") // First time date set. { - cbdt = DateTime.Now.ToString("MM/dd/yyyy") + " " + DateTime.Now.ToString("HH:mm:ss"); + cbdt = $"{DateTime.Now:MM/dd/yyyy} {DateTime.Now:HH:mm:ss}"; dateTimeInput1.Value = DateTime.Parse(cbdt); return; } @@ -43,13 +42,13 @@ namespace VEPROMS var time = tmpdt.TimeOfDay; if (start < time) // If time is greater than 12:00:00 AM { - cbdt = DateTime.Now.ToString("MM/dd/yyyy") + " " + tmpdt.TimeOfDay.ToString(); + cbdt = $"{DateTime.Now:MM/dd/yyyy} {tmpdt.TimeOfDay}"; dateTimeInput1.Value = DateTime.Parse(cbdt); return; } else // if time is 12:00:00 AM { - cbdt = DateTime.Now.ToString("MM/dd/yyyy") + " " + " 00:00:00"; + cbdt = $"{DateTime.Now:MM/dd/yyyy} 00:00:00"; dateTimeInput1.Value = DateTime.Parse(cbdt); return; } @@ -68,7 +67,7 @@ namespace VEPROMS MyProcConfig.Print_ChangeBarDate = dateTimeInput1.Value.ToString("MM/dd/yyyy HH:mm:ss");// ("MM/dd/yyyy HH:mm:ss"); //CSM - C2026-010 - Add Audit Record for Change Bar Audit History - ChangeBarAuditHistory.AddAudit(MyProcInfo.ItemID, $"Set ChangeBars set to ({dateTimeInput1.Value.ToString("MM/dd/yyyy HH:mm:ss")}) by ({VlnSettings.UserID}) on ({DateTime.Now})", DateTime.Now, VlnSettings.UserID, 0); + ChangeBarAuditHistory.AddAudit(MyProcInfo.ItemID, $"Set ChangeBars set to ({dateTimeInput1.Value:MM/dd/yyyy HH:mm:ss}) by ({VlnSettings.UserID}) on ({DateTime.Now})", DateTime.Now, VlnSettings.UserID, 0); //CSM C2026-014 if multi-unit, set for each unit System.Data.DataTable dt = RevisionData.GetRevisionDataByUnit(MyProcInfo.ItemID); @@ -83,7 +82,7 @@ namespace VEPROMS MyProcConfig.Print_ChangeBarDate = dateTimeInput1.Value.ToString("MM/dd/yyyy HH:mm:ss"); //CSM - C2026-010 - Add Audit Record for Change Bar Audit History - ChangeBarAuditHistory.AddAudit(MyProcInfo.ItemID, $"Set ChangeBars set to ({dateTimeInput1.Value.ToString("MM/dd/yyyy HH:mm:ss")}) by ({VlnSettings.UserID}) on ({DateTime.Now}) for (Unit {r["UnitName"]})", DateTime.Now, VlnSettings.UserID, MyProcConfig.SelectedSlave); + ChangeBarAuditHistory.AddAudit(MyProcInfo.ItemID, $"Set ChangeBars set to ({dateTimeInput1.Value:MM/dd/yyyy HH:mm:ss}) by ({VlnSettings.UserID}) on ({DateTime.Now}) for (Unit {r["UnitName"]})", DateTime.Now, VlnSettings.UserID, MyProcConfig.SelectedSlave); } } MyProcConfig.SelectedSlave = 0; @@ -91,12 +90,9 @@ namespace VEPROMS } - private void btnNow_Click(object sender, EventArgs e) - { - dateTimeInput1.Value = DateTime.Now; - } + private void btnNow_Click(object sender, EventArgs e) => dateTimeInput1.Value = DateTime.Now; - //C2026-009 Add Option to Reset Change Bar to Last Approved Date/Time + //C2026-009 Add Option to Reset Change Bar to Last Approved Date/Time private void btnResetToApproved_Click(object sender, EventArgs e) { System.Data.DataTable dt = RevisionData.GetRevisionDataByUnit(MyProcInfo.ItemID); @@ -134,7 +130,7 @@ namespace VEPROMS sb.Append("\r\n Any Change Bars for Units not listed above will use the Overall/Procedure Viewer Change Bar Date (as these Units have no approvals)."); - if (CustomMessageBox.Show($"This will reset ChangeBars to show for changes newer than the last approval.\r\nThis includes the following changes:\r\n{sb.ToString()}\r\n\r\nAre you sure you wish to reset ChangeBars?", "Reset ChangeBar Date", "Yes", "No") == DialogResult.Yes) + if (CustomMessageBox.Show($"This will reset ChangeBars to show for changes newer than the last approval.\r\nThis includes the following changes:\r\n{sb}\r\n\r\nAre you sure you wish to reset ChangeBars?", "Reset ChangeBar Date", "Yes", "No") == DialogResult.Yes) { //Change the overall ChangeBarDate MyProcConfig.Print_ChangeBarDate = maxDTS; diff --git a/PROMS/VEPROMS User Interface/dlgTransitionReport.cs b/PROMS/VEPROMS User Interface/dlgTransitionReport.cs index a8cf15af..8a6ea658 100644 --- a/PROMS/VEPROMS User Interface/dlgTransitionReport.cs +++ b/PROMS/VEPROMS User Interface/dlgTransitionReport.cs @@ -1,9 +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 VEPROMS.CSLA.Library; using Volian.Print.Library; @@ -13,10 +9,11 @@ namespace VEPROMS { public partial class dlgTransitionReport : Form { - private FolderInfo folderInfo = null; - private ProcedureInfo procedureInfo = null; + private readonly FolderInfo folderInfo = null; + private readonly ProcedureInfo procedureInfo = null; private PDFTransitionReport rpt; - private List lstDocVersions; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List lstDocVersions; public dlgTransitionReport(FolderInfo fi) { InitializeComponent(); @@ -26,7 +23,7 @@ namespace VEPROMS if (lstDocVersions.Count == 1) { pnlVersions.Visible = false; - this.Height = this.Height - pnlVersions.Height; + Height -= pnlVersions.Height; } } public dlgTransitionReport(ProcedureInfo pi) @@ -34,16 +31,17 @@ namespace VEPROMS InitializeComponent(); procedureInfo = pi; pnlVersions.Visible = pnlProcs.Visible = false; - this.Height = this.Height - pnlVersions.Height - pnlProcs.Height; + Height = Height - pnlVersions.Height - pnlProcs.Height; } - //private DocVersionInfo docVersionInfo; private void dlgTransitionReport_Load(object sender, EventArgs e) { if (folderInfo != null) { - rpt = new PDFTransitionReport(folderInfo, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\TransitionReport.pdf"); - rpt.MyDocVersionList = lstDocVersions; - if (lstDocVersions.Count == 1) + rpt = new PDFTransitionReport(folderInfo, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\TransitionReport.pdf") + { + MyDocVersionList = lstDocVersions + }; + if (lstDocVersions.Count == 1) pbProcs.Maximum = lstDocVersions[0].Procedures.Count; else pbVersions.Maximum = lstDocVersions.Count; @@ -54,8 +52,8 @@ namespace VEPROMS if (VlnSettings.GetCommandFlag("PROFILE")) ProfileTimer.TurnOnTracking("Profile.txt"); VEPROMS.CSLA.Library.Database.TrackDBUsage = VlnSettings.GetCommandFlag("DBTrack"); ProfileTimer.Reset(); - int profileDepth = ProfileTimer.Push(">>>> transitionreport"); - rpt = new PDFTransitionReport(procedureInfo, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\TransitionReport.pdf"); + _ = ProfileTimer.Push(">>>> transitionreport"); + rpt = new PDFTransitionReport(procedureInfo, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\TransitionReport.pdf"); pbTrans.Maximum = rpt.TransitionInfoCount; tmrReportStart.Enabled = true; } @@ -131,7 +129,7 @@ namespace VEPROMS { tmrReportFinish.Enabled = false; System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS\TransitionReport.pdf"); - this.Close(); + Close(); } } } \ No newline at end of file diff --git a/PROMS/VEPROMS User Interface/frmAnnotationsCleanup.cs b/PROMS/VEPROMS User Interface/frmAnnotationsCleanup.cs index ca3f70f8..3829783d 100644 --- a/PROMS/VEPROMS User Interface/frmAnnotationsCleanup.cs +++ b/PROMS/VEPROMS User Interface/frmAnnotationsCleanup.cs @@ -1,32 +1,22 @@ 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; using VEPROMS.CSLA.Library; -using Volian.Base.Library; -//using Volian.Pipe.Library; -using System.Xml; -using System.Diagnostics; -using JR.Utils.GUI.Forms; namespace VEPROMS { public partial class frmAnnotationsCleanup : Form { - Label mylab = new Label(); string procList = ""; string docvList = ""; int AnnotationTyp; string AnnotationName = ""; string totalDeleteCnt = ""; - List pil2 = new List(); - List dvil2 = new List(); - private frmBatchRefresh mainForm = null; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + List pil2 = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + List dvil2 = new List(); + private readonly frmBatchRefresh mainForm = null; // frmAnnotationsCleanup constructor passes users procedure and docversion selections from frmBatchRefresh public frmAnnotationsCleanup(Form callingForm, List pil, List dvil) @@ -47,7 +37,6 @@ namespace VEPROMS foreach (LocalAnnotationTypeInfo lati in myLocalAnnotationTypeInfoList) { AnnotationsList.Add(lati.TypeID.ToString(), lati.Name); - //cbAnnotationTypes.Items.Add(new { Name = lati.Name, Value = lati.TypeID }); } lbAnnotationTypes.DataSource = new BindingSource(AnnotationsList, null); @@ -67,11 +56,11 @@ namespace VEPROMS { if (procList == "") { - procList = procList + p.ItemID.ToString(); + procList += p.ItemID.ToString(); } else { - procList = procList + "," + p.ItemID.ToString(); + procList = $"{procList},{p.ItemID}"; } } } @@ -88,19 +77,20 @@ namespace VEPROMS { if (docvList == "") { - docvList = docvList + d.VersionID.ToString(); + docvList += d.VersionID.ToString(); } else { - docvList = docvList + "," + d.VersionID.ToString(); + docvList = $"{docvList},{d.VersionID}"; } } } return docvList; } - - private AnnotationTypeInfoList myAnnotationTypeInfoList = null; - private LocalAnnotationTypeInfoList myLocalAnnotationTypeInfoList = null; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private AnnotationTypeInfoList myAnnotationTypeInfoList = null; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private LocalAnnotationTypeInfoList myLocalAnnotationTypeInfoList = null; // Process used to cleanup annotations "(Proceed?" button) private void button1_Click(object sender, EventArgs e) @@ -112,21 +102,15 @@ namespace VEPROMS TextBox frm3 = mainForm.GettxtResults(); AnnotationTyp = System.Convert.ToInt32(((KeyValuePair)lbAnnotationTypes.SelectedItem).Key); AnnotationName = System.Convert.ToString(((KeyValuePair)lbAnnotationTypes.SelectedItem).Value); - frm3.AppendText("Deleting Annotations: Annotation Type: " + '"' + AnnotationName + '"'); - frm3.AppendText(Environment.NewLine + "P = Procedure, F = Folder" + Environment.NewLine); - int deletecountProc = 0; - int deletecountDocv = 0; - foreach (var p in pil2) + frm3.AppendText($"Deleting Annotations: Annotation Type: \"{AnnotationName}\""); + frm3.AppendText($"{Environment.NewLine}P = Procedure, F = Folder{Environment.NewLine}"); + foreach (var p in pil2) { if (p.IsProcedure) { - //AnnotationTyp = System.Convert.ToInt32(((KeyValuePair)lbAnnotationTypes.SelectedItem).Key); - //AnnotationName = System.Convert.ToString(((KeyValuePair)lbAnnotationTypes.SelectedItem).Value); - //deletecountProc = Annotation.getAnnotationProcCnt(AnnotationTyp, getAnnotationProcItems(p)); - deletecountProc = Annotation.getAnnotationProcCnt(AnnotationTyp, p.ItemID.ToString()); - frm2.AppendText(Environment.NewLine + p.DisplayNumber + ' ' + p.DisplayText); - //frm3.AppendText(Environment.NewLine + "P: " + p.DisplayNumber + '"' + p.DisplayText + '"' + " Type: " + '"' + AnnotationName + '"' + " count: " + deletecountProc); - frm3.AppendText(Environment.NewLine + "P: " + p.DisplayNumber + '"' + p.DisplayText + '"' + " Delete count: " + deletecountProc); + int deletecountProc = Annotation.getAnnotationProcCnt(AnnotationTyp, p.ItemID.ToString()); + frm2.AppendText($"{Environment.NewLine}{p.DisplayNumber} {p.DisplayText}"); + frm3.AppendText($"{Environment.NewLine}P: {p.DisplayNumber}\"{p.DisplayText}\" Delete count: {deletecountProc}"); Annotation.DeleteAnnotationProcByType(AnnotationTyp, p.ItemID.ToString()); lblCountNumber.Text = "0"; } @@ -136,18 +120,16 @@ namespace VEPROMS { if (d.IsDocVersion) { - //AnnotationTyp = System.Convert.ToInt32(((KeyValuePair)lbAnnotationTypes.SelectedItem).Key); - //AnnotationName = System.Convert.ToString(((KeyValuePair)lbAnnotationTypes.SelectedItem).Value); - deletecountDocv = Annotation.getAnnotationCountDocv(AnnotationTyp, d.VersionID.ToString()); - frm2.AppendText(Environment.NewLine + d.ActiveParent.ToString()); - frm3.AppendText(Environment.NewLine + "F: " + '"' + d.ActiveParent.ToString() + '"' + " Delete count: " + deletecountDocv); + int deletecountDocv = Annotation.getAnnotationCountDocv(AnnotationTyp, d.VersionID.ToString()); + frm2.AppendText(Environment.NewLine + d.ActiveParent.ToString()); + frm3.AppendText($"{Environment.NewLine}F: \"{d.ActiveParent.ToString()}\" Delete count: {deletecountDocv}"); AnnotationTyp = System.Convert.ToInt32(((KeyValuePair)lbAnnotationTypes.SelectedItem).Key); Annotation.DeleteAnnotationDocvByType(AnnotationTyp, d.VersionID.ToString()); lblCountNumber.Text = "0"; } } - frm3.AppendText(Environment.NewLine + Environment.NewLine + "Total Annotations Deleted: " + totalDeleteCnt + Environment.NewLine + Environment.NewLine); + frm3.AppendText($"{Environment.NewLine}{Environment.NewLine}Total Annotations Deleted: {totalDeleteCnt}{Environment.NewLine}{Environment.NewLine}"); } } @@ -178,13 +160,10 @@ namespace VEPROMS } } - // Close form. - private void btnClose_Click(object sender, EventArgs e) - { - this.Close(); - } + // Close form. + private void btnClose_Click(object sender, EventArgs e) => Close(); - } + } } diff --git a/PROMS/VEPROMS User Interface/frmBatchRefresh.cs b/PROMS/VEPROMS User Interface/frmBatchRefresh.cs index 89d1bc48..6945e606 100644 --- a/PROMS/VEPROMS User Interface/frmBatchRefresh.cs +++ b/PROMS/VEPROMS User Interface/frmBatchRefresh.cs @@ -15,28 +15,23 @@ namespace VEPROMS { public partial class frmBatchRefresh : Form { - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } - private bool IsAdministratorUser = false; //C2020-035 used to control what Set Amins can do + public SessionInfo MySessionInfo { get; set; } + private readonly bool IsAdministratorUser = false; //C2020-035 used to control what Set Amins can do // C2017-030 - new Admin Tools user interface // pass in session info to constructor - private frmVEPROMS _veProms; + private readonly frmVEPROMS _veProms; public frmBatchRefresh(SessionInfo sessionInfo, frmVEPROMS veProms) { InitializeComponent(); - _MySessionInfo = sessionInfo; + MySessionInfo = sessionInfo; _veProms = veProms; // When opening Admin tools Repair tab will be default. - this.sideNavItmRepair.Checked = true; + sideNavItmRepair.Checked = true; if (sideNavItmDelete.Checked) { @@ -73,28 +68,22 @@ namespace VEPROMS //default to 10 years back dtePurge.Value = DateTime.Now.AddYears(-10); } - // Make txtProcess text box available to frmAnnotationsClean form. - internal TextBox GettxtProcess() + // Make txtProcess text box available to frmAnnotationsClean form. + internal TextBox GettxtProcess() => txtProcess; + + // Make txtResults text box available to frmAnnotationsClean form. + internal TextBox GettxtResults() => txtResults; + + // NOTE: removed the Refresh ROs and Refresh Transitions and ROs options (now only Transitions can be refreshed) + // the Update ROs and Refresh ROs logic was merged together. The Update ROs will functionally do both + // also annotations will be placed on step elements that have RO changes + + // make all of the hyphen character consistant so they can all be found with the Search function + + + private void FixHyphens() { - return txtProcess; - } - - // Make txtResults text box available to frmAnnotationsClean form. - internal TextBox GettxtResults() - { - return txtResults; - } - - // NOTE: removed the Refresh ROs and Refresh Transitions and ROs options (now only Transitions can be refreshed) - // the Update ROs and Refresh ROs logic was merged together. The Update ROs will functionally do both - // also annotations will be placed on step elements that have RO changes - - // make all of the hyphen character consistant so they can all be found with the Search function - - - private void FixHyphens() - { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Standardizing Hyphens"); txtProcess.AppendText(Environment.NewLine); @@ -112,29 +101,26 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } - private Dictionary myProcedures = new Dictionary(); - private Dictionary myDocVersions = new Dictionary(); - private Dictionary myFolders = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary myProcedures = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary myDocVersions = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary myFolders = new Dictionary(); - private void frmBatchRefresh_Load(object sender, EventArgs e) - { - IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. - } - private bool IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. - private void frmBatchRefresh_FormClosing(object sender, EventArgs e) - { - IsClosing = true;//B2017-221 Allow the batch dialog to close when waiting to process. - } - // C2017-030 - new Admin Tools user interface - // check to see if at least one tree node is checked. - // Used to determin whether to make the process button active for - // Refresh Transitions and for Update RO Values - // B2025-013 Admin Tool Tree Behavior - //Made this generic so same logic for all the TreeViews on this form - private bool AtLeastOneNodeChecked(TreeNodeCollection col) + private void frmBatchRefresh_Load(object sender, EventArgs e) => IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. + private bool IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. + private void frmBatchRefresh_FormClosing(object sender, EventArgs e) => IsClosing = true;//B2017-221 Allow the batch dialog to close when waiting to process. + // C2017-030 - new Admin Tools user interface + // check to see if at least one tree node is checked. + // Used to determin whether to make the process button active for + // Refresh Transitions and for Update RO Values + // B2025-013 Admin Tool Tree Behavior + //Made this generic so same logic for all the TreeViews on this form + private bool AtLeastOneNodeChecked(TreeNodeCollection col) { foreach (TreeNode tn in col) if (NodeIsChecked(tn)) @@ -154,7 +140,7 @@ namespace VEPROMS //C2026-002 Enhancements to new admin Tool for ROs not used. private void ResetmyTV_RO_DBs() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; myTV_RO_DBs.Nodes.Clear(); TreeNode tn = myTV_RO_DBs.Nodes.Add("Select All"); @@ -169,13 +155,13 @@ namespace VEPROMS } tn.Expand(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } private void ResetTV(bool noProcs) { btnFixLinks.Enabled = false; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; myTV.Nodes.Clear(); myDocVersions.Clear(); myFolders.Clear(); @@ -184,14 +170,13 @@ namespace VEPROMS tn.Tag = fi; if (fi.ChildFolderCount > 0) LoadChildFolders(fi, tn, noProcs); - if (myTV.SelectedNode != null) - myTV.SelectedNode.Expand(); - this.Cursor = Cursors.Default; + myTV.SelectedNode?.Expand(); + Cursor = Cursors.Default; } private void ResetDelTV(bool noProcs) { btnFixLinks.Enabled = false; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; myTVdel.Nodes.Clear(); myDocVersions.Clear(); FolderInfo fi = FolderInfo.GetTop(); @@ -200,21 +185,22 @@ namespace VEPROMS if (fi.ChildFolderCount > 0) { - TreeNode tn = new TreeNode(fi.Name); - tn.Tag = fi; - tn.StateImageIndex = -1; // Hide the checkbox for the root node - LoadChildFolders(fi, tn, noProcs); + TreeNode tn = new TreeNode(fi.Name) + { + Tag = fi, + StateImageIndex = -1 // Hide the checkbox for the root node + }; + LoadChildFolders(fi, tn, noProcs); myTVdel.Nodes.Add(tn); } - if (myTVdel.SelectedNode != null) - myTVdel.SelectedNode.Expand(); + myTVdel.SelectedNode?.Expand(); //Expand if folders if (noProcs) myTVdel.ExpandAll(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // B2021-060 Higher level folders where being removed from the tree even if there was a child folder that containe a working draft set @@ -304,7 +290,7 @@ namespace VEPROMS private void UpdateROValues() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; List pil = new List(); // C2023-002: list of checked out procedures, used in frmBatchRefreshCheckedOut dialog List dvil = new List(); foreach (TreeNode tn in myDocVersions.Keys) @@ -377,14 +363,16 @@ namespace VEPROMS sb.AppendLine("Once this is complete you can continue the process otherwise you may terminate the process immediately."); sb.AppendLine(); sb.AppendLine("Have you requested the users to close the procedures and do you want to continue the process?"); - frmBatchRefreshCheckedOut frmCO = new frmBatchRefreshCheckedOut(1); - frmCO.MySessionInfo = MySessionInfo; - frmCO.CheckedOutProcedures = pil; // C2023-002: set list of checked out procedures - frmCO.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmCO.Width, Screen.PrimaryScreen.WorkingArea.Height - frmCO.Height); + frmBatchRefreshCheckedOut frmCO = new frmBatchRefreshCheckedOut(1) + { + MySessionInfo = MySessionInfo, + CheckedOutProcedures = pil // C2023-002: set list of checked out procedures + }; + frmCO.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmCO.Width, Screen.PrimaryScreen.WorkingArea.Height - frmCO.Height); // C2023-002: Allow close of dialog that has list of procedures that are checked out if (frmCO.ShowDialog(this) != DialogResult.Cancel) { - while (!this.Visible) + while (!Visible) Application.DoEvents(); } else @@ -400,7 +388,7 @@ namespace VEPROMS txtProcess.AppendText(string.Format("Could Not Complete: {0} {1} Seconds Elapsed", pEnd.ToString("MM/dd/yyyy @ HH:mm"), TimeSpan.FromTicks(pEnd.Ticks - pStart.Ticks).TotalSeconds)); pbProcess.Value = pbProcess.Maximum; } - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } //C2025-011 RO Update Admin Tool Memory Enhancements @@ -425,7 +413,7 @@ namespace VEPROMS private void CheckROLinks() { bool badLinksFound = false; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; List pil = new List(); // populate a list of procedures that the user selected to process foreach (TreeNode tn in myProcedures.Keys) @@ -500,15 +488,17 @@ namespace VEPROMS if (piq.Count > 0) { - frmBatchRefreshCheckedOut frmCO = new frmBatchRefreshCheckedOut(0); - frmCO.MySessionInfo = MySessionInfo; - frmCO.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmCO.Width, Screen.PrimaryScreen.WorkingArea.Height - frmCO.Height); + frmBatchRefreshCheckedOut frmCO = new frmBatchRefreshCheckedOut(0) + { + MySessionInfo = MySessionInfo + }; + frmCO.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmCO.Width, Screen.PrimaryScreen.WorkingArea.Height - frmCO.Height); frmCO.Show(this); - while (!this.Visible) + while (!Visible) Application.DoEvents(); } } - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // B2018-002 - Invalid Transitions - Define Transition Refresh Statistics @@ -528,7 +518,7 @@ namespace VEPROMS { // B2018-002 - Invalid Transitions - Initialize Transition Refresh Statistics ResetTransNumbers(); - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; List pil = new List(); foreach (TreeNode tn in myProcedures.Keys) if (tn.Checked) @@ -606,16 +596,18 @@ namespace VEPROMS sb.AppendLine("Once this is complete you can continue the process otherwise you may terminate the process immediately."); sb.AppendLine(); sb.AppendLine("Have you requested the users to close the procedures and do you want to continue the process?"); - frmBatchRefreshCheckedOut frmCO = new frmBatchRefreshCheckedOut(0); - frmCO.MySessionInfo = MySessionInfo; - frmCO.CheckedOutProcedures = pil; - frmCO.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmCO.Width, Screen.PrimaryScreen.WorkingArea.Height - frmCO.Height); + frmBatchRefreshCheckedOut frmCO = new frmBatchRefreshCheckedOut(0) + { + MySessionInfo = MySessionInfo, + CheckedOutProcedures = pil + }; + frmCO.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmCO.Width, Screen.PrimaryScreen.WorkingArea.Height - frmCO.Height); frmCO.Show(this); - while (!this.Visible) + while (!Visible) Application.DoEvents(); } } - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; // B2018-002 - Invalid Transitions - Display Transition Refresh Statistic if (numTransFixed == 0 && numTransConverted == 0 && numTransCantFix == 0) MessageBox.Show(string.Format("{0} Transitions Checked.\n\nNo Transitions Modified.", numTransProcessed), "Refresh Transitions Completed"); @@ -629,7 +621,7 @@ namespace VEPROMS // the next time the procedures are printed. This also forces ROs to be refreshed in the attachments private void DeletePDFs() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Refreshing Word Attachments"); txtProcess.AppendText(Environment.NewLine); @@ -647,7 +639,7 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } private int RegenCounter = 0; @@ -659,7 +651,7 @@ namespace VEPROMS // so that this is not needed the next time the procedures are printed. This also forces ROs to be refreshed in the attachments private void RegenPDFs() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Generating missing Word Attachments"); txtProcess.AppendText(Environment.NewLine); @@ -737,7 +729,7 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } //Outputs the Progress of Regenerating the PDFs every __ minutes @@ -756,7 +748,7 @@ namespace VEPROMS // rerun until all tables/text fields are completed. private void RefreshTablesForSearch() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Refreshing Tables for Search"); txtProcess.AppendText(Environment.NewLine); @@ -783,7 +775,7 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } private int RefreshForSearch() { @@ -824,7 +816,7 @@ namespace VEPROMS } catch { - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return -cntfix; } } @@ -839,7 +831,7 @@ namespace VEPROMS // tool renamed to Remove Orphan Items private void PurgeDisconnectedItems() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Purging Orphan Items"); txtProcess.AppendText(Environment.NewLine); @@ -881,13 +873,13 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Admin Tools user interface is one of two tools run from Remove Obsolete RO Data private void RemoveUnusedRoFstsAndFigures() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Purging Unused RoFSTs and Figures Items"); txtProcess.AppendText(Environment.NewLine); @@ -936,14 +928,14 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Admin Tools user interface // is one of two tools run from Remove Obsolete RO Data private void CleanUpROAssociations() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Purging Unused Referenced Object Associations"); txtProcess.AppendText(Environment.NewLine); @@ -985,14 +977,14 @@ namespace VEPROMS txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Admin Tools user interface // tool was renamed to Show Users private void GetDatabaseSessions() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Show Users in PROMS"); txtProcess.AppendText(Environment.NewLine); @@ -1004,7 +996,7 @@ namespace VEPROMS DateTime pEnd = DateTime.Now; txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; MessageBox.Show("Show Users Completed", "Show Users"); } @@ -1046,10 +1038,10 @@ namespace VEPROMS FinalProgressBarMessage = "No existing RO.FST"; txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText("No existing ro.fst in path " + roFstInfo.MyRODb.FolderPath + ". Check for invalid path"); + txtProcess.AppendText($"No existing ro.fst in path {roFstInfo.MyRODb.FolderPath}. Check for invalid path"); txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); - txtResults.AppendText("No existing ro.fst in path " + roFstInfo.MyRODb.FolderPath + ". Check for invalid path"); + txtResults.AppendText($"No existing ro.fst in path {roFstInfo.MyRODb.FolderPath}. Check for invalid path"); txtResults.AppendText(Environment.NewLine); txtResults.AppendText(Environment.NewLine); return; @@ -1123,15 +1115,12 @@ namespace VEPROMS } StringBuilder myFixes; - int myFixesCount = 0; - int myConvertCount = 0; // show the changes made in the Results pannel, include the ItemId of the step element void ContentInfo_StaticContentInfoChange(object sender, StaticContentInfoEventArgs args) { if (args.Type == "TX") { - myFixesCount++; if (args.NewValue.StartsWith("Reason for Change:")) myFixes.AppendLine(string.Format("Fixed Transition for {1}({4}){0}Old Text: {2}{0}{3}{0}", Environment.NewLine, (sender as ItemInfo).ShortPath, args.OldValue, args.NewValue, (sender as ItemInfo).ItemID)); else @@ -1155,13 +1144,15 @@ namespace VEPROMS private void btnSave_Click(object sender, EventArgs e) { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.DefaultExt = "txt"; - sfd.AddExtension = true; - sfd.Filter = "Text Files (*.txt)|*.txt"; - sfd.FileName = string.Format("BatchRefreshResults_{0}", DateTime.Now.ToString("yyyyMMdd_HHmm")); - sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS"; - DialogResult dr = sfd.ShowDialog(); + SaveFileDialog sfd = new SaveFileDialog + { + DefaultExt = "txt", + AddExtension = true, + Filter = "Text Files (*.txt)|*.txt", + FileName = string.Format("BatchRefreshResults_{0}", DateTime.Now.ToString("yyyyMMdd_HHmm")), + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS" + }; + DialogResult dr = sfd.ShowDialog(); if (dr == DialogResult.OK) { @@ -1186,7 +1177,7 @@ namespace VEPROMS { //Purge Change History - string statmsg = $"Purging all Change History before {dtePurge.Value.Date.ToString("MM/dd/yyyy")}"; + string statmsg = $"Purging all Change History before {dtePurge.Value.Date:MM/dd/yyyy}"; InitialProgressBarMessage = statmsg; txtResults.AppendText(statmsg); txtResults.AppendText(Environment.NewLine); @@ -1194,7 +1185,7 @@ namespace VEPROMS Maintenance.PurgeChangeHistory(dtePurge.Value); //update status - statmsg = $"Finished Purging all Change History before {dtePurge.Value.Date.ToString("MM/dd/yyyy")}. Updating indexes to reflect cleaned data."; + statmsg = $"Finished Purging all Change History before {dtePurge.Value.Date:MM/dd/yyyy}. Updating indexes to reflect cleaned data."; DoProgressBarRefresh(50, 100, statmsg); txtProcess.AppendText(statmsg); txtProcess.AppendText(Environment.NewLine); @@ -1380,14 +1371,11 @@ namespace VEPROMS ResetTV(false); } - // C2017-030 new Admin Tools user interface - private void sideNavItmExit_Click(object sender, EventArgs e) - { - this.Close(); - } + // C2017-030 new Admin Tools user interface + private void sideNavItmExit_Click(object sender, EventArgs e) => Close(); - // new Admin Tools user interface for deletes - private void sideNavItmDelete_Click(object sender, EventArgs e) + // new Admin Tools user interface for deletes + private void sideNavItmDelete_Click(object sender, EventArgs e) { AdminToolType = E_AdminToolType.Delete; lblAdmToolProgressType.Text = ""; @@ -1426,12 +1414,12 @@ namespace VEPROMS }; private E_AdminToolType AdminToolType = E_AdminToolType.Repair; - DevComponents.DotNetBar.StepItem siOrphDatRecs = new DevComponents.DotNetBar.StepItem("siOrphDatRecs", "Orphan Data Records"); - DevComponents.DotNetBar.StepItem siObsoleteROData = new DevComponents.DotNetBar.StepItem("siObsoleteROData", "Obsolete RO Data"); - DevComponents.DotNetBar.StepItem siStandardHyphens = new DevComponents.DotNetBar.StepItem("siStandardHyphens", "Standardize Hyphens"); - DevComponents.DotNetBar.StepItem siRefreshAttmts = new DevComponents.DotNetBar.StepItem("siRefreshAttmts", "Refresh Word Attachments"); - DevComponents.DotNetBar.StepItem siRegenAttmts = new DevComponents.DotNetBar.StepItem("siRegenAttmts", "Regenerate Word Attachments"); - DevComponents.DotNetBar.StepItem siRefreshTblsSrchTxt = new DevComponents.DotNetBar.StepItem("siRefreshTblsSrchTxt", "Refresh Tables For Search"); + readonly DevComponents.DotNetBar.StepItem siOrphDatRecs = new DevComponents.DotNetBar.StepItem("siOrphDatRecs", "Orphan Data Records"); + readonly DevComponents.DotNetBar.StepItem siObsoleteROData = new DevComponents.DotNetBar.StepItem("siObsoleteROData", "Obsolete RO Data"); + readonly DevComponents.DotNetBar.StepItem siStandardHyphens = new DevComponents.DotNetBar.StepItem("siStandardHyphens", "Standardize Hyphens"); + readonly DevComponents.DotNetBar.StepItem siRefreshAttmts = new DevComponents.DotNetBar.StepItem("siRefreshAttmts", "Refresh Word Attachments"); + readonly DevComponents.DotNetBar.StepItem siRegenAttmts = new DevComponents.DotNetBar.StepItem("siRegenAttmts", "Regenerate Word Attachments"); + readonly DevComponents.DotNetBar.StepItem siRefreshTblsSrchTxt = new DevComponents.DotNetBar.StepItem("siRefreshTblsSrchTxt", "Refresh Tables For Search"); // this will update/rebuild the progress bar in the bottom panel of Admin Tools private void setupProgessSteps1() { @@ -1483,13 +1471,10 @@ namespace VEPROMS } } - // used for all of the Switch buttons (ON/OFF buttons) - private void swCk_ValueChanged(object sender, EventArgs e) - { - setupProgessSteps1(); - } + // used for all of the Switch buttons (ON/OFF buttons) + private void swCk_ValueChanged(object sender, EventArgs e) => setupProgessSteps1(); - private void swUpdateROVals_ValueChanged(object sender, EventArgs e) + private void swUpdateROVals_ValueChanged(object sender, EventArgs e) { if (swUpdateROVals.Value) { @@ -1509,16 +1494,13 @@ namespace VEPROMS } } - #endregion + #endregion - // C2017-030 New Admin Tools user interface - // functions to handle the progress bar in the bottom panel of Admin Tools - private void StepProgress(int prgStpIdx, int val) - { - ((DevComponents.DotNetBar.StepItem)progressSteps1.Items[prgStpIdx]).Value = val; - } + // C2017-030 New Admin Tools user interface + // functions to handle the progress bar in the bottom panel of Admin Tools + private void StepProgress(int prgStpIdx, int val) => ((DevComponents.DotNetBar.StepItem)progressSteps1.Items[prgStpIdx]).Value = val; - private void ClearStepProgress() + private void ClearStepProgress() { for (int i = 0; i < progressSteps1.Items.Count; i++) { @@ -1673,7 +1655,7 @@ namespace VEPROMS txtResults.Clear(); txtProcess.Clear(); - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; //Create checked proce and doc info lists. List pil = new List(); @@ -1756,7 +1738,7 @@ namespace VEPROMS sb.AppendLine("If you want to delete annotations from these working drafts, please contact the respective users and have them close any procedures in the working draft."); sb.AppendLine(); txtProcess.AppendText(sb.ToString()); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return; } @@ -1790,7 +1772,7 @@ namespace VEPROMS } - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } private void ProcessDelete(List foldersToDelete, List emptyFoldersToDelete) @@ -1952,14 +1934,16 @@ namespace VEPROMS //CSM - C2025-043 report RO's that are not used in any of the PROMS data. private void btnROsNotUsed_Click(object sender, EventArgs e) { - //Get the path to save the Image to - SaveFileDialog sfd = new SaveFileDialog(); - sfd.DefaultExt = "bmp"; - sfd.AddExtension = true; - sfd.Filter = "Image Files (*.bmp)|*.bmp"; - sfd.FileName = string.Format("ROsNotUsed_{0}", DateTime.Now.ToString("yyyyMMdd_HHmm")); - sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS"; - DialogResult dr = sfd.ShowDialog(); + //Get the path to save the Image to + SaveFileDialog sfd = new SaveFileDialog + { + DefaultExt = "bmp", + AddExtension = true, + Filter = "Image Files (*.bmp)|*.bmp", + FileName = string.Format("ROsNotUsed_{0}", DateTime.Now.ToString("yyyyMMdd_HHmm")), + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS" + }; + DialogResult dr = sfd.ShowDialog(); if (dr == DialogResult.OK) { diff --git a/PROMS/VEPROMS User Interface/frmBatchRefreshCheckedOut.cs b/PROMS/VEPROMS User Interface/frmBatchRefreshCheckedOut.cs index 8eba4e10..a44a601e 100644 --- a/PROMS/VEPROMS User Interface/frmBatchRefreshCheckedOut.cs +++ b/PROMS/VEPROMS User Interface/frmBatchRefreshCheckedOut.cs @@ -1,35 +1,18 @@ 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 LBOutlookLibrary; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Net.Mail; -using System.Net; -using System.IO; namespace VEPROMS { public partial class frmBatchRefreshCheckedOut : Form { - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } - private List _CheckedOutProcedures; - public List CheckedOutProcedures - { - get { return _CheckedOutProcedures; } - set { _CheckedOutProcedures = value; } - } - private int RType = -1; // C2023-002: Flag type of checkout, docversion -1 or procedures 0 + public SessionInfo MySessionInfo { get; set; } + public List CheckedOutProcedures { get; set; } + private readonly int RType = -1; // C2023-002: Flag type of checkout, docversion -1 or procedures 0 public frmBatchRefreshCheckedOut(int type) { RType = type; @@ -53,32 +36,39 @@ namespace VEPROMS } private void AddToDisplayList(ProcedureInfo pi) { - Panel p = new Panel(); - p.BorderStyle = BorderStyle.FixedSingle; - p.Dock = DockStyle.Top; - p.Height = 28; - if (RType != 1) // C2023-002: only put out ForceCheckin & sendemail buttons if on procedures (can't check in a docversion) + Panel p = new Panel + { + BorderStyle = BorderStyle.FixedSingle, + Dock = DockStyle.Top, + Height = 28 + }; + if (RType != 1) // C2023-002: only put out ForceCheckin & sendemail buttons if on procedures (can't check in a docversion) { - Button b = new Button(); - //b.FlatStyle = FlatStyle.Popup; - b.Dock = DockStyle.Right; - b.Text = "Force Check In"; - b.Tag = pi; - b.Click += new EventHandler(ForceCheckIn_Click); + Button b = new Button + { + Dock = DockStyle.Right, + Text = "Force Check In", + Tag = pi + }; + b.Click += new EventHandler(ForceCheckIn_Click); p.Controls.Add(b); - b = new Button(); - //b.FlatStyle = FlatStyle.Popup; - b.Dock = DockStyle.Right; - b.Text = "Send Email"; - b.Tag = pi; - b.Click += new EventHandler(SendEmail_Click); + b = new Button + { + //b.FlatStyle = FlatStyle.Popup; + Dock = DockStyle.Right, + Text = "Send Email", + Tag = pi + }; + b.Click += new EventHandler(SendEmail_Click); p.Controls.Add(b); } - Label l = new Label(); - l.Dock = DockStyle.Fill; - l.TextAlign = ContentAlignment.MiddleLeft; - l.Text = string.Format("Procedure {0} is checked out to {1}", pi.DisplayNumber, UserInfo.GetByUserID(OwnerInfo.GetByItemID(pi.ItemID, CheckOutType.Procedure).SessionUserID).UserID); - p.Controls.Add(l); + Label l = new Label + { + Dock = DockStyle.Fill, + TextAlign = ContentAlignment.MiddleLeft, + Text = $"Procedure {pi.DisplayNumber} is checked out to {UserInfo.GetByUserID(OwnerInfo.GetByItemID(pi.ItemID, CheckOutType.Procedure).SessionUserID).UserID}" + }; + p.Controls.Add(l); pnlList.Controls.Add(p); p.BringToFront(); pnlList.Focus(); @@ -103,15 +93,7 @@ namespace VEPROMS private string BuildEmailMessageBody(ProcedureInfo pi) { StringBuilder body = new StringBuilder(); - //body.AppendLine("THIS IS A TEST MESSAGE FROM JIM BODINE"); - //body.AppendLine(); - body.AppendLine(string.Format("The administrator needs you to check in procedure {0} so the administrator can continue an administrative tool process", pi.DisplayNumber)); - //body.AppendLine(); - //body.AppendLine("Obviously, you do not really have this procedure checked out, so you really do not have to do anything."); - //body.AppendLine(); - //body.AppendLine("However, I would appreciate it if you would reply to this email so I know the email worked"); - //body.AppendLine(); - //body.AppendLine("I will try NOT to overwhelm your email system :-)"); + body.AppendLine($"The administrator needs you to check in procedure {pi.DisplayNumber} so the administrator can continue an administrative tool process"); return body.ToString(); } void ForceCheckIn_Click(object sender, EventArgs e) @@ -134,15 +116,7 @@ namespace VEPROMS private string BuildForcedMessageBody(ProcedureInfo pi) { StringBuilder body = new StringBuilder(); - //body.AppendLine("THIS IS A TEST MESSAGE FROM JIM BODINE"); - //body.AppendLine(); - body.AppendLine(string.Format("The administrator needed to force check in procedure {0} so the administrator could continue an administrative tool process", pi.DisplayNumber)); - //body.AppendLine(); - //body.AppendLine("Obviously, you do not really have this procedure checked out, so nothing really got forced checked in."); - //body.AppendLine(); - //body.AppendLine("However, I would appreciate it if you would reply to this email so I know the email worked"); - //body.AppendLine(); - //body.AppendLine("I will try NOT to overwhelm your email system :-)"); + body.AppendLine($"The administrator needed to force check in procedure {pi.DisplayNumber} so the administrator could continue an administrative tool process"); return body.ToString(); } private bool SendOutlookEmail(string email, string subject, string body) @@ -163,7 +137,7 @@ namespace VEPROMS if (ex.Message.ToLower().Contains("failed due to the following error: 80080005")) MessageBox.Show("You cannot send email via a running instance of Outlook from VE PROMS running from within Visual Studio."); else - MessageBox.Show(string.Format("{0} - {1}", ex.GetType().Name, ex.Message)); + MessageBox.Show($"{ex.GetType().Name} - {ex.Message}"); return false; } } @@ -180,7 +154,7 @@ namespace VEPROMS CheckedOutProcedures = tmp; if (CheckedOutProcedures.Count == 0) { - this.Close(); + Close(); return; } foreach (ProcedureInfo pi in CheckedOutProcedures) diff --git a/PROMS/VEPROMS User Interface/frmFolderProperties.cs b/PROMS/VEPROMS User Interface/frmFolderProperties.cs index b15ad4b1..029c0ac5 100644 --- a/PROMS/VEPROMS User Interface/frmFolderProperties.cs +++ b/PROMS/VEPROMS User Interface/frmFolderProperties.cs @@ -1,13 +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 System.IO; using VEPROMS.CSLA.Library; -using DevComponents; using DevComponents.DotNetBar; using DevComponents.DotNetBar.Controls; using System.Drawing.Imaging; @@ -20,9 +16,9 @@ namespace VEPROMS public partial class frmFolderProperties : DevComponents.DotNetBar.Office2007Form { private bool _Initializing = false; - private FolderConfig _FolderConfig; - private bool _IsVepromsNode = false; - private bool _IsDefaultSettingNode = false; + private readonly FolderConfig _FolderConfig; + private readonly bool _IsVepromsNode = false; + private readonly bool _IsDefaultSettingNode = false; private string _DefaultFormatName = null; private string _DefaultChgBarType = null; @@ -31,16 +27,8 @@ namespace VEPROMS private string _DefaultChgBarUsrMsg1 = null; private string _DefaultChgBarUsrMsg2 = null; private string _DefaultROGraficFileExtension = null; - //private string _DefaultImagePrefix = null; - //private string _DefaultROPrefix = null; - //private string _DefaultPagination = null; private string _DefaultWatermark = null; - private bool _DefaultDisableDuplex = false; private string _DefaultFormatColumns = null; - //private string _ROcolor; - //private string _TransColor; - //private string _EditBckgndColor; - //private string _ViewBckgndColor; private bool _ValidateTextBox = true; public frmFolderProperties(FolderConfig folderConfig) @@ -54,7 +42,7 @@ namespace VEPROMS btnGeneral.PerformClick(); // always start with General tab or button _Initializing = false; // Build window caption - this.Text = string.Format("{0} Properties",folderConfig.Name); + Text = $"{folderConfig.Name} Properties"; if (_IsDefaultSettingNode) { // Change these labels for the first node after the VE-PROMS node. @@ -108,10 +96,6 @@ namespace VEPROMS } SetupDefault(_DefaultROGraficFileExtension, ppLblGrphFileExtDefault, ppCmbxGrphFileExt); - // Get the default Print Pagination - //_DefaultPagination = _FolderConfig.Print_Pagination.ToString(); - //SetupDefault(EnumDescConverter.GetEnumDescription(_FolderConfig.Print_Pagination), ppLblPaginationDefault, ppCmbxPagination); - // Get the default Watermark _DefaultWatermark = _FolderConfig.Print_Watermark.ToString(); SetupDefault(EnumDescConverter.GetEnumDescription(_FolderConfig.Print_Watermark), ppLblWatermarkDefault, ppCmbxWatermark); @@ -132,17 +116,8 @@ namespace VEPROMS private void frmFolderProperties_Load(object sender, EventArgs e) { _Initializing = true; - // populate the a list box of possible graphic file types - // supported by .NET -// foreach (ImageCodecInfo info in ImageCodecInfo.GetImageDecoders()) -// { -// string st = string.Format("{0} - ({1})", info.FormatDescription, info.FilenameExtension); -// //string st = string.Format("{0}", info.FormatDescription); -// comboBoxEx1.Items.Add(st); -// } imageCodecInfoBindingSource.DataSource = ImageCodecInfo.GetImageDecoders(); - //formatInfoListBindingSource.DataSource = FormatInfoList.Get(); folderConfigBindingSource.DataSource = _FolderConfig; ppCmbxFormat.DataSource = null; @@ -160,20 +135,16 @@ namespace VEPROMS // Get the saved settings for this user // // This setting tells us if we should display the default values on this property page - //ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultFolderProp"] != null)? Settings.Default.ShowDefaultFolderProp : false; - if (_IsVepromsNode || Settings.Default["ShowDefaultFolderProp"] == null) - ppCbShwDefSettings.Checked = false; - else - ppCbShwDefSettings.Checked = Settings.Default.ShowDefaultFolderProp; + ppCbShwDefSettings.Checked = !_IsVepromsNode && Settings.Default["ShowDefaultFolderProp"] != null && Settings.Default.ShowDefaultFolderProp; - // Get the User's property page style "PropPageStyle" (this is a system wide user setting) - // 1 - Button Dialog (default) - // 2 - Tab Dialog - if ((int)Settings.Default["PropPageStyle"] == (int)PropPgStyle.Tab) + // Get the User's property page style "PropPageStyle" (this is a system wide user setting) + // 1 - Button Dialog (default) + // 2 - Tab Dialog + if ((int)Settings.Default["PropPageStyle"] == (int)PropPgStyle.Tab) { tcFolder.TabsVisible = true; panButtons.Visible = false; - this.Width -= panButtons.Width; + Width -= panButtons.Width; } // Get the default values for the property page information @@ -186,30 +157,26 @@ namespace VEPROMS { // if we are at the top node of the tree, remove the Folder Property page tabs // that do not pertain to this level (top of tree) - this.tcFolder.Tabs.Remove(tiOutputSettings); - this.tcFolder.Tabs.Remove(tiEditSettings); + tcFolder.Tabs.Remove(tiOutputSettings); + tcFolder.Tabs.Remove(tiEditSettings); // for format settings, include it if the top node's format is NOT the base, i.e. formatid != 1. // this is done so that PROMS EXPRESS folder specific info can be displayed/used for the top // node of the tree. The formatid for the top folder for PROMS EXPRESS databases must be // set manually to the PROMS EXPRESS format. if (_FolderConfig.MyFolder.MyFormat.FormatID == 1) { - this.tcFolder.Tabs.Remove(tiFmtSettings); - this.btnFormatSettings.Visible = false; + tcFolder.Tabs.Remove(tiFmtSettings); + btnFormatSettings.Visible = false; } - //this.tcFolder.Tabs.Remove(tiAnnoTypes); // TEMPORARY - JSJ - //this.tcFolder.Tabs.Remove(tiApprvStages);// TEMPORARY - JSJ - //this.btnAnnoTypes.Visible = false; // TEMPORARY - JSJ - //this.btnApprvStages.Visible = false; // TEMPORARY - JSJ - this.btnOutputSettings.Visible = false; - this.btnEdSettings.Visible = false; + btnOutputSettings.Visible = false; + btnEdSettings.Visible = false; ppLblDefSettingsInfo.Visible = false; ppCbShwDefSettings.Visible = false; // hide check box for showing default values for top node ppCbShwDefSettings.Checked = false; // FOR NOW, don't show Start Message tab // TODO: later on, not needed for initial release. - this.tcFolder.Tabs.Remove(tiStMsg); - this.btnStMsg.Visible = false; + tcFolder.Tabs.Remove(tiStMsg); + btnStMsg.Visible = false; // Also, for the referenced object tab, the top node (veproms system level) should // allow setting of the default graphics file extension. No other folder level allows this. @@ -230,38 +197,23 @@ namespace VEPROMS tbSqlTimeout.Visible = true; lblSqlTimeout.Visible = true; lblSqlTimeoutDefault.Visible = true; - this.cbIncTranCvtPerm.Visible = true; - this.cbIncTranCvtPerm.Checked = _FolderConfig.General_IncTranCvtPerm; // C2020-033: defaults to does not have permission - this.lblIncTrans.Visible = true; + cbIncTranCvtPerm.Visible = true; + cbIncTranCvtPerm.Checked = _FolderConfig.General_IncTranCvtPerm; // C2020-033: defaults to does not have permission + lblIncTrans.Visible = true; } else { // don't show Start Message or ref obj tab if not at top level - this.tcFolder.Tabs.Remove(tiStMsg); - this.tcFolder.Tabs.Remove(tiRefObj); - this.tcFolder.Tabs.Remove(tiAnnoTypes); - this.tcFolder.Tabs.Remove(tiRevisionStages); - this.btnStMsg.Visible = false; - this.btnRefObjs.Visible = false; - this.btnAnnoTypes.Visible = false; - this.btnRevisionStages.Visible = false; - this.cbIncTranCvtPerm.Visible = false; - this.lblIncTrans.Visible = false; - - /* This color settings property page is currently no visible... - * - // this was coded for demo purposes... setup the text colors for the sample text - // of the Step Editor Text Colors property - _ROcolor = _FolderConfig.Color_ro; - if (_ROcolor == string.Empty) _ROcolor = "Orange"; - _EditBckgndColor = _FolderConfig.Color_editbackground; - if (_EditBckgndColor == string.Empty) _EditBckgndColor = "LightGray"; - _ViewBckgndColor = _FolderConfig.Default_BkColor.Name; - if (_ViewBckgndColor == string.Empty) _ViewBckgndColor = "White"; - _TransColor = _FolderConfig.Color_transition; - if (_TransColor == string.Empty) _TransColor = "Orange"; - SetupSampleTextBoxes(); - * */ + tcFolder.Tabs.Remove(tiStMsg); + tcFolder.Tabs.Remove(tiRefObj); + tcFolder.Tabs.Remove(tiAnnoTypes); + tcFolder.Tabs.Remove(tiRevisionStages); + btnStMsg.Visible = false; + btnRefObjs.Visible = false; + btnAnnoTypes.Visible = false; + btnRevisionStages.Visible = false; + cbIncTranCvtPerm.Visible = false; + lblIncTrans.Visible = false; // Assign the data sources to the combo boxes ppCmbxChangeBarType.DataSource = EnumDetail.Details(); @@ -279,11 +231,6 @@ namespace VEPROMS ppCmbxChgBarTxtType.ValueMember = "EValue"; ppCmbxChgBarTxtType.SelectedValue = -1; - //ppCmbxPagination.DataSource = EnumDetail.Details(); - //ppCmbxPagination.DisplayMember = "Name"; - //ppCmbxPagination.ValueMember = "EValue"; - //ppCmbxPagination.SelectedValue = -1; - ppCmbxWatermark.DataSource = EnumDetail.Details(); ppCmbxWatermark.DisplayMember = "Name"; ppCmbxWatermark.ValueMember = "EValue"; @@ -300,7 +247,7 @@ namespace VEPROMS // allow setting of the default graphics file extension. No other folder level allows this. ppCmbxGrphFileExt.Visible = false; ppLblGrphFileExtDefault.Visible = false; - this.lblGrphFileExt.Visible = false; + lblGrphFileExt.Visible = false; // HIDE the text box that allows the user to change the Procedure Panel's heading (title) on the panel bar ppRTxtHeading.Visible = false; @@ -316,26 +263,19 @@ namespace VEPROMS { folderConfigBindingSource.CancelEdit(); DialogResult = DialogResult.Cancel; - this.Close(); + Close(); } - private void ppBtnCancel_MouseEnter(object sender, EventArgs e) - { - _ValidateTextBox = false; - } + private void ppBtnCancel_MouseEnter(object sender, EventArgs e) => _ValidateTextBox = false; - private void ppBtnCancel_MouseLeave(object sender, EventArgs e) - { - _ValidateTextBox = true; - } + private void ppBtnCancel_MouseLeave(object sender, EventArgs e) => _ValidateTextBox = true; - private void ppBtnOK_Click(object sender, EventArgs e) + private void ppBtnOK_Click(object sender, EventArgs e) { if (btnRevisoinStageUndo.Enabled) btnRevisoinStageUndo.PerformClick(); if (btnAnnoTypeUndo.Enabled) btnAnnoTypeUndo.PerformClick(); - //if (btnAnnoTypeSave.Enabled) return; folderConfigBindingSource.EndEdit(); // Save Default settings for User @@ -352,7 +292,7 @@ namespace VEPROMS SaveApprStages(); SaveAnnotationTypes(); DialogResult = DialogResult.OK; - this.Close(); + Close(); } private void SaveApprStages() @@ -415,9 +355,11 @@ namespace VEPROMS { at.Name = found.Name; at.UserID = Volian.Base.Library.VlnSettings.UserID; - AnnotationTypeConfig newAtc = new AnnotationTypeConfig(); - newAtc.PrintableText_XLocation = found.PrntLoc; - at.Config = newAtc.ToString(); + AnnotationTypeConfig newAtc = new AnnotationTypeConfig + { + PrintableText_XLocation = found.PrntLoc + }; + at.Config = newAtc.ToString(); at.DTS = DateTime.Now; at.Save(); } @@ -436,27 +378,26 @@ namespace VEPROMS } foreach (LocalAnnotationTypeInfo lai in myLocalAnnotationTypeInfoList) { - AnnotationTypeConfig newAtc = new AnnotationTypeConfig(); - newAtc.PrintableText_XLocation = lai.PrntLoc; - using (AnnotationType at = AnnotationType.New(lai.Name, newAtc.ToString(), DateTime.Now, Volian.Base.Library.VlnSettings.UserID)) + AnnotationTypeConfig newAtc = new AnnotationTypeConfig + { + PrintableText_XLocation = lai.PrntLoc + }; + using (AnnotationType at = AnnotationType.New(lai.Name, newAtc.ToString(), DateTime.Now, Volian.Base.Library.VlnSettings.UserID)) at.Save(); } AnnotationTypeInfoList.Refresh(); } - #region General tab + #region General tab - /// - /// This is the General button used on the button interface design - /// - /// object - /// EventArgs - private void btnGeneral_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiGeneral, btnGeneral); - } + /// + /// This is the General button used on the button interface design + /// + /// object + /// EventArgs + private void btnGeneral_Click(object sender, EventArgs e) => ProcessButtonClick(tiGeneral, btnGeneral); - private void ppRTxtName_Leave(object sender, EventArgs e) + private void ppRTxtName_Leave(object sender, EventArgs e) { if (ppRTxtName.Text == null || ppRTxtName.Text == "") { @@ -469,31 +410,28 @@ namespace VEPROMS bool isunique = _FolderConfig.CheckUniqueName(ppRTxtName.Text); if (!isunique) { - MessageBox.Show(string.Format("The Name '{0}' that was entered is not a unique folder name", ppRTxtName.Text)); + MessageBox.Show($"The Name '{ppRTxtName.Text}' that was entered is not a unique folder name"); ppRTxtName.Text = _FolderConfig.Name; } } } - #endregion + #endregion - #region Referenced Objects tab + #region Referenced Objects tab - /// - /// This is the Referenced Objects button used on the button interface design - /// - /// object - /// EventArgs - private void btnRefObjs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiRefObj, btnRefObjs); - } + /// + /// This is the Referenced Objects button used on the button interface design + /// + /// object + /// EventArgs + private void btnRefObjs_Click(object sender, EventArgs e) => ProcessButtonClick(tiRefObj, btnRefObjs); - /// - /// Selection in Graphic File Extension combo box changed. - /// - /// object - /// EventArgs - private void ppCmbxGrphFileExt_SelectedValueChanged(object sender, EventArgs e) + /// + /// Selection in Graphic File Extension combo box changed. + /// + /// object + /// EventArgs + private void ppCmbxGrphFileExt_SelectedValueChanged(object sender, EventArgs e) { if (!_Initializing) ProcessCmbxSelectedValueChange(ppCmbxGrphFileExt, _DefaultROGraficFileExtension, ppBtnDefaultGrphFileExt, ppLblGrphFileExtDefault); @@ -512,94 +450,25 @@ namespace VEPROMS if (_DefaultROGraficFileExtension.Equals(_FolderConfig.Graphics_defaultext)) _FolderConfig.Graphics_defaultext = _DefaultROGraficFileExtension;// this will force a database update (write) ppCmbxGrphFileExt.SelectedIndex = -1; //reset to the default Graphic File Extension setting - //tcpRefObjs.Focus(); } - /// - /// TEMPORARY - TO PROVIDE DEMO FUNCTIONALITY - /// An RO Folder was selected, find the RO.FST file and populate the RO and Image database combo boxes - /// - /// object - /// EventArgs - private void ppTxbxRoFoldLoc_TextChanged(object sender, EventArgs e) - { - //TODO: - //string tpath = ppTxbxRoFoldLoc.Text + "\\RO.FST"; - //if (File.Exists(tpath)) - //{ - // build a list of available RO Accessory Page ID's - //ROFst rofst = ROFst.Get(_DocVersionConfig.MyDocVersion.DocVersionDocVersionROFsts[0].MyROFst.ROFstID);//new ROFst(tpath, null); - //ROFst.rodbi[] rodblist = rofst.GetRODatabaseList(); - //for (int i = 0; i < rodblist.Length; i++) - //{ - // string mitem = string.Format("{0} - {1}", rodblist[i].dbiTitle, rodblist[i].dbiAP); - // switch (rodblist[i].dbiType) - // { - // case 7: ppCmbxDefROPrefix.Items.Add(mitem); // setpoint - // break; - // case 8: ppCmbxDefImgPrefix.Items.Add(mitem); // graphic - // break; - // default: // user defined - // ppCmbxDefROPrefix.Items.Add(mitem); - // ppCmbxDefImgPrefix.Items.Add(mitem); - // break; - // } - //} - //} - } - #endregion + #endregion - #region Output Settings tab + #region Output Settings tab - /// - /// This is the Output Settings button used on the button interface design - /// - /// object - /// EventArgs - private void btnOutputSettings_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiOutputSettings, btnOutputSettings); - } + /// + /// This is the Output Settings button used on the button interface design + /// + /// object + /// EventArgs + private void btnOutputSettings_Click(object sender, EventArgs e) => ProcessButtonClick(tiOutputSettings, btnOutputSettings); - /// - /// Selection in Pagination combo box changed. - /// - /// object - /// EventArgs - //private void ppCmbxPagination_SelectedValueChanged(object sender, EventArgs e) - //{ - // if (!_Initializing || !_IsDefaultSettingNode) - // { - // PrintPagination pgtn = (PrintPagination)Enum.Parse(typeof(PrintPagination), _DefaultPagination); - // ProcessCmbxSelectionEnumChanged(ppCmbxPagination, pgtn, ppBtnDefPagination, ppLblPaginationDefault); - // } - //} - - /// - /// Reset to the parent setting. - /// Find the parent setting and assign it to _FolderConfig.Print_Pagination. - /// This will force the database to be updated. - /// - /// - /// - //private void ppBtnDefPagination_Click(object sender, EventArgs e) - //{ - // Console.WriteLine("ppBtnDefPagination_Click"); - // // Get the parent setting - // PrintPagination pgtn = (PrintPagination)Enum.Parse(typeof(PrintPagination), _DefaultPagination); - // // Compare parent setting with current setting - // if (pgtn != _FolderConfig.Print_Pagination) - // _FolderConfig.Print_Pagination = pgtn; // this will force a database update (write) - // ppCmbxPagination.SelectedIndex = -1; //reset to the default Pagination setting - // //tcpOutputSettings.Focus(); - //} - - /// - /// Selection in Watermark combo box changed. - /// - /// object - /// EventArgs - private void ppCmbxWatermark_SelectedValueChanged(object sender, EventArgs e) + /// + /// Selection in Watermark combo box changed. + /// + /// object + /// EventArgs + private void ppCmbxWatermark_SelectedValueChanged(object sender, EventArgs e) { if (!_Initializing) { @@ -623,76 +492,46 @@ namespace VEPROMS if (wtr != _FolderConfig.Print_Watermark) _FolderConfig.Print_Watermark = wtr; // this will force a database update (write) ppCmbxWatermark.SelectedIndex = -1; //reset to the default Watermark setting - //tcpOutputSettings.Focus(); } + #endregion - #endregion + #region Startup Message tab - #region Startup Message tab + /// + /// This is the Startup Message button used on the button interface design + /// + /// object + /// EventArgs + private void btnStMsg_Click(object sender, EventArgs e) => ProcessButtonClick(tiStMsg, btnStMsg); - /// - /// This is the Startup Message button used on the button interface design - /// - /// object - /// EventArgs - private void btnStMsg_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiStMsg, btnStMsg); - } + #endregion - #endregion + #region Format Settings tab - #region Format Settings tab - - /// - /// This is the Format Settings button used on the button interface design - /// - /// object - /// EventArgs - private void btnFormatSettings_Click(object sender, EventArgs e) + /// + /// This is the Format Settings button used on the button interface design + /// + /// object + /// EventArgs + private void btnFormatSettings_Click(object sender, EventArgs e) { ProcessButtonClick(tiFmtSettings, btnFormatSettings); // added for code change C2017-004 - select default format in dropdown list if (_InitialIndex < -1) _InitialIndex = ppCmbxFormat.SelectedIndex; // save the current format selection (happens here when current section is set to the default format) } - // commented out as part of code change C2017-004. this also makes it consistent with section properties - ///// - ///// Selection in Format combo box changed. - ///// - ///// object - ///// EventArgs - //private void ppCmbxFormat_SelectedValueChanged(object sender, EventArgs e) - //{ - // if (!_Initializing) - // ProcessCmbxSelectedValueChange(ppCmbxFormat, _DefaultFormatName, ppBtnDefaultFmt, ppLblFormatDefault); - //} + private void ppBtnDefaultFmt_Click(object sender, EventArgs e) => ppCmbxFormat.SelectedIndex = -1; //reset to the default Format setting - private void ppBtnDefaultFmt_Click(object sender, EventArgs e) + /// + /// Enable or disable the user specified change bar options base on the type + /// of change bar selected. + /// + private void setEnabledUserSpecifiedChgBarCombos(PrintChangeBar pcb) { - ppCmbxFormat.SelectedIndex = -1; //reset to the default Format setting - //tcpFmtSettings.Focus(); - } - - /// - /// Enable or disable the user specified change bar options base on the type - /// of change bar selected. - /// - private void setEnabledUserSpecifiedChgBarCombos(PrintChangeBar pcb) - { - //ppGpbxUserSpecCB.Enabled = - //ppCmbxChgBarPos.Enabled = - //ppCmbxChgBarTxtType.Enabled = - //ppBtnDefaultCbPos.Enabled = - //ppBtnDefCbTxtTyp.Enabled = (ppCmbxChangeBarType.SelectedValue != null && - //ppCmbxChangeBarType.SelectedValue.Equals(FolderConfig.PrintChangeBar.WithUserSpecified)) || - //(ppCmbxChangeBarType.SelectedValue == null && pcb.Equals(FolderConfig.PrintChangeBar.WithUserSpecified)); - ppGpbxUserSpecCB.Enabled = (ppCmbxChangeBarType.SelectedValue != null && ppCmbxChangeBarType.SelectedValue.Equals(PrintChangeBar.WithUserSpecified)) || (ppCmbxChangeBarType.SelectedValue == null && pcb.Equals(PrintChangeBar.WithUserSpecified)); - } /// @@ -722,12 +561,9 @@ namespace VEPROMS // Get the parent setting PrintChangeBar pcb = (PrintChangeBar)Enum.Parse(typeof(PrintChangeBar), _DefaultChgBarType); // Compare parent setting with current setting - //_Initializing = true; if (pcb != _FolderConfig.Print_ChangeBar) _FolderConfig.Print_ChangeBar = pcb; // this will force a database update (write) ppCmbxChangeBarType.SelectedIndex = -1; //reset combo box to the default Change Bar setting - //_Initializing = false; - //tcpFmtSettings.Focus(); } /// @@ -759,7 +595,6 @@ namespace VEPROMS if (cbl != _FolderConfig.Print_ChangeBarLoc) _FolderConfig.Print_ChangeBarLoc = cbl; // this will force a database update (write) ppCmbxChgBarPos.SelectedIndex = -1; //reset to the default Change Bar Position setting - //tcpFmtSettings.Focus(); } /// @@ -774,7 +609,6 @@ namespace VEPROMS PrintChangeBarText cbt = (PrintChangeBarText)Enum.Parse(typeof(PrintChangeBarText), _DefaultChgBarText); ProcessCmbxSelectionEnumChanged(ppCmbxChgBarTxtType, cbt, ppBtnDefCbTxtTyp, ppLblChgBarTxtTypeDefault); setEnabledUserSpecifiedChgBarText(); - //tcpFmtSettings.Focus(); } } @@ -793,7 +627,6 @@ namespace VEPROMS if (cbt != _FolderConfig.Print_ChangeBarText) _FolderConfig.Print_ChangeBarText = cbt; // this will force a database update (write) ppCmbxChgBarTxtType.SelectedIndex = -1; //reset to the default Change Bar Text Type setting - //tcpFmtSettings.Focus(); } /// @@ -802,13 +635,6 @@ namespace VEPROMS /// private void setEnabledUserSpecifiedChgBarText() { - //ppGpbxUserSpecTxt.Enabled = - //ppTxbxChangeBarUserMsgOne.Enabled = - //ppTxbxChgBarUserMsgTwo.Enabled = - //ppBtnDefCbTxt1.Enabled = - //ppBtnDefCbTxt2.Enabled = (ppCmbxChgBarTxtType.SelectedValue != null && - //ppCmbxChgBarTxtType.SelectedValue.Equals(FolderConfig.PrintChangeBarText.UserDef)); - // This string is used to check against our default setting to see if User Defined Changebar Text is active string decUserDef = PrintChangeBarText.UserDef.ToString(); @@ -824,8 +650,6 @@ namespace VEPROMS /// EventArgs private void ppTxbxChangeBarUserMsgOne_TextChanged(object sender, EventArgs e) { - //ppBtnDefCbTxt1.Visible = (!_FolderConfig.Name.Equals("VEPROMS")) && - // ((ppTxbxChangeBarUserMsgOne.Text != null) && !ppTxbxChangeBarUserMsgOne.Text.Equals(_DefaultChgBarUsrMsg1)); ppBtnDefCbTxt1.Visible = ((ppTxbxChangeBarUserMsgOne.Text != null) && !ppTxbxChangeBarUserMsgOne.Text.Equals(_DefaultChgBarUsrMsg1)); ppLblChgBarUserMsgOneDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefCbTxt1.Visible; } @@ -837,188 +661,27 @@ namespace VEPROMS /// EventArgs private void ppTxbxChangeBarUserMsgTwo_TextChanged(object sender, EventArgs e) { - //ppBtnDefCbTxt2.Visible = (!_FolderConfig.Name.Equals("VEPROMS")) && - // ((ppTxbxChgBarUserMsgTwo.Text != null) && !ppTxbxChgBarUserMsgTwo.Text.Equals(_DefaultChgBarUsrMsg2)); ppBtnDefCbTxt2.Visible = ((ppTxbxChgBarUserMsgTwo.Text != null) && !ppTxbxChgBarUserMsgTwo.Text.Equals(_DefaultChgBarUsrMsg2)); ppLblChgBarUserMsgTwoDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefCbTxt2.Visible; } - #endregion + #endregion - #region Editor Settings tab + #region Editor Settings tab - /// - /// This is the Editor Settings button used on the button interface design - /// - /// object - /// EventArgs - private void btnEdSettings_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiEditSettings, btnEdSettings); - } + /// + /// This is the Editor Settings button used on the button interface design + /// + /// object + /// EventArgs + private void btnEdSettings_Click(object sender, EventArgs e) => ProcessButtonClick(tiEditSettings, btnEdSettings); - #region Editor Color Property Page Settings - /** The property page for these color settings is not visible for now. - * - /// - /// Set the text and background colors for the sample text for the Step Editor Text Colors - /// on the Editor Settings property page - /// - private void SetupSampleTextBoxes() - { - ppPanelViewSample.BackColor = cGetColor(_ViewBckgndColor); - ppLblViewRO.ForeColor = cGetColor(_ROcolor); - ppLblViewTrans.ForeColor = cGetColor(_TransColor); - ppPanelEditSample.BackColor = cGetColor(_EditBckgndColor); - ppLblEditRO.ForeColor = cGetColor(_ROcolor); - ppLblEditTrans.ForeColor = cGetColor(_TransColor); - } - - /// - /// Selection in View Mode Background Color changed. - /// - /// object - /// EventArgs - private void ppColorPickerViewModebckgnd_SelectedColorChanged(object sender, EventArgs e) - { - _ViewBckgndColor = strMakeColorName(ppColorPickerViewModebckgnd.SelectedColor); - SetupSampleTextBoxes(); - } - - /// - /// Selection in Edit Mode Background Color changed. - /// - /// object - /// EventArgs - private void ppColorPickerEditModeBckGnd_SelectedColorChanged(object sender, EventArgs e) - { - _EditBckgndColor = strMakeColorName(ppColorPickerEditModeBckGnd.SelectedColor); - _FolderConfig.Color_editbackground = _EditBckgndColor; - SetupSampleTextBoxes(); - } - - /// - /// Selection in Transition Color changed. - /// - /// object - /// EventArgs - private void ppColorPickerTransition_SelectedColorChanged(object sender, EventArgs e) - { - _TransColor = strMakeColorName(ppColorPickerTransition.SelectedColor); - SetupSampleTextBoxes(); - } - - /// - /// Selection in RO Color changed. - /// - /// object - /// EventArgs - private void ppColorPickerRO_SelectedColorChanged(object sender, EventArgs e) - { - _ROcolor = strMakeColorName(ppColorPickerRO.SelectedColor); - SetupSampleTextBoxes(); - } - - /// - /// Preview the current color under mouse pointer - /// For View Mode Background - /// - /// object - /// ColorPreviewEventArgs - private void ppColorPickerViewModebckgnd_ColorPreview(object sender, DevComponents.DotNetBar.ColorPreviewEventArgs e) - { - ppPanelViewSample.BackColor = e.Color; - } - - /// - /// Finalize the current color under mouse pointer - /// For View Mode Background - /// - /// object - /// EventArgs - private void ppColorPickerViewModebckgnd_PopupFinalized(object sender, EventArgs e) - { - ppPanelViewSample.BackColor = cGetColor(_ViewBckgndColor); - } - - /// - /// Preview the current color under mouse pointer - /// For Edit Mode Background - /// - /// object - /// ColorPreviewEventArgs - private void ppColorPickerEditModeBckGnd_ColorPreview(object sender, DevComponents.DotNetBar.ColorPreviewEventArgs e) - { - ppPanelEditSample.BackColor = e.Color; - } - - /// - /// Finalize the current color under mouse pointer - /// For Edit Mode Background - /// - /// object - /// EventArgs - private void ppColorPickerEditModeBckGnd_PopupFinalized(object sender, EventArgs e) - { - ppPanelEditSample.BackColor = cGetColor(_EditBckgndColor); - } - - /// - /// Preview the current color under mouse pointer - /// For Transition - /// - /// object - /// ColorPreviewEventArgs - private void ppColorPickerTransition_ColorPreview(object sender, DevComponents.DotNetBar.ColorPreviewEventArgs e) - { - ppLblViewTrans.ForeColor = e.Color; - ppLblEditTrans.ForeColor = e.Color; - } - - /// - /// Finalize the current color under mouse pointer - /// For Transition - /// - /// object - /// EventArgs - private void ppColorPickerTransition_PopupFinalized(object sender, EventArgs e) - { - ppLblViewTrans.ForeColor = cGetColor(_TransColor); - ppLblEditTrans.ForeColor = cGetColor(_TransColor); - } - - /// - /// Preview the current color under mouse pointer - /// For RO - /// - /// object - /// ColorPreviewEventArgs - private void ppColorPickerRO_ColorPreview(object sender, DevComponents.DotNetBar.ColorPreviewEventArgs e) - { - ppLblViewRO.ForeColor = e.Color; - ppLblEditRO.ForeColor = e.Color; - } - - /// - /// Finalize the current color under mouse pointer - /// For RO - /// - /// object - /// EventArgs - private void ppColorPickerRO_PopupFinalized(object sender, EventArgs e) - { - ppLblViewRO.ForeColor = cGetColor(_ROcolor); - ppLblEditRO.ForeColor = cGetColor(_ROcolor); - } -**/ - #endregion - - /// - /// Selection in Step Editor Columns combo box changed. - /// - /// object - /// EventArgs - private void ppCmbxStpEditorCols_SelectedValueChanged(object sender, EventArgs e) + /// + /// Selection in Step Editor Columns combo box changed. + /// + /// object + /// EventArgs + private void ppCmbxStpEditorCols_SelectedValueChanged(object sender, EventArgs e) { if (!_Initializing) { @@ -1042,59 +705,11 @@ namespace VEPROMS if (fcl != _FolderConfig.Format_Columns) _FolderConfig.Format_Columns = fcl; // this will force a database update (write) ppCmbxStpEditorCols.SelectedIndex = -1; //reset to the default Step Editor Columns setting - //tcpEdSettings.Focus(); } - #endregion + #endregion - #region Generic functions used on this property page - - /// - /// Convert the given System.Drawing.Color to a string containing either the color's name or the Argb. - /// - /// System.Drawing.Color - /// - private string strMakeColorName(Color c) - { - string rtnstring = ""; - if (c.IsNamedColor) - rtnstring = c.Name; - else - rtnstring = string.Format("[A={0},R={1},G={2},B={3}]", c.A, c.R, c.G, c.B); - return rtnstring; - } - - /// - /// Get a System.Drawing.Color from an Argb or color name - /// - /// Color Name or "[(alpha,)red,green,blue]" - /// - // a copy of this function was put in frmVEPROMS.CS - private static Color cGetColor(string strColor) - { - Color rtnColor; // = new Color(); - if (strColor == null || strColor.Equals("")) - rtnColor = Color.White; - else - { - if (strColor[0] == '[') - { - string[] parts = strColor.Substring(1, strColor.Length - 2).Split(",".ToCharArray()); - int parts_cnt = 0; - foreach (string s in parts) - { - parts[parts_cnt] = parts[parts_cnt].TrimStart(' '); // remove preceeding blanks - parts_cnt++; - } - if (parts_cnt == 3) - rtnColor = Color.FromArgb(Int32.Parse(parts[0]), Int32.Parse(parts[1]), Int32.Parse(parts[2])); - else - rtnColor = Color.FromArgb(Int32.Parse(parts[0].Substring(2)), Int32.Parse(parts[1].Substring(2)), Int32.Parse(parts[2].Substring(2)), Int32.Parse(parts[3].Substring(2))); - } - else rtnColor = Color.FromName(strColor); - } - return rtnColor; - } + #region Generic functions used on this property page /// /// Set the watermark and default label @@ -1125,7 +740,6 @@ namespace VEPROMS ppLblStpEditorColsDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefEdCols.Visible; ppLblGrphFileExtDefault.Visible = (ppCbShwDefSettings.Checked || _IsVepromsNode) && ppBtnDefaultGrphFileExt.Visible; ppLblWatermarkDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefWatermark.Visible; - //ppLblPaginationDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefPagination.Visible; ppLblChgBarTxtTypeDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefCbTxtTyp.Visible; ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; ppLblChangeBarTypeDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultChgBar.Visible; @@ -1169,7 +783,6 @@ namespace VEPROMS cmbx.SelectedIndex = -1; // This will hide the Default button _Initializing = false; } - //button.Visible = ((!_FolderConfig.Name.Equals("VEPROMS")) && (cmbx.SelectedValue != null)); button.Visible = (!_IsVepromsNode && (cmbx.SelectedValue != null)&&(cmbx.SelectedIndex >= 0)); deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; } @@ -1214,9 +827,8 @@ namespace VEPROMS private void tabpage_Enter(object sender, EventArgs e) { // Show or hide the labels containing the default values - //if (!_Initializing) - defaultSettingsVisiblity(); - } + defaultSettingsVisiblity(); + } #endregion private void ppBtnDefCbTxt1_Click(object sender, EventArgs e) @@ -1225,12 +837,9 @@ namespace VEPROMS // Reset with the default and hide the default button and label if (_DefaultChgBarUsrMsg1 != _FolderConfig.Print_UserCBMess1) { - //_Initializing = true; _FolderConfig.Print_UserCBMess1 = _DefaultChgBarUsrMsg1; // this will force a database update (write) ppLblChgBarUserMsgOneDefault.Visible = false; ppBtnDefCbTxt1.Visible = false; - //tcpFmtSettings.Focus(); - //_Initializing = false; } } @@ -1243,39 +852,25 @@ namespace VEPROMS _FolderConfig.Print_UserCBMess2 = _DefaultChgBarUsrMsg2; // this will force a database update (write) ppLblChgBarUserMsgTwoDefault.Visible = false; ppBtnDefCbTxt2.Visible = false; - //tcpFmtSettings.Focus(); } } - private void frmFolderProperties_Shown(object sender, EventArgs e) - { - ppRTxtName.Focus(); - } + private void frmFolderProperties_Shown(object sender, EventArgs e) => ppRTxtName.Focus(); - private void btnAnnoTypes_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiAnnoTypes, btnAnnoTypes); - } + private void btnAnnoTypes_Click(object sender, EventArgs e) => ProcessButtonClick(tiAnnoTypes, btnAnnoTypes); - private void btnApprvStages_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiRevisionStages, btnRevisionStages); - } + private void btnApprvStages_Click(object sender, EventArgs e) => ProcessButtonClick(tiRevisionStages, btnRevisionStages); - #region Annotation Types - private void lbAnnotationTypes_SelectedIndexChanged(object sender, System.EventArgs e) + #region Annotation Types + private void lbAnnotationTypes_SelectedIndexChanged(object sender, System.EventArgs e) { if (btnAnnoTypeUndo.Enabled) { btnAnnoTypeUndo.Enabled = false; btnAnnoTypeApply.Enabled = false; - //DialogResult dr = MessageBox.Show("The Annotation Description was changed. \n\nSave your Changes?", "Annotation Desctiption", MessageBoxButtons.YesNo); - //if (dr == DialogResult.Yes) - //{ - myLocalAnnotationTypeInfoList[_LastAnnotationTypeInfoIndex].Name = tbxAnnotationDescription.Text; - myLocalAnnotationTypeInfoList[_LastAnnotationTypeInfoIndex].PrntLoc = int.Parse(txbPrntLoc.Text == "" ? "0" : txbPrntLoc.Text); - RefreshAnnotationTypeList(); - //} + myLocalAnnotationTypeInfoList[_LastAnnotationTypeInfoIndex].Name = tbxAnnotationDescription.Text; + myLocalAnnotationTypeInfoList[_LastAnnotationTypeInfoIndex].PrntLoc = int.Parse(txbPrntLoc.Text == "" ? "0" : txbPrntLoc.Text); + RefreshAnnotationTypeList(); } LoadLocalAnnotationTypeInfo(); } @@ -1287,22 +882,21 @@ namespace VEPROMS btnAnnoTypeApply.Enabled = false; _LastAnnotationTypeInfoIndex = lbAnnotationTypes.SelectedIndex; - LocalAnnotationTypeInfo ai = lbAnnotationTypes.SelectedValue as LocalAnnotationTypeInfo; - if (ai == null) - { - tbxAnnotationDescription.Text = ""; - tbxAnnotationDescription.Enabled = false; - btnAnnoTypeUndo.Enabled = false; - btnAnnoTypeApply.Enabled = false; - btnAnnoTypeNew.Enabled = true; - btnAnnoTypeRemove.Enabled = false; - txbxRemoveMsg.Visible = false; - lblAnnoTypeCntMessage.Visible = false; - txbPrntLoc.Visible = false; - lblPrintTxt.Visible = false; - return; - } - tbxAnnotationDescription.Enabled = true; + if (!(lbAnnotationTypes.SelectedValue is LocalAnnotationTypeInfo ai)) + { + tbxAnnotationDescription.Text = ""; + tbxAnnotationDescription.Enabled = false; + btnAnnoTypeUndo.Enabled = false; + btnAnnoTypeApply.Enabled = false; + btnAnnoTypeNew.Enabled = true; + btnAnnoTypeRemove.Enabled = false; + txbxRemoveMsg.Visible = false; + lblAnnoTypeCntMessage.Visible = false; + txbPrntLoc.Visible = false; + lblPrintTxt.Visible = false; + return; + } + tbxAnnotationDescription.Enabled = true; tbxAnnotationDescription.Text = ai.Name; btnAnnoTypeUndo.Enabled = false; btnAnnoTypeApply.Enabled = false; @@ -1317,7 +911,7 @@ namespace VEPROMS } else { - string countMsg = string.Format("{0} is used in {1} places", ai.Name, ai.AnnotationTypeAnnotationCount); + string countMsg = $"{ai.Name} is used in {ai.AnnotationTypeAnnotationCount} places"; btnAnnoTypeRemove.Enabled = false; lblAnnoTypeCntMessage.Text = countMsg; txbxRemoveMsg.Visible = true; @@ -1365,7 +959,6 @@ namespace VEPROMS LocalAnnotationTypeInfo lati = new LocalAnnotationTypeInfo("New Annotation Type"); lati.Name = string.Format("{0} {1}", lati.Name, lati.TypeID); myLocalAnnotationTypeInfoList.Add(lati); - //myLocalAnnotationTypeInfoList.Add(new LocalAnnotationTypeInfo("New Annotation Type")); btnAnnoTypeUndo.Enabled = false; btnAnnoTypeApply.Enabled = false; RefreshAnnotationTypeList(); @@ -1380,12 +973,6 @@ namespace VEPROMS txbPrntLoc.Undo(); btnAnnoTypeUndo.Enabled = false; btnAnnoTypeApply.Enabled = false; - //int saveIdx = lbAnnotationTypes.SelectedIndex; - //LocalAnnotationTypeInfo ai = lbAnnotationTypes.SelectedValue as LocalAnnotationTypeInfo; - //btnAnnoTypeSave.Enabled = false; - //ai.Name = tbxAnnotationDescription.Text; - //RefreshAnnotationTypeList(); - //lbAnnotationTypes.SelectedIndex = saveIdx; } private void btnAnnoTypeRemove_Click(object sender, EventArgs e) @@ -1415,8 +1002,8 @@ namespace VEPROMS { int newloci = int.Parse(newloc); } - catch (Exception ex) - { + catch (Exception) + { MessageBox.Show("Invalid Print Location, must be an integer.", "Print Text Location"); e.Cancel = true; } @@ -1445,20 +1032,14 @@ namespace VEPROMS } } - private void btnAnnoTypeRemove_MouseEnter(object sender, EventArgs e) - { - _ValidateTextBox = false; - } + private void btnAnnoTypeRemove_MouseEnter(object sender, EventArgs e) => _ValidateTextBox = false; - private void btnAnnoTypeRemove_MouseLeave(object sender, EventArgs e) - { - _ValidateTextBox = true; - } + private void btnAnnoTypeRemove_MouseLeave(object sender, EventArgs e) => _ValidateTextBox = true; - #endregion - #region Revision Stages + #endregion + #region Revision Stages - private void tbRevisionStage_TextChanged(object sender, EventArgs e) + private void tbRevisionStage_TextChanged(object sender, EventArgs e) { btnRevisoinStageUndo.Enabled = true; btnRevisionStageApply.Enabled = true; @@ -1468,8 +1049,7 @@ namespace VEPROMS private void btnRevisionStageNew_Click(object sender, EventArgs e) { LocalStageInfo lsi = new LocalStageInfo("New Stage", 0); - lsi.Name = string.Format("{0} {1}", lsi.Name, lsi.ID); - //myLocalStageInfoList.Add(new LocalStageInfo("New Stage", 0)); + lsi.Name = $"{lsi.Name} {lsi.ID}"; myLocalStageInfoList.Add(lsi); btnRevisoinStageUndo.Enabled = false; btnRevisionStageApply.Enabled = false; @@ -1512,13 +1092,6 @@ namespace VEPROMS LocalStageInfo si = lbRevisionStages.SelectedValue as LocalStageInfo; rbApprovalStage.Checked = (si.IsApproved > 0); rbWorkflowStage.Checked = (si.IsApproved == 0); - //int savIdx = lbRevisionStages.SelectedIndex; - //LocalStageInfo si = lbRevisionStages.SelectedValue as LocalStageInfo; - //si.Name = tbRevisionStage.Text; - //si.IsApproved = rbRevisionStage.Checked ? 1 : 0; - //RefreshRevisionStagesList(); - //lbRevisionStages.SelectedIndex = savIdx; - } private void lbRevisionStages_SelectedIndexChanged(object sender, EventArgs e) @@ -1527,13 +1100,9 @@ namespace VEPROMS { btnRevisoinStageUndo.Enabled = false; btnRevisionStageApply.Enabled = false; - //DialogResult dr = MessageBox.Show("The Approval Stage Description was changed. \n\nSave your Changes?", "Approval Stage Desctiption", MessageBoxButtons.YesNo); - //if (dr == DialogResult.Yes) - //{ - myLocalStageInfoList[_LastStageInfoIndex].Name = tbRevisionStage.Text; - myLocalStageInfoList[_LastStageInfoIndex].IsApproved = rbApprovalStage.Checked ? 1 : 0; - RefreshRevisionStagesList(); - //} + myLocalStageInfoList[_LastStageInfoIndex].Name = tbRevisionStage.Text; + myLocalStageInfoList[_LastStageInfoIndex].IsApproved = rbApprovalStage.Checked ? 1 : 0; + RefreshRevisionStagesList(); } LoadLocalStageInfo(); } @@ -1543,18 +1112,17 @@ namespace VEPROMS btnRevisoinStageUndo.Enabled = false; btnRevisionStageApply.Enabled = false; _LastStageInfoIndex = lbRevisionStages.SelectedIndex; - LocalStageInfo si = lbRevisionStages.SelectedValue as LocalStageInfo; - if (si == null) - { - tbRevisionStage.Text = ""; - tbRevisionStage.Enabled = false; - btnRevisoinStageUndo.Enabled = false; - btnRevisionStageApply.Enabled = false; - btnRevisionStageNew.Enabled = true; - btnRevisionStageRemove.Enabled = false; - return; - } - tbRevisionStage.Enabled = true; + if (!(lbRevisionStages.SelectedValue is LocalStageInfo si)) + { + tbRevisionStage.Text = ""; + tbRevisionStage.Enabled = false; + btnRevisoinStageUndo.Enabled = false; + btnRevisionStageApply.Enabled = false; + btnRevisionStageNew.Enabled = true; + btnRevisionStageRemove.Enabled = false; + return; + } + tbRevisionStage.Enabled = true; tbRevisionStage.Text = si.Name; if (si.IsApproved > 0) rbApprovalStage.Checked = true; @@ -1611,45 +1179,25 @@ namespace VEPROMS } } - private void btnRevisionStageRemove_MouseEnter(object sender, EventArgs e) - { - _ValidateTextBox = false; - } + private void btnRevisionStageRemove_MouseEnter(object sender, EventArgs e) => _ValidateTextBox = false; - private void btnRevisionStageRemove_MouseLeave(object sender, EventArgs e) - { - _ValidateTextBox = true; - } + private void btnRevisionStageRemove_MouseLeave(object sender, EventArgs e) => _ValidateTextBox = true; - private void rbReviseStage_MouseEnter(object sender, EventArgs e) - { - _ValidateTextBox = false; - } + private void rbReviseStage_MouseEnter(object sender, EventArgs e) => _ValidateTextBox = false; - private void rbReviseStage_MouseLeave(object sender, EventArgs e) - { - _ValidateTextBox = true; - } + private void rbReviseStage_MouseLeave(object sender, EventArgs e) => _ValidateTextBox = true; - private void rbApproveStage_MouseEnter(object sender, EventArgs e) - { - _ValidateTextBox = false; - } + private void rbApproveStage_MouseEnter(object sender, EventArgs e) => _ValidateTextBox = false; - private void rbApproveStage_MouseLeave(object sender, EventArgs e) - { - _ValidateTextBox = true; - } - #endregion + private void rbApproveStage_MouseLeave(object sender, EventArgs e) => _ValidateTextBox = true; + #endregion - private void btnRevisionStageApply_Click(object sender, EventArgs e) + private void btnRevisionStageApply_Click(object sender, EventArgs e) { //add code to apply changes btnRevisoinStageUndo.Enabled = false; btnRevisionStageApply.Enabled = false; LocalStageInfo si = lbRevisionStages.SelectedValue as LocalStageInfo; - //rbApprovalStage.Checked = (si.IsApproved > 0); - //rbWorkflowStage.Checked = (si.IsApproved == 0); si.Name = tbRevisionStage.Text; si.IsApproved = rbApprovalStage.Checked ? 1 : 0; RefreshRevisionStagesList(); @@ -1712,36 +1260,16 @@ namespace VEPROMS public partial class LocalStageInfo { private static int _UniqueID = 0; - protected static int UniqueID - { get { return --_UniqueID; } } - private int _MyUniqueID = UniqueID; - public int MyUniqueID // Absolutely Unique ID - Editable - { get { return _MyUniqueID; } } - private int _ID; - public int ID - { - get { return _ID; } - set { _ID = value; } - } - private string _Name; - public string Name - { - get { return _Name; } - set { _Name = value; } - } - private int _IsApproved; - public int IsApproved - { - get { return _IsApproved; } - set { _IsApproved = value; } - } - private int _StageVersionCount; - public int StageVersionCount - { - get { return _StageVersionCount; } - set { _StageVersionCount = value; } - } - public LocalStageInfo(string name, int isApproved) + protected static int UniqueID => --_UniqueID; + private readonly int _MyUniqueID = UniqueID; + // Absolutely Unique ID - Editable + public int MyUniqueID => _MyUniqueID; + + public int ID { get; set; } + public string Name { get; set; } + public int IsApproved { get; set; } + public int StageVersionCount { get; set; } + public LocalStageInfo(string name, int isApproved) { ID = MyUniqueID; Name = name; @@ -1755,11 +1283,8 @@ namespace VEPROMS IsApproved = si.IsApproved; StageVersionCount = si.StageVersionCount; } - public override string ToString() - { - return string.Format("{0} {1}", ID, Name); - } - } + public override string ToString() => $"{ID} {Name}"; + } public partial class LocalStageInfoList : List { public LocalStageInfoList(StageInfoList sil) @@ -1774,34 +1299,15 @@ namespace VEPROMS private static int _UniqueID = 0; protected static int UniqueID { get { return --_UniqueID; } } - private int _MyUniqueID = UniqueID; - public int MyUniqueID // Absolutely Unique ID - Editable - { get { return _MyUniqueID; } } - private int _TypeID; - public int TypeID - { - get { return _TypeID; } - set { _TypeID = value; } - } - private string _Name; - public string Name - { - get { return _Name; } - set { _Name = value; } - } - private int _PrntLoc; - public int PrntLoc - { - get {return _PrntLoc;} - set {_PrntLoc = value; } - } - private int _AnnotationTypeAnnotationCount; - public int AnnotationTypeAnnotationCount - { - get { return _AnnotationTypeAnnotationCount; } - set { _AnnotationTypeAnnotationCount = value; } - } - public LocalAnnotationTypeInfo(string name) + private readonly int _MyUniqueID = UniqueID; + // Absolutely Unique ID - Editable + public int MyUniqueID => _MyUniqueID; + + public int TypeID { get; set; } + public string Name { get; set; } + public int PrntLoc { get; set; } + public int AnnotationTypeAnnotationCount { get; set; } + public LocalAnnotationTypeInfo(string name) { TypeID = MyUniqueID; Name = name; @@ -1819,11 +1325,8 @@ namespace VEPROMS } AnnotationTypeAnnotationCount = ai.AnnotationTypeAnnotationCount; } - public override string ToString() - { - return string.Format("{0} {1}", TypeID, Name); - } - } + public override string ToString() => $"{TypeID} {Name}"; + } public partial class LocalAnnotationTypeInfoList : List { public LocalAnnotationTypeInfoList(AnnotationTypeInfoList ail) diff --git a/PROMS/VEPROMS User Interface/frmGenTools.cs b/PROMS/VEPROMS User Interface/frmGenTools.cs index 4d0decc8..d5cff385 100644 --- a/PROMS/VEPROMS User Interface/frmGenTools.cs +++ b/PROMS/VEPROMS User Interface/frmGenTools.cs @@ -1,14 +1,9 @@ using System; using System.Collections.Generic; -using System.Drawing; -using System.Text; using System.Windows.Forms; using VEPROMS.CSLA.Library; -using System.IO; using Volian.Controls.Library; using DevComponents.DotNetBar; -using JR.Utils.GUI.Forms; -using System.Linq; using System.Data; using xls = Microsoft.Office.Interop.Excel; @@ -16,52 +11,42 @@ namespace VEPROMS { public partial class frmGenTools : Form { - private SessionInfo _MySessionInfo; - public SessionInfo MySessionInfo - { - get { return _MySessionInfo; } - set { _MySessionInfo = value; } - } + public SessionInfo MySessionInfo { get; set; } - public frmGenTools(SessionInfo sessionInfo, frmVEPROMS veProms) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping veProms for potential future use")] + public frmGenTools(SessionInfo sessionInfo, frmVEPROMS veProms) { InitializeComponent(); - _MySessionInfo = sessionInfo; + MySessionInfo = sessionInfo; // When opening General tools Check tab will be default. - this.sideNavItmCheck.Checked = true; + sideNavItmCheck.Checked = true; setupProgessSteps1(); // C2017-030 - new Tools user interface } - private void frmGenTools_Load(object sender, EventArgs e) - { - IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. - } - private bool IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. - private void frmGenTools_FormClosing(object sender, EventArgs e) - { - IsClosing = true;//B2017-221 Allow the batch dialog to close when waiting to process. - } + private void frmGenTools_Load(object sender, EventArgs e) => IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. + private bool IsClosing = false;//B2017-221 Allow the batch dialog to close when waiting to process. + private void frmGenTools_FormClosing(object sender, EventArgs e) => IsClosing = true;//B2017-221 Allow the batch dialog to close when waiting to process. - // C2017-030 - new Tools user interface - // tool renamed to Identify Orphan Items - private void IdentifyDisconnectedItems() + // C2017-030 - new Tools user interface + // tool renamed to Identify Orphan Items + private void IdentifyDisconnectedItems() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Identifing Orphan Items"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); int rowCount = ESP_IdentifyDisconnectedItems.Execute("vesp_GetDisconnectedItemsCount"); - txtProcess.AppendText(string.Format("Orphan Items Count: {0}", rowCount)); + txtProcess.AppendText($"Orphan Items Count: {rowCount}"); txtProcess.AppendText(Environment.NewLine); if (rowCount > 0) { - txtResults.AppendText(string.Format("The database contains {0} Orphan items.", rowCount)); + txtResults.AppendText($"The database contains {rowCount} Orphan items."); txtResults.AppendText(Environment.NewLine); txtResults.AppendText("These can be removed via the Remove Orphan Data Records in the Repair tools"); txtResults.AppendText(Environment.NewLine); @@ -74,33 +59,33 @@ namespace VEPROMS txtResults.AppendText(Environment.NewLine); } DateTime pEnd = DateTime.Now; - txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Tools user interface // is one of two tools run from Check Obsolete RO Data private void IdentifyUnusedRoFstsAndFigures() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Identifing Unused RoFsts and Figures"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); int rowCountRoFst = ESP_GetUnusedRoFsts.Execute("vesp_GetUnusedRoFstsCount"); int rowCountFigures = ESP_GetUnusedFigures.Execute("vesp_GetUnusedFiguresCount"); - txtProcess.AppendText(string.Format("Unused RoFsts Count: {0}, Unused Figures Count: {1}", rowCountRoFst, rowCountFigures)); + txtProcess.AppendText($"Unused RoFsts Count: {rowCountRoFst}, Unused Figures Count: {rowCountFigures}"); txtProcess.AppendText(Environment.NewLine); if (rowCountRoFst > 0 || rowCountFigures > 0) { - txtResults.AppendText(string.Format("The database contains {0} unused RoFsts.", rowCountRoFst)); + txtResults.AppendText($"The database contains {rowCountRoFst} unused RoFsts."); txtResults.AppendText(Environment.NewLine); - txtResults.AppendText(string.Format("The database contains {0} unused Figures items.", rowCountFigures)); + txtResults.AppendText($"The database contains {rowCountFigures} unused Figures items."); txtResults.AppendText(Environment.NewLine); txtResults.AppendText(Environment.NewLine); } @@ -112,31 +97,31 @@ namespace VEPROMS } DateTime pEnd = DateTime.Now; - txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Tools user interface // is one of two tools run from Check Obsolete RO Data private void IdentifyROAssociations() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Identifing Unused RO Associations"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); int rowCount = ESP_GetROAssoc.Execute("vesp_GetUnusedROAssociationsCount"); - txtProcess.AppendText(string.Format("Unused RO Associations Count: {0}", rowCount)); + txtProcess.AppendText($"Unused RO Associations Count: {rowCount}"); txtProcess.AppendText(Environment.NewLine); if (rowCount > 0) { - txtResults.AppendText(string.Format("The database contains {0} unused RO Associations.", rowCount)); + txtResults.AppendText($"The database contains {rowCount} unused RO Associations."); txtResults.AppendText(Environment.NewLine); txtResults.AppendText(Environment.NewLine); } @@ -147,26 +132,26 @@ namespace VEPROMS txtResults.AppendText(Environment.NewLine); } DateTime pEnd = DateTime.Now; - txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Tools user interface // tool was renamed to Hidden Data Locations (on Check list) private void IdentifyNonEditableItems() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Identifing Hidden Item Locations"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); List myItems = ESP_IdentifyNonEditableItems.Execute("vesp_GetNonEditableItems"); - txtProcess.AppendText(string.Format("Hidden Items Count: {0}", myItems.Count)); + txtProcess.AppendText($"Hidden Items Count: {myItems.Count}"); txtProcess.AppendText(Environment.NewLine); if (myItems.Count > 0) { @@ -190,52 +175,46 @@ namespace VEPROMS //clear the list since no longer using it myItems.Clear(); DateTime pEnd = DateTime.Now; - txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // C2017-030 - new Tools user interface // tool was renamed to Show Users private void GetDatabaseSessions() { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Show Users in PROMS"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); txtResults.Clear(); txtResults.AppendText(ESP_GetDatabaseSessions.Execute("vesp_GetDatabaseSessions")); DateTime pEnd = DateTime.Now; - txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; MessageBox.Show("Show Users Completed", "Show Users"); } - public List roFstInfo_ROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) - { - return VlnFlexGrid.ROTableUpdate(sender, args); - } + private void btnClear_Click(object sender, EventArgs e) => txtResults.Clear(); - private void btnClear_Click(object sender, EventArgs e) + private void btnSave_Click(object sender, EventArgs e) { - txtResults.Clear(); - } - - private void btnSave_Click(object sender, EventArgs e) - { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.DefaultExt = "txt"; - sfd.AddExtension = true; - sfd.Filter = "Text Files (*.txt)|*.txt"; - sfd.FileName = string.Format("BatchRefreshResults_{0}", DateTime.Now.ToString("yyyyMMdd_HHmm")); - sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS"; - DialogResult dr = sfd.ShowDialog(); + SaveFileDialog sfd = new SaveFileDialog + { + DefaultExt = "txt", + AddExtension = true, + Filter = "Text Files (*.txt)|*.txt", + FileName = $"BatchRefreshResults_{DateTime.Now:yyyyMMdd_HHmm}", + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\VEPROMS" + }; + DialogResult dr = sfd.ShowDialog(); if (dr == DialogResult.OK) { @@ -257,13 +236,10 @@ namespace VEPROMS } } - private void chkLater_CheckedChanged(object sender, EventArgs e) - { - pnlLater.Enabled = chkLater.Checked; - } + private void chkLater_CheckedChanged(object sender, EventArgs e) => pnlLater.Enabled = chkLater.Checked; - // C2017-030 new Tools user interface - private void sideNavItmCheck_Click(object sender, EventArgs e) + // C2017-030 new Tools user interface + private void sideNavItmCheck_Click(object sender, EventArgs e) { GenToolType = E_GenToolType.Check; lblAdmToolProgressType.Text = "Checking:"; @@ -284,16 +260,13 @@ namespace VEPROMS setupProgessSteps1(); } - // C2017-030 new Tools user interface - private void sideNavItmExit_Click(object sender, EventArgs e) - { - this.Close(); - } + // C2017-030 new Tools user interface + private void sideNavItmExit_Click(object sender, EventArgs e) => Close(); - #region On/Off Swiches + #region On/Off Swiches - // C2017-030 new Tools user interface - private enum E_GenToolType : int + // C2017-030 new Tools user interface + private enum E_GenToolType : int { Check = 0, Users = 3, @@ -301,9 +274,9 @@ namespace VEPROMS }; private E_GenToolType GenToolType = 0; - DevComponents.DotNetBar.StepItem siOrphDatRecs = new DevComponents.DotNetBar.StepItem("siOrphDatRecs", "Orphan Data Records"); - DevComponents.DotNetBar.StepItem siHiddenDataLocs = new DevComponents.DotNetBar.StepItem("siHiddenDataLocs", "Hidden Data"); - DevComponents.DotNetBar.StepItem siObsoleteROData = new DevComponents.DotNetBar.StepItem("siObsoleteROData", "Obsolete RO Data"); + readonly DevComponents.DotNetBar.StepItem siOrphDatRecs = new DevComponents.DotNetBar.StepItem("siOrphDatRecs", "Orphan Data Records"); + readonly DevComponents.DotNetBar.StepItem siHiddenDataLocs = new DevComponents.DotNetBar.StepItem("siHiddenDataLocs", "Hidden Data"); + readonly DevComponents.DotNetBar.StepItem siObsoleteROData = new DevComponents.DotNetBar.StepItem("siObsoleteROData", "Obsolete RO Data"); // this will update/rebuild the progress bar in the bottom panel of Tools private void setupProgessSteps1() @@ -332,22 +305,16 @@ namespace VEPROMS } } - // used for all of the Switch buttons (ON/OFF buttons) - private void swCk_ValueChanged(object sender, EventArgs e) - { - setupProgessSteps1(); - } + // used for all of the Switch buttons (ON/OFF buttons) + private void swCk_ValueChanged(object sender, EventArgs e) => setupProgessSteps1(); - #endregion + #endregion - // C2017-030 New Tools user interface - // functions to handle the progress bar in the bottom panel of Tools - private void StepProgress(int prgStpIdx, int val) - { - ((DevComponents.DotNetBar.StepItem)progressSteps1.Items[prgStpIdx]).Value = val; - } + // C2017-030 New Tools user interface + // functions to handle the progress bar in the bottom panel of Tools + private void StepProgress(int prgStpIdx, int val) => ((DevComponents.DotNetBar.StepItem)progressSteps1.Items[prgStpIdx]).Value = val; - private void ClearStepProgress() + private void ClearStepProgress() { for (int i = 0; i < progressSteps1.Items.Count; i++) { @@ -362,7 +329,7 @@ namespace VEPROMS { if (chkLater.Checked) { - long later = long.Parse(dtpDate.Value.ToString("yyyyMMdd") + dtpTime.Value.ToString("HHmm")); + long later = long.Parse($"{dtpDate.Value:yyyyMMdd}{dtpTime.Value:HHmm}"); long now = long.Parse(DateTime.Now.ToString("yyyyMMddHHmm")); while (now < later) @@ -435,10 +402,12 @@ namespace VEPROMS { if (string.IsNullOrEmpty(UACfilename)) { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.Filter = "Excel XLS (*.xlsx)|*.xlsx"; - sfd.FileName = "UACReport.xlsx"; - if (sfd.ShowDialog() == DialogResult.OK) + SaveFileDialog sfd = new SaveFileDialog + { + Filter = "Excel XLS (*.xlsx)|*.xlsx", + FileName = "UACReport.xlsx" + }; + if (sfd.ShowDialog() == DialogResult.OK) { UACfilename = sfd.FileName; } @@ -462,11 +431,11 @@ namespace VEPROMS //Get Datatable of results then loop through outputting into excel private void Generate_UAC_Report(string filename) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DateTime pStart = DateTime.Now; txtProcess.AppendText("Generate User Access Control Report in PROMS"); txtProcess.AppendText(Environment.NewLine); - txtProcess.AppendText(string.Format("Started: {0}", pStart.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText(Environment.NewLine); Application.DoEvents(); txtResults.Clear(); @@ -525,9 +494,9 @@ namespace VEPROMS } DateTime pEnd = DateTime.Now; - txtProcess.AppendText(string.Format("Completed: {0}", pEnd.ToString("MM/dd/yyyy @ HH:mm"))); + txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); Application.DoEvents(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; MessageBox.Show("Generate User Access Control Report Completed", "User Access Control Report"); } @@ -544,7 +513,7 @@ namespace VEPROMS catch (Exception ex) { obj = null; - MessageBox.Show("Exception Occurred while releasing object " + ex.ToString()); + MessageBox.Show($"Exception Occurred while releasing object {ex}"); } finally { @@ -552,18 +521,11 @@ namespace VEPROMS } } - //C2025-011 RO Update Tool Memory Enhancements - private void txtProcess_TextChanged(object sender, EventArgs e) - { - //clears the stack to help with memory - should never need to undo text changes to this. - txtProcess.ClearUndo(); - } - - private void txtResults_TextChanged(object sender, EventArgs e) - { - //clears the stack to help with memory - should never need to undo text changes to this. - txtResults.ClearUndo(); - } + //C2025-011 RO Update Tool Memory Enhancements + //clears the stack to help with memory - should never need to undo text changes to this. + private void txtProcess_TextChanged(object sender, EventArgs e) => txtProcess.ClearUndo(); + //clears the stack to help with memory - should never need to undo text changes to this. + private void txtResults_TextChanged(object sender, EventArgs e) => txtResults.ClearUndo(); } } diff --git a/PROMS/VEPROMS User Interface/frmManageUser.cs b/PROMS/VEPROMS User Interface/frmManageUser.cs index f9ac650e..6e5faba2 100644 --- a/PROMS/VEPROMS User Interface/frmManageUser.cs +++ b/PROMS/VEPROMS User Interface/frmManageUser.cs @@ -1,9 +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 VEPROMS.CSLA.Library; @@ -40,10 +36,10 @@ namespace VEPROMS tmp = $"{su.UserID} Information"; } - this.Text = tmp; + Text = tmp; } } - private string _Mode; + private readonly string _Mode; public frmManageUser(string mode) { InitializeComponent(); @@ -55,7 +51,7 @@ namespace VEPROMS _MyUser = (pgUser.SelectedObject as SimpleUser).MyUser; if (_MyUser.UserID.StartsWith("[")) { - MessageBox.Show(string.Format("{0} is an invalid UserID", _MyUser.UserID)); + MessageBox.Show($"{_MyUser.UserID} is an invalid UserID"); return; } if (_MyUser.UserID == string.Empty) @@ -65,29 +61,26 @@ namespace VEPROMS } if (UserInfo.GetByUserID(_MyUser.UserID) != null && _Mode.ToUpper() == "ADD") { - MessageBox.Show(string.Format("A user already exists with the UserID '{0}'", _MyUser.UserID)); + MessageBox.Show($"A user already exists with the UserID '{_MyUser.UserID}'"); return; } _MyUser.Save(); - this.DialogResult = DialogResult.OK; + DialogResult = DialogResult.OK; } private void btnCancel_Click(object sender, EventArgs e) { _MyUser = User.Get(_MyUser.UID); - this.DialogResult = DialogResult.Cancel; + DialogResult = DialogResult.Cancel; } } internal class SimpleUser { - private User _MyUser; - private UserConfig _MyUC; - [Browsable(false)] - public User MyUser - { - get { return _MyUser; } - } - public SimpleUser(User myUser) + private readonly User _MyUser; + private readonly UserConfig _MyUC; + [Browsable(false)] + public User MyUser => _MyUser; + public SimpleUser(User myUser) { _MyUser = myUser; _MyUC = new UserConfig(myUser.Config); diff --git a/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs b/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs index 14ddb2ab..dbfec5cb 100644 --- a/PROMS/VEPROMS User Interface/frmPDFStatusForm.cs +++ b/PROMS/VEPROMS User Interface/frmPDFStatusForm.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 Volian.Print.Library; using VEPROMS.CSLA.Library; @@ -14,90 +11,24 @@ namespace VEPROMS { public partial class frmPDFStatusForm : Form { - private bool _CancelPrinting = false; - public bool CancelPrinting - { - get { return _CancelPrinting; } - set { _CancelPrinting = value; } - } - private bool _CloseWhenDone = false; - public bool CloseWhenDone - { - get { return _CloseWhenDone; } - set { _CloseWhenDone = value; } - } - private bool _CancelStop = false; - public bool CancelStop - { - get { return _CancelStop; } - set { _CancelStop = value; } - } - private bool _Stop = false; - public bool Stop - { - get { return _Stop; } - set { _Stop = value; } - } - private string _PDFPath; + public bool CancelPrinting { get; set; } = false; + public bool CloseWhenDone { get; set; } = false; + public bool CancelStop { get; set; } = false; + public bool Stop { get; set; } = false; - public string PDFPath - { - get { return _PDFPath; } - set { _PDFPath = value; } - } - private PromsPrinter _MyPromsPrinter; + public string PDFPath { get; set; } - public PromsPrinter MyPromsPrinter - { - get { return _MyPromsPrinter; } - set { _MyPromsPrinter = value; } - } + public PromsPrinter MyPromsPrinter { get; set; } - private bool _OpenPDF; + public bool OpenPDF { get; set; } + private Point _NewLocation; - public bool OpenPDF - { - get { return _OpenPDF; } - set { _OpenPDF = value; } - } - private Point _NewLocation; - private string _Prefix = ""; // RHM20150506 Multiline ItemID TextBox - public string Prefix - { - get { return _Prefix; } - set { _Prefix = value; } - } - // this flag is used when the Continuous Action Sumamry is printed from the tree or ribbon button - // it will prevent the temporary PDF (generated with printing - needed to get page numbers) from being displayed - // and will delete that temporary PDF file - private bool _OnlyShowContinuousActionSummary = false; - public bool OnlyShowContinuousActionSummary - { - get { return _OnlyShowContinuousActionSummary; } - set { _OnlyShowContinuousActionSummary = value; } - } - // F2022-024 this flag is used when the Time Critical Action Sumamry is printed from the tree or ribbon button - // it will prevent the temporary PDF (generated with printing - needed to get page numbers) from being displayed - // and will delete that temporary PDF file - private bool _OnlyShowTimeCriticalActionSummary = false; - public bool OnlyShowTimeCriticalActionSummary - { - get { return _OnlyShowTimeCriticalActionSummary; } - set { _OnlyShowTimeCriticalActionSummary = value; } - } - private bool _DidAll = false; - public bool DidAll - { - get { return _DidAll; } - set { _DidAll = value; } - } - private int _prtSectID = -1; - public int PrtSectID - { - get { return _prtSectID; } - set { _prtSectID = value; } - } - public frmPDFStatusForm(ItemInfo myItem, string rev, string watermark, bool debugOutput, bool origPgBrk, bool openPDF, bool overWrite, string pdfPath, ChangeBarDefinition cbd, string pdfFile, Point newLocation, bool insertBlankPages, bool allOrAuto, string prefix, bool saveLinks, int removeTrailingHardReturnsAndManualPageBreaks, bool showPROMSVer, bool didAll, string blankPageText, MergedPdf mergedPdf, string watermarkColor, int PrtSectID = -1) + public string Prefix { get; set; } = ""; + public bool OnlyShowContinuousActionSummary { get; set; } = false; + public bool OnlyShowTimeCriticalActionSummary { get; set; } = false; + public bool DidAll { get; set; } = false; + public int PrtSectID { get; set; } = -1; + public frmPDFStatusForm(ItemInfo myItem, string rev, string watermark, bool debugOutput, bool origPgBrk, bool openPDF, bool overWrite, string pdfPath, ChangeBarDefinition cbd, string pdfFile, Point newLocation, bool insertBlankPages, bool allOrAuto, string prefix, bool saveLinks, int removeTrailingHardReturnsAndManualPageBreaks, bool showPROMSVer, bool didAll, string blankPageText, MergedPdf mergedPdf, string watermarkColor, int PrtSectID = -1) { // B2021-088 moved this if/else from CreatePDF() so that the Approval logic will have access to this logic ProcedureInfo MyProcedure = myItem as ProcedureInfo; @@ -114,28 +45,29 @@ namespace VEPROMS // B2021-102 moved the baseline meta file write here too - should have been done with B2021-088 fix // C2018-015 add the procedure tree path and the procedure number and title to the meta file - if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0}", MyProcedure.SearchDVPath.Replace("\a", " | ")); - if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! {0} | {1}", MyProcedure.DisplayNumber, MyProcedure.DisplayText); + if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine($"!! {MyProcedure.SearchDVPath.Replace("\a", " | ")}"); + if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine($"!! {MyProcedure.DisplayNumber} | {MyProcedure.DisplayText}"); myItem = MyProcedure; Prefix = prefix; OpenPDF = openPDF; DidAll = didAll; - _prtSectID = PrtSectID; + this.PrtSectID = PrtSectID; InitializeComponent(); - // if the version number of PROMS is 1.0, then we are running a Demo version. - // When running a Demo version, force a "Sample" watermark when printing. - // B2020-022 append a ".pdf" extension if the file name does on have one. - MyPromsPrinter = new PromsPrinter(myItem, rev, (VlnSettings.ReleaseMode.Equals("DEMO")) ? "Sample" : watermark, debugOutput, origPgBrk, pdfPath + @"\Compare", false, overWrite, cbd, (pdfFile.ToUpper().EndsWith(".PDF"))?pdfFile:pdfFile+".pdf", insertBlankPages, allOrAuto,Prefix,saveLinks,removeTrailingHardReturnsAndManualPageBreaks, blankPageText, DidAll, mergedPdf, watermarkColor); - - MyPromsPrinter.PromsVersion = (showPROMSVer) ? AboutVEPROMS.PROMSVersion : ""; //C2018-009 print PROMS version - - - PDFPath = pdfPath; - this.Text = "Creating PDF of " + myItem.DisplayNumber; + // if the version number of PROMS is 1.0, then we are running a Demo version. + // When running a Demo version, force a "Sample" watermark when printing. + // B2020-022 append a ".pdf" extension if the file name does on have one. + MyPromsPrinter = new PromsPrinter(myItem, rev, (VlnSettings.ReleaseMode.Equals("DEMO")) ? "Sample" : watermark, debugOutput, origPgBrk, pdfPath + @"\Compare", false, overWrite, cbd, (pdfFile.ToUpper().EndsWith(".PDF")) ? pdfFile : $"{pdfFile}.pdf", insertBlankPages, allOrAuto, Prefix, saveLinks, removeTrailingHardReturnsAndManualPageBreaks, blankPageText, DidAll, mergedPdf, watermarkColor) + { + PromsVersion = (showPROMSVer) ? AboutVEPROMS.PROMSVersion : "" //C2018-009 print PROMS version + }; + + + PDFPath = pdfPath; + Text = $"Creating PDF of {myItem.DisplayNumber}"; _NewLocation = newLocation; DialogResult = DialogResult.OK; @@ -162,24 +94,18 @@ namespace VEPROMS if (waterMarkText.ToUpper() == "[U-TEXT]") { string utxt = (procInfo.MyDocVersion.MultiUnitCount > 1) ? procInfo.MyDocVersion.DocVersionConfig.Unit_Text : ""; - waterMarkText = (utxt == null) ? "" : utxt; + waterMarkText = utxt ?? ""; } else if (waterMarkText.ToUpper() == "[U-NUMBER]") { string uNum = (procInfo.MyDocVersion.MultiUnitCount > 1) ? procInfo.MyDocVersion.DocVersionConfig.Unit_Number : ""; - waterMarkText = (uNum == null) ? "" : uNum; + waterMarkText = uNum ?? ""; } } } - // used when the approved function creates an export file with unlinked ROs and Transitons. Word sections that have RO tokens are saved with the RO Vaules in DocReplace - // DocReplace is passed on to the Export functions. - private Dictionary _DocReplace; - public Dictionary DocReplace - { - get { return _DocReplace; } - set { _DocReplace = value; } - } - public bool AllowAllWatermarks + + public Dictionary DocReplace { get; set; } + public bool AllowAllWatermarks { get { return MyPromsPrinter.AllowAllWatermarks; } set { MyPromsPrinter.AllowAllWatermarks = value; } @@ -195,7 +121,7 @@ namespace VEPROMS if (args.Progress == pb.Maximum) pb.Text = args.MyStatus; else - pb.Text = string.Format("Processing {0} ({1} of {2})", args.MyStatus, args.Progress + 1, pb.Maximum); + pb.Text = $"Processing {args.MyStatus} ({args.Progress + 1} of {pb.Maximum})"; } MyStatus = args.MyStatus; Application.DoEvents(); @@ -217,38 +143,15 @@ namespace VEPROMS Text = Text.Replace("PDF", "Time Critical Action Summary"); // F2022-024 Time Critical Action } - private string _PdfFile; - public string PdfFile - { - get { return _PdfFile; } - set { _PdfFile = value; } - } - private bool _MakePlaceKeeper = false; + public string PdfFile { get; set; } - public bool MakePlaceKeeper - { - get { return _MakePlaceKeeper; } - set { _MakePlaceKeeper = value; } - } + public bool MakePlaceKeeper { get; set; } = false; - private bool _MakeContinuousActionSummary = false; + public bool MakeContinuousActionSummary { get; set; } = false; - public bool MakeContinuousActionSummary - { - get { return _MakeContinuousActionSummary; } - set { _MakeContinuousActionSummary = value; } - } + public bool MakeTimeCriticalActionSummary { get; set; } = false; - // F2022-024 Time Critical Action Summary - private bool _MakeTimeCriticalActionSummary = false; - - public bool MakeTimeCriticalActionSummary - { - get { return _MakeTimeCriticalActionSummary; } - set { _MakeTimeCriticalActionSummary = value; } - } - - private void tmrRun_Tick(object sender, EventArgs e) + private void tmrRun_Tick(object sender, EventArgs e) { tmrRun.Enabled = false; if (CancelStop) btnCancel.Visible = true; @@ -293,7 +196,7 @@ namespace VEPROMS if (OnlyShowTimeCriticalActionSummary) { MyPromsPrinter.PromsPrinterPrintType = PromsPrinterPrintType.TCAS_only; } - _PdfFile = MyPromsPrinter.Print(PDFPath, MakePlaceKeeper, MakeContinuousActionSummary, MakeTimeCriticalActionSummary, PrtSectID); + PdfFile = MyPromsPrinter.Print(PDFPath, MakePlaceKeeper, MakeContinuousActionSummary, MakeTimeCriticalActionSummary, PrtSectID); ProfileTimer.Pop(profileDepth); @@ -307,13 +210,13 @@ namespace VEPROMS } // B2024-062 Added check for EmptyProcedure. We don't need to show the Try Again message if the procedure // is empty, as it would be just be a waste of time for the user. - while (!MyPromsPrinter.MergeNotIncluded && _PdfFile == null && !MyPromsPrinter.EmptyProcedure && + while (!MyPromsPrinter.MergeNotIncluded && PdfFile == null && !MyPromsPrinter.EmptyProcedure && MessageBox.Show("Try Again?", "PDF Creation Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes); - if (_PdfFile == null) + if (PdfFile == null) { - this.Close(); + Close(); return; } @@ -329,13 +232,13 @@ namespace VEPROMS } DateTime tEnd = DateTime.Now; - MyStatus = _PdfFile + " created."; - MyStatus = string.Format("{0} created in {1:0.} milliseconds", _PdfFile, (TimeSpan.FromTicks(tEnd.Ticks - tStart.Ticks).TotalMilliseconds)); + MyStatus = $"{PdfFile} created."; + MyStatus = $"{PdfFile} created in {(TimeSpan.FromTicks(tEnd.Ticks - tStart.Ticks).TotalMilliseconds):0.} milliseconds"; if (OpenPDF) { - OpenPDFandPlacekeeper(_PdfFile); - this.Close(); + OpenPDFandPlacekeeper(PdfFile); + Close(); // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. Ask if user wants to save chanages // if they were found. @@ -362,15 +265,15 @@ namespace VEPROMS if (CloseWhenDone) { OpenPDFandPlacekeeper(null); - this.Close(); + Close(); return; } } private void btnOpenPDF_Click(object sender, EventArgs e) { - OpenPDFandPlacekeeper(_PdfFile); - this.Close(); + OpenPDFandPlacekeeper(PdfFile); + Close(); } // set a delay so that the word document containing the newly generated placekeeper will appear on top of everything else. @@ -383,8 +286,7 @@ namespace VEPROMS { System.Diagnostics.Process sdp = System.Diagnostics.Process.Start(pdffile); - if (sdp != null) - sdp.WaitForInputIdle(); + sdp?.WaitForInputIdle(); } if (OnlyShowContinuousActionSummary || OnlyShowTimeCriticalActionSummary) // F2022-024 Time Critical Action Summary @@ -441,16 +343,16 @@ namespace VEPROMS } catch (Exception ex) { - string str = string.Format("{0} - {1} - {2}",pdffile,ex.GetType().Name,ex.Message); + string str = $"{pdffile} - {ex.GetType().Name} - {ex.Message}"; MessageBox.Show(str, "Error Opening PDFFile", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void btnOpenFolder_Click(object sender, EventArgs e) { - System.Diagnostics.Process.Start("Explorer", "/select," + _PdfFile); + System.Diagnostics.Process.Start("Explorer", $"/select,{PdfFile}"); OpenPDFandPlacekeeper(null); - this.Close(); + Close(); } private void btnCancel_Click(object sender, EventArgs e) diff --git a/PROMS/VEPROMS User Interface/frmPSI.cs b/PROMS/VEPROMS User Interface/frmPSI.cs index f84bafbf..8d1d9211 100644 --- a/PROMS/VEPROMS User Interface/frmPSI.cs +++ b/PROMS/VEPROMS User Interface/frmPSI.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; @@ -13,10 +11,13 @@ namespace VEPROMS public partial class frmPSI : Form { private ProcedureInfo _MyProcedureInfo; - private StepTabRibbon _MyStepTabRibbon; - private Dictionary _DicStepRtb; - private Dictionary _DicCheckBox; - private Dictionary _DicComboBox; + private readonly StepTabRibbon _MyStepTabRibbon; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicStepRtb; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicCheckBox; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicComboBox; public frmPSI(ProcedureInfo pi) { InitializeComponent(); @@ -31,22 +32,23 @@ namespace VEPROMS { _MyProcedureInfo = pi; PSI psiDialogDef = pi.ActiveFormat.PlantFormat.FormatData.ProcData.PSI; - this.Text = psiDialogDef.Caption; - this.Location = new Point((int)psiDialogDef.x * 2, (int)psiDialogDef.y * 2); + Text = psiDialogDef.Caption; + Location = new Point((int)psiDialogDef.x * 2, (int)psiDialogDef.y * 2); int maxx = 0; int maxy = 0; int xB4Scroll = 900; int yB4Scroll = 630; - this.panelPSI.AutoScroll = false; + panelPSI.AutoScroll = false; foreach (SILabel lbl in psiDialogDef.LabelList) { - Label wlbl = new Label(); - wlbl.Text = lbl.text; - wlbl.Location = new Point((int)lbl.x * 2, (int)lbl.y * 2); - wlbl.AutoSize = true; - //wlbl.Size = new Size((int)lbl.width * 2, (int)lbl.height * 2); - wlbl.Visible = true; - this.panelPSI.Controls.Add(wlbl); + Label wlbl = new Label + { + Text = lbl.text, + Location = new Point((int)lbl.x * 2, (int)lbl.y * 2), + AutoSize = true, + Visible = true + }; + panelPSI.Controls.Add(wlbl); maxx = ((int)lbl.x * 2 + (int)lbl.width * 2) > maxx ? ((int)lbl.x * 2 + (int)lbl.width * 2) : maxx; maxy = ((int)lbl.y * 2 + (int)lbl.height * 2) > maxy ? ((int)lbl.y * 2 + (int)lbl.height * 2) : maxy; } @@ -62,7 +64,7 @@ namespace VEPROMS tb.MyItemInfo = pi as ItemInfo; tb.FieldToEdit = E_FieldToEdit.PSI; tb.BorderStyle = BorderStyle.FixedSingle; - tb.Enter += new System.EventHandler(this.FieldStepRTB_Enter); + tb.Enter += new System.EventHandler(FieldStepRTB_Enter); // see if config has data for this field, i.e. search for the 'name' // B2018-057 Replace non-breaking hyphen with hyphen. string val = procConfig.GetValue("PSI", fld.name).Replace("\\u8209?", "-"); @@ -70,13 +72,13 @@ namespace VEPROMS StringBuilder sb = new StringBuilder(); sb.Append(@"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset2 Arial;}"); sb.Append(@"{\f1\fnil\fcharset0 Arial;}}{\colortbl ;\red255\green0\blue0;}"); //C2017-036 changed to just Arial because Microsoft removed Arial Unicode MS with Word16 - sb.Append(@"\viewkind4\uc1\pard\sl-240\slmult0\fs" + (int)(this.Font.SizeInPoints*2) + " " + dt.StartText + @"}"); + sb.Append(@"\viewkind4\uc1\pard\sl-240\slmult0\fs" + (int)(Font.SizeInPoints*2) + " " + dt.StartText + @"}"); tb.Rtf = sb.ToString(); tb.Location = new Point((int)fld.x * 2, (int)fld.y * 2); tb.Size = new Size((int)fld.width * 2, (int)fld.height * 2); tb.MinimumSize = new Size((int)fld.width * 2, (int)fld.height * 2); tb.Visible = true; - this.panelPSI.Controls.Add(tb); + panelPSI.Controls.Add(tb); maxx = ((int)fld.x * 2 + (int)fld.width * 2) > maxx ? ((int)fld.x * 2 + (int)fld.width * 2) : maxx; maxy = ((int)fld.y * 2 + (int)fld.height * 2) > maxy ? ((int)fld.y * 2 + (int)fld.height * 2) : maxy; } @@ -89,8 +91,8 @@ namespace VEPROMS cb.Visible = true; cb.Width = (int)fld.width * 2; string val = procConfig.GetValue("PSI", fld.name); - cb.Checked = val!=null && val!="" && val.ToUpper()[0] == 'Y' ? true : false; - this.panelPSI.Controls.Add(cb); + cb.Checked = val !=null && val!="" && val.ToUpper()[0] == 'Y'; + panelPSI.Controls.Add(cb); maxx = ((int)fld.x * 2 + (int)fld.width * 2) > maxx ? ((int)fld.x * 2 + (int)fld.width * 2) : maxx; maxy = ((int)fld.y * 2 + (int)fld.height * 2) > maxy ? ((int)fld.y * 2 + (int)fld.height * 2) : maxy; } @@ -107,7 +109,7 @@ namespace VEPROMS foreach (string t in tmps) cmb.Items.Add(t); string val = procConfig.GetValue("PSI", fld.name); if (val != null && val != "") cmb.SelectedItem = val; - this.panelPSI.Controls.Add(cmb); + panelPSI.Controls.Add(cmb); maxx = ((int)fld.x * 2 + (int)fld.width * 2) > maxx ? ((int)fld.x * 2 + (int)fld.width * 2) : maxx; maxy = ((int)fld.y * 2 + (int)fld.height * 2) > maxy ? ((int)fld.y * 2 + (int)fld.height * 2) : maxy; } @@ -115,19 +117,19 @@ namespace VEPROMS if (maxx > xB4Scroll) { maxx = xB4Scroll; - this.panelPSI.Width = xB4Scroll; - this.panelPSI.AutoScroll = true; + panelPSI.Width = xB4Scroll; + panelPSI.AutoScroll = true; } else - this.panelPSI.Width = maxx + 50; + panelPSI.Width = maxx + 50; if (maxy > yB4Scroll) { maxy = yB4Scroll; - this.panelPSI.Height = yB4Scroll; - this.panelPSI.AutoScroll = true; + panelPSI.Height = yB4Scroll; + panelPSI.AutoScroll = true; } else - this.panelPSI.Height = maxy; // B2018-062: Ok/Cancel buttons not displayed if more than a few labels/fields are defined. + panelPSI.Height = maxy; // B2018-062: Ok/Cancel buttons not displayed if more than a few labels/fields are defined. if (psiDialogDef.ButtonsOnBottom == null || psiDialogDef.ButtonsOnBottom.ToUpper() == "NO") { btnOk.Location = new Point(maxx+70, 30); @@ -138,17 +140,14 @@ namespace VEPROMS // B2018-062: Ok/Cancel buttons not displayed if more than a few labels/fields are defined: // Adjust location of buttons so that they have a larger Y than the panel that holds the labels/fields // and adjust the dialog size if it's height is not enough. - btnOk.Location = new Point(btnOk.Location.X, panelPSI.Location.Y + this.panelPSI.Height + 10); - btnCancel.Location = new Point(btnCancel.Location.X, panelPSI.Location.Y + this.panelPSI.Height + 10); - if (this.Height < btnOk.Location.Y + btnOk.Size.Height + 10) - this.Height = btnOk.Location.Y + btnOk.Size.Height + 30; + btnOk.Location = new Point(btnOk.Location.X, panelPSI.Location.Y + panelPSI.Height + 10); + btnCancel.Location = new Point(btnCancel.Location.X, panelPSI.Location.Y + panelPSI.Height + 10); + if (Height < btnOk.Location.Y + btnOk.Size.Height + 10) + Height = btnOk.Location.Y + btnOk.Size.Height + 30; } } - private void FieldStepRTB_Enter(object sender, EventArgs e) - { - _MyStepTabRibbon.MyStepRTB = (StepRTB)sender; - } - private void btnOk_Click(object sender, EventArgs e) + private void FieldStepRTB_Enter(object sender, EventArgs e) => _MyStepTabRibbon.MyStepRTB = (StepRTB)sender; + private void btnOk_Click(object sender, EventArgs e) { ProcedureConfig procConfig = _MyProcedureInfo.MyConfig as ProcedureConfig; PSI psiDialogDef = _MyProcedureInfo.ActiveFormat.PlantFormat.FormatData.ProcData.PSI; @@ -204,13 +203,13 @@ namespace VEPROMS } } DialogResult = DialogResult.OK; - this.Close(); + Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; - this.Close(); + Close(); } } } \ No newline at end of file diff --git a/PROMS/VEPROMS User Interface/frmProcedureProperties.cs b/PROMS/VEPROMS User Interface/frmProcedureProperties.cs index 19d5958d..4bf03180 100644 --- a/PROMS/VEPROMS User Interface/frmProcedureProperties.cs +++ b/PROMS/VEPROMS User Interface/frmProcedureProperties.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 VEPROMS.CSLA.Library; using VEPROMS.Properties; @@ -11,8 +6,6 @@ using DescriptiveEnum; using DevComponents.DotNetBar; using DevComponents.DotNetBar.Controls; using Volian.Controls.Library; -using System.Xml; -using Csla; namespace VEPROMS { @@ -20,7 +13,6 @@ namespace VEPROMS { private bool _Initializing = false; private string _DefaultFormatName = null; - //private string _DefaultPagination = null; private string _DefaultWatermark = null; private string _DefaultChgBarType = null; private string _DefaultChgBarLoc = null; @@ -28,21 +20,18 @@ namespace VEPROMS private string _DefaultChgBarUsrMsg1 = null; private string _DefaultChgBarUsrMsg2 = null; private string _DefaultFormatColumns = null; - private bool _DefaultDisableDuplex = false; - private ProcedureConfig _ProcedureConfig; - private StepTabRibbon _MyStepTabRibbon; + private readonly ProcedureConfig _ProcedureConfig; + private readonly StepTabRibbon _MyStepTabRibbon; public frmProcedureProperties(ProcedureConfig procedureConfig) { _ProcedureConfig = procedureConfig; _Initializing = true; InitializeComponent(); - btnGeneral.PerformClick(); // always start with General tab or button - _Initializing = false; - // build the title bar caption - //this.Text = string.Format("{0} {1} Properties", procedureConfig.Number, procedureConfig.Title); + btnGeneral.PerformClick(); // always start with General tab or button ItemInfo itmInfo = ItemInfo.Get(_ProcedureConfig.MyProcedure.ItemID); - this.Text = string.Format("{0} {1} Properties", itmInfo.DisplayNumber, itmInfo.DisplayText); + // build the title bar caption + Text = $"{itmInfo.DisplayNumber} {itmInfo.DisplayText} Properties"; ppProcTitleStpRTB.Font = ppProcTitleStpRTB.FormatFont = new System.Drawing.Font("Microsoft Sans Serif", 10F); ppProcTitleStpRTB.FieldToEdit = E_FieldToEdit.Text; ppProcTitleStpRTB.BorderStyle = BorderStyle.Fixed3D; @@ -54,12 +43,11 @@ namespace VEPROMS ppProcNumStpRTB.MyItemInfo = itmInfo; ppProcNumStpRTB.RefreshDisplay(true); - _MyStepTabRibbon = new StepTabRibbon(); - //_MyStepTabRibbon.Dock = System.Windows.Forms.DockStyle.Top; - //_MyStepTabRibbon.Location = new System.Drawing.Point(0, 0); - _MyStepTabRibbon.Name = "displayTabRibbon1"; - _MyStepTabRibbon.Visible = false; - //defaultSettingsVisiblity(); + _MyStepTabRibbon = new StepTabRibbon + { + Name = "displayTabRibbon1", + Visible = false + }; } private void ppBtnOK_Click(object sender, EventArgs e) @@ -99,7 +87,7 @@ namespace VEPROMS } } DialogResult = DialogResult.OK; - this.Close(); + Close(); } public void SaveText(StepRTB myStepRTB) { @@ -118,8 +106,8 @@ namespace VEPROMS { procedureConfigBindingSource.CancelEdit(); _ProcedureConfig.MyProcedure.MyProcedureInfo.CreateEnhanced = false; - this.DialogResult = DialogResult.Cancel; - this.Close(); + DialogResult = DialogResult.Cancel; + Close(); } /// @@ -156,10 +144,6 @@ namespace VEPROMS if (!(_DefaultChgBarUsrMsg2.Equals(""))) ppLblChgBarUserMsgTwoDefault.Text = string.Format("({0})", _DefaultChgBarUsrMsg2); - // Get the default Print Pagination - //_DefaultPagination = _ProcedureConfig.Print_Pagination.ToString(); - //SetupDefault(EnumDescConverter.GetEnumDescription(_ProcedureConfig.Print_Pagination), ppLblPaginationDefault, ppCmbxPagination); - // Get the default Watermark _DefaultWatermark = _ProcedureConfig.Print_Watermark.ToString(); SetupDefault(EnumDescConverter.GetEnumDescription(_ProcedureConfig.Print_Watermark), ppLblWatermarkDefault, ppCmbxWatermark); @@ -178,8 +162,6 @@ namespace VEPROMS _Initializing = true; procedureConfigBindingSource.DataSource = _ProcedureConfig; - //formatInfoListBindingSource.DataSource = FormatInfoList.Get(); - ppCmbxFormat.DataSource = null; ppCmbxFormat.DisplayMember = "FullName"; ppCmbxFormat.ValueMember = "FullName"; @@ -195,7 +177,7 @@ namespace VEPROMS // Get the saved settings for this user // // This setting tells us if we should display the default values on this property page - ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultProcedureProp"] != null) ? Settings.Default.ShowDefaultProcedureProp : false; + ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultProcedureProp"] != null) && Settings.Default.ShowDefaultProcedureProp; // Get the User's property page style "PropPageStyle" (this is a system wide user setting) // 1 - Button Dialog (default) @@ -204,7 +186,7 @@ namespace VEPROMS { tcProcProp.TabsVisible = true; panProcBtns.Visible = false; - this.Width -= panProcBtns.Width; + Width -= panProcBtns.Width; } // Get the default values for the property page information @@ -230,11 +212,6 @@ namespace VEPROMS ppCmbxChangeBarType.ValueMember = "EValue"; ppCmbxChangeBarType.SelectedIndex = -1; - //ppCmbxPagination.DataSource = EnumDetail.Details(); - //ppCmbxPagination.DisplayMember = "Description"; - //ppCmbxPagination.ValueMember = "EValue"; - //ppCmbxPagination.SelectedIndex = -1; - ppCmbxWatermark.DataSource = EnumDetail.Details(); ppCmbxWatermark.DisplayMember = "Description"; ppCmbxWatermark.ValueMember = "EValue"; @@ -247,8 +224,7 @@ namespace VEPROMS // the only time the create enhanced checkbox is visisble is if this is a 'New' procedure in a set that is the 'Source'. cbEnhanced.Visible = false; - DocVersionConfig dvc = _ProcedureConfig.MyProcedure.MyProcedureInfo.MyDocVersion.MyConfig as DocVersionConfig; - if (_ProcedureConfig.CreatingNew && dvc != null && dvc.MyEnhancedDocuments != null && dvc.MyEnhancedDocuments.Count > 0 && dvc.MyEnhancedDocuments[0].Type != 0) + if (_ProcedureConfig.CreatingNew && _ProcedureConfig.MyProcedure.MyProcedureInfo.MyDocVersion.MyConfig is DocVersionConfig dvc && dvc.MyEnhancedDocuments != null && dvc.MyEnhancedDocuments.Count > 0 && dvc.MyEnhancedDocuments[0].Type != 0) cbEnhanced.Visible = true; cbNotIncludeInMerged.Checked = _ProcedureConfig.Print_NotInMergeAll; _Initializing = false; @@ -262,10 +238,7 @@ namespace VEPROMS /// /// object /// EventArgs - private void btnGeneral_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiGeneral, btnGeneral); - } + private void btnGeneral_Click(object sender, EventArgs e) => ProcessButtonClick(tiGeneral, btnGeneral); /// /// Selection in Default Column Mode combo box changed. @@ -278,14 +251,6 @@ namespace VEPROMS { FormatColumns fc = (FormatColumns)Enum.Parse(typeof(FormatColumns), _DefaultFormatColumns); ProcessCmbxSelectionEnumChanged(ppCmbxStpEditorCols, fc, ppBtnDefEdCols, ppLblStpEditorColsDefault); - //if ((ppCmbxStpEditorCols.SelectedIndex != -1) && ppCmbxStpEditorCols.SelectedValue.Equals(fc)) - //{ - // ppBtnDefEdCols.Focus(); - // ppBtnDefEdCols.PerformClick(); - //} - //ppBtnDefEdCols.Visible = ppCmbxStpEditorCols.SelectedValue != null; - //ppLblStpEditorColsDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefEdCols.Visible; - //tcpGeneral.Focus(); } } #endregion @@ -304,22 +269,7 @@ namespace VEPROMS if (_InitialIndex < -1) _InitialIndex = ppCmbxFormat.SelectedIndex; // save the current format selection (happens here when current section is set to the default format) } - private void ppBtnDefaultFmt_Click(object sender, EventArgs e) - { - ppCmbxFormat.SelectedIndex = -1; //reset to the default Format setting - //tcpFormatSettings.Focus(); - } - - // Commented out as part of code change C2017-004. this also makes it consistent with section properties - /// - /// Selection in Format combo box changed. - /// - /// object - /// EventArgs - //private void ppCmbxFormat_SelectedValueChanged(object sender, EventArgs e) - //{ - // ProcessCmbxSelectedValueChange(ppCmbxFormat, _DefaultFormatName, ppBtnDefaultFmt, ppLblFormatDefault); - //} + private void ppBtnDefaultFmt_Click(object sender, EventArgs e) => ppCmbxFormat.SelectedIndex = -1; //reset to the default Format setting /// /// Enable or disable the user specified change bar options base on the type @@ -327,14 +277,6 @@ namespace VEPROMS /// private void setEnabledUserSpecifiedChgBarCombos(PrintChangeBar pcb) { - //ppGpbxUserSpecCB.Enabled = - //ppCmbxChgBarPos.Enabled = - //ppCmbxChgBarTxtType.Enabled = - //ppBtnDefaultCbPos.Enabled = - //ppBtnDefCbTxtTyp.Enabled = (ppCmbxChangeBarType.SelectedValue != null && - // ppCmbxChangeBarType.SelectedValue.Equals(ProcedureConfig.PrintChangeBar.WithUserSpecified)) || - // (ppCmbxChangeBarType.SelectedValue == null && pcb.Equals(DocVersionConfig.PrintChangeBar.WithUserSpecified)); - ppGpbxUserSpecCB.Enabled = (ppCmbxChangeBarType.SelectedValue != null && ppCmbxChangeBarType.SelectedValue.Equals(PrintChangeBar.WithUserSpecified)) || (ppCmbxChangeBarType.SelectedValue == null && pcb.Equals(PrintChangeBar.WithUserSpecified)); @@ -353,7 +295,6 @@ namespace VEPROMS PrintChangeBar pcb = (PrintChangeBar)Enum.Parse(typeof(PrintChangeBar), _DefaultChgBarType); ProcessCmbxSelectionEnumChanged(ppCmbxChangeBarType, pcb, ppBtnDefaultChgBar, ppLblChangeBarTypeDefault); setEnabledUserSpecifiedChgBarCombos(pcb); - //tcpFormatSettings.Focus(); } } @@ -369,12 +310,9 @@ namespace VEPROMS // Get the parent setting PrintChangeBar pcb = (PrintChangeBar)Enum.Parse(typeof(PrintChangeBar), _DefaultChgBarType); // Compare parent setting with current setting - //_Initializing = true; if (pcb != _ProcedureConfig.Print_ChangeBar) _ProcedureConfig.Print_ChangeBar = pcb; // this will force a database update (write) ppCmbxChangeBarType.SelectedIndex = -1; //reset to the default Change Bar setting - //_Initializing = false; - //tcpFormatSettings.Focus(); } /// @@ -388,7 +326,6 @@ namespace VEPROMS { PrintChangeBarLoc cbl = (PrintChangeBarLoc)Enum.Parse(typeof(PrintChangeBarLoc), _DefaultChgBarLoc); ProcessCmbxSelectionEnumChanged(ppCmbxChgBarPos, cbl, ppBtnDefaultCbPos, ppLblChgBarPosDefault); - //tcpFormatSettings.Focus(); } } @@ -407,7 +344,6 @@ namespace VEPROMS if (cbl != _ProcedureConfig.Print_ChangeBarLoc) _ProcedureConfig.Print_ChangeBarLoc = cbl; // this will force a database update (write) ppCmbxChgBarPos.SelectedIndex = -1; //reset to the default Change Bar Position setting - //tcpFormatSettings.Focus(); } /// @@ -422,7 +358,6 @@ namespace VEPROMS PrintChangeBarText cbt = (PrintChangeBarText)Enum.Parse(typeof(PrintChangeBarText), _DefaultChgBarText); ProcessCmbxSelectionEnumChanged(ppCmbxChgBarTxtType, cbt, ppBtnDefCbTxtTyp, ppLblChgBarTxtTypeDefault); setEnabledUserSpecifiedChgBarText(); - //tcpFormatSettings.Focus(); } } @@ -441,7 +376,6 @@ namespace VEPROMS if (cbt != _ProcedureConfig.Print_ChangeBarText) _ProcedureConfig.Print_ChangeBarText = cbt; // this will force a database update (write) ppCmbxChgBarTxtType.SelectedIndex = -1; //reset to the default Change Bar Text Type setting - //tcpFormatSettings.Focus(); } /// @@ -450,13 +384,6 @@ namespace VEPROMS /// private void setEnabledUserSpecifiedChgBarText() { - //ppGpbxUserSpecTxt.Enabled = - //ppTxbxChangeBarUserMsgOne.Enabled = - //ppTxbxChgBarUserMsgTwo.Enabled = - //ppBtnDefCbTxt1.Enabled = - //ppBtnDefCbTxt2.Enabled = (ppCmbxChgBarTxtType.SelectedValue != null && - //ppCmbxChgBarTxtType.SelectedValue.Equals(ProcedureConfig.PrintChangeBarText.UserDef)); - // This string is used to check against our default setting to see if User Defined Changebar Text is active string decUserDef = PrintChangeBarText.UserDef.ToString(); @@ -475,43 +402,7 @@ namespace VEPROMS /// /// object /// EventArgs - private void btnOutputStngs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiOutputStngs, btnOutputStngs); - } - - /// - /// Selection in Pagination combo box changed. - /// - /// object - /// EventArgs - //private void ppCmbxPagination_SelectedValueChanged(object sender, EventArgs e) - //{ - // if (!_Initializing) - // { - // PrintPagination pgtn = (PrintPagination)Enum.Parse(typeof(PrintPagination), _DefaultPagination); - // ProcessCmbxSelectionEnumChanged(ppCmbxPagination, pgtn, ppBtnDefPagination, ppLblPaginationDefault); - // //tcpOutputSettings.Focus(); - // } - //} - - /// - /// Reset to the parent setting. - /// Find the parent setting and assign it to _ProcedureConfig.Print_Pagination. - /// This will force the database to be updated. - /// - /// - /// - //private void ppBtnDefPagination_Click(object sender, EventArgs e) - //{ - // // Get the parent setting - // PrintPagination pgtn = (PrintPagination)Enum.Parse(typeof(PrintPagination), _DefaultPagination); - // // Compare parent setting with current setting - // if (pgtn != _ProcedureConfig.Print_Pagination) - // _ProcedureConfig.Print_Pagination = pgtn; // this will force a database update (write) - // ppCmbxPagination.SelectedIndex = -1; //reset to the default Pagination setting - // //tcpOutputSettings.Focus(); - //} + private void btnOutputStngs_Click(object sender, EventArgs e) => ProcessButtonClick(tiOutputStngs, btnOutputStngs); /// /// Selection in Watermark combo box changed. @@ -524,7 +415,6 @@ namespace VEPROMS { PrintWatermark wtr = (PrintWatermark)Enum.Parse(typeof(PrintWatermark), _DefaultWatermark); ProcessCmbxSelectionEnumChanged(ppCmbxWatermark, wtr, ppBtnDefWatermark, ppLblWatermarkDefault); - //tcpOutputSettings.Focus(); } } @@ -547,19 +437,6 @@ namespace VEPROMS #endregion - #region View Settings tab - - ///// - ///// This is the View Settings button used on the button interface design - ///// - ///// object - ///// EventArgs - //private void btnVwStngs_Click(object sender, EventArgs e) - //{ - // ProcessButtonClick(tiViewStngs, btnVwStngs); - //} - #endregion - #region Generic functions used on this property page /// @@ -570,7 +447,6 @@ namespace VEPROMS ppLblDefSettingsInfo.Visible = ppCbShwDefSettings.Checked; ppLblWatermarkDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefWatermark.Visible; - //ppLblPaginationDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefPagination.Visible; ppLblStpEditorColsDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefEdCols.Visible; ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; ppLblChangeBarTypeDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultChgBar.Visible; @@ -603,7 +479,6 @@ namespace VEPROMS btnGeneral.Checked = false; btnFmtStngs.Checked = false; btnOutputStngs.Checked = false; - //btnVwStngs.Checked = false; } /// @@ -616,7 +491,6 @@ namespace VEPROMS private void tabpage_Enter(object sender, EventArgs e) { // Show or hide the labels containing the default values - //if (!_Initializing) defaultSettingsVisiblity(); } @@ -658,36 +532,11 @@ namespace VEPROMS button.Visible = (cmbx.SelectedValue != null); deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; } - // Commented out as part of code change C2017-004 - select default format on dropdown - ///// - ///// Process a change in the combo box selection - ///// - ///// Combo Box Name - ///// string containing default text - ///// button to reset to default value - ///// label containing the default - //private void ProcessCmbxSelectedValueChange(ComboBoxEx cmbx, string defstr, ButtonX button, Label deflabel) - //{ - // if ((cmbx.SelectedIndex != -1) && defstr != null && defstr.Equals(cmbx.SelectedValue)) - // { - // button.Visible = true; - // button.Focus(); - // button.PerformClick(); - // } - // button.Visible = cmbx.SelectedValue != null; - // deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; - //} #endregion - private void ppProcTitleStpRTB_Enter(object sender, EventArgs e) - { - _MyStepTabRibbon.MyStepRTB = ppProcTitleStpRTB; - } + private void ppProcTitleStpRTB_Enter(object sender, EventArgs e) => _MyStepTabRibbon.MyStepRTB = ppProcTitleStpRTB; - private void ppProcNumStpRTB_Enter(object sender, EventArgs e) - { - _MyStepTabRibbon.MyStepRTB = ppProcNumStpRTB; - } + private void ppProcNumStpRTB_Enter(object sender, EventArgs e) => _MyStepTabRibbon.MyStepRTB = ppProcNumStpRTB; private void ppBtnDefCbTxt1_Click(object sender, EventArgs e) { @@ -698,9 +547,7 @@ namespace VEPROMS _ProcedureConfig.Print_UserCBMess1 = _DefaultChgBarUsrMsg1; ppLblChgBarUserMsgOneDefault.Visible = false; ppBtnDefCbTxt1.Visible = false; - //tcpFormatSettings.Focus(); } - } private void ppBtnDefCbTxt2_Click(object sender, EventArgs e) @@ -712,7 +559,6 @@ namespace VEPROMS _ProcedureConfig.Print_UserCBMess2 = _DefaultChgBarUsrMsg2; ppLblChgBarUserMsgTwoDefault.Visible = false; ppBtnDefCbTxt2.Visible = false; - //tcpFormatSettings.Focus(); } } @@ -723,7 +569,6 @@ namespace VEPROMS if (fc != _ProcedureConfig.Format_Columns) _ProcedureConfig.Format_Columns = fc; // this will force a database update (write) ppCmbxStpEditorCols.SelectedIndex = -1; //reset to the default - //tcpGeneral.Focus(); } private void ppBtnDefWatermark_Click_1(object sender, EventArgs e) @@ -734,30 +579,23 @@ namespace VEPROMS if (wtr != _ProcedureConfig.Print_Watermark) _ProcedureConfig.Print_Watermark = wtr; // this will force a database update (write) ppCmbxWatermark.SelectedIndex = -1; - //tcpOutputSettings.Focus(); } private void ppTxbxChangeBarUserMsgOne_TextChanged(object sender, EventArgs e) { - ppBtnDefCbTxt1.Visible = ((ppTxbxChangeBarUserMsgOne.Text != null) && !ppTxbxChangeBarUserMsgOne.Text.Equals(_DefaultChgBarUsrMsg1)); + ppBtnDefCbTxt1.Visible = (ppTxbxChangeBarUserMsgOne.Text != null) && !ppTxbxChangeBarUserMsgOne.Text.Equals(_DefaultChgBarUsrMsg1); ppLblChgBarUserMsgOneDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefCbTxt1.Visible; - //tcpOutputSettings.Focus(); } private void ppTxbxChgBarUserMsgTwo_TextChanged(object sender, EventArgs e) { ppBtnDefCbTxt2.Visible = ((ppTxbxChgBarUserMsgTwo.Text != null) && !ppTxbxChgBarUserMsgTwo.Text.Equals(_DefaultChgBarUsrMsg2)); ppLblChgBarUserMsgTwoDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefCbTxt2.Visible; - //tcpOutputSettings.Focus(); } - private void frmProcedureProperties_Shown(object sender, EventArgs e) - { - ppProcNumStpRTB.Focus(); - - } + private void frmProcedureProperties_Shown(object sender, EventArgs e) => ppProcNumStpRTB.Focus(); private void ppCmbxFormat_DropDown(object sender, EventArgs e) { diff --git a/PROMS/VEPROMS User Interface/frmPropGrid.cs b/PROMS/VEPROMS User Interface/frmPropGrid.cs index fc03069f..bac237df 100644 --- a/PROMS/VEPROMS User Interface/frmPropGrid.cs +++ b/PROMS/VEPROMS User Interface/frmPropGrid.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 VEPROMS.CSLA.Library; @@ -11,7 +6,7 @@ namespace VEPROMS { public partial class frmPropGrid : DevComponents.DotNetBar.Office2007Form { - private object _PGobject; + private readonly object _PGobject; public frmPropGrid(object pgobject) { @@ -23,24 +18,23 @@ namespace VEPROMS { InitializeComponent(); _PGobject = pgobject; - this.Text = title; + Text = title; } private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; - DocVersionConfig dvcfg = this._PGobject as DocVersionConfig; - if (dvcfg != null && dvcfg.IsDirty) - { - dvcfg.MyDocVersion.Save(); - } - this.Close(); + if (_PGobject is DocVersionConfig dvcfg && dvcfg.IsDirty) + { + dvcfg.MyDocVersion.Save(); + } + Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; - this.Close(); + Close(); } private void frmPropGrid_Load(object sender, EventArgs e) @@ -51,39 +45,23 @@ namespace VEPROMS private void pg_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { - DocVersionConfig dvcfg = this._PGobject as DocVersionConfig; - if (dvcfg != null) - dvcfg.IsDirty = true; - // check if folder config & if so, check for name change - FolderConfig tstfoldercfg = this._PGobject as FolderConfig; - if (tstfoldercfg != null) - { - if ((string)e.OldValue != tstfoldercfg.Name) - { - bool isunique = tstfoldercfg.CheckUniqueName(tstfoldercfg.Name); - if (!isunique) - { - MessageBox.Show(string.Format("The Name '{0}' that was entered is not a unique folder name", tstfoldercfg.Name)); - tstfoldercfg.Name = (string)e.OldValue; - } - } - } - this.Refresh(); + if (_PGobject is DocVersionConfig dvcfg) + dvcfg.IsDirty = true; + // check if folder config & if so, check for name change + if (_PGobject is FolderConfig tstfoldercfg) + { + if ((string)e.OldValue != tstfoldercfg.Name) + { + bool isunique = tstfoldercfg.CheckUniqueName(tstfoldercfg.Name); + if (!isunique) + { + MessageBox.Show(string.Format("The Name '{0}' that was entered is not a unique folder name", tstfoldercfg.Name)); + tstfoldercfg.Name = (string)e.OldValue; + } + } + } + Refresh(); } } - //public partial class SystemConfig - //{ - // FolderConfig _FolderConfig; - // public SystemConfig(FolderConfig folderConfig) - // { - // _FolderConfig = folderConfig; - // //_FolderConfig.Default_SPPrefix; - // } - // public string Default_SPPrefix - // { - // get { return _FolderConfig.Default_SPPrefix; } - // set { _FolderConfig.Default_SPPrefix = value; } - // } - //} } \ No newline at end of file diff --git a/PROMS/VEPROMS User Interface/frmRODbProperties.cs b/PROMS/VEPROMS User Interface/frmRODbProperties.cs index f0381c40..1af79ffb 100644 --- a/PROMS/VEPROMS User Interface/frmRODbProperties.cs +++ b/PROMS/VEPROMS User Interface/frmRODbProperties.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; -using System.Text; using System.Windows.Forms; using System.IO; using VEPROMS.CSLA.Library; @@ -15,13 +12,8 @@ namespace VEPROMS { public partial class frmRODbProperties : Form { - 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.Value = value; @@ -29,54 +21,30 @@ namespace VEPROMS ProgressBar.Text = text; Application.DoEvents(); } - private string InitialProgressBarMessage - { - set - { - if (ProgressBar == null) return; - ProgressBar.Value = 100; - ProgressBar.Maximum = 100; - ProgressBar.Text = value; - Application.DoEvents(); - } - } - private string FinalProgressBarMessage - { - set - { - if (ProgressBar == null) return; - ProgressBar.Value = 100; - ProgressBar.Maximum = 100; - ProgressBar.Text = value; - Application.DoEvents(); - } - } private Point _ParentLocation; public Point ParentLocation { get { return _ParentLocation; } set { _ParentLocation = value; } } - private RODbInfo _roDbInfo; - private string _origROName; - private string _origFolderPath; - private string _origSQLConnect = null; - private DocVersion _docVersion; + private readonly RODbInfo _roDbInfo; + private readonly string _origROName; + private readonly string _origFolderPath; + private readonly string _origSQLConnect = null; + private readonly DocVersion _docVersion; public frmRODbProperties(DocVersion docVersion, RODbInfo roDbInfo) { _roDbInfo = roDbInfo; _docVersion = docVersion; InitializeComponent(); - _origROName = (_roDbInfo == null) ? null : _roDbInfo.ROName; - _origFolderPath = (_roDbInfo == null) ? null : _roDbInfo.FolderPath; + _origROName = _roDbInfo?.ROName; + _origFolderPath = _roDbInfo?.FolderPath; _origSQLConnect = (_roDbInfo == null) ? null : (_roDbInfo.DBConnectionString == null || _roDbInfo.DBConnectionString == "" || _roDbInfo.DBConnectionString == "cstring") ? null : _roDbInfo.DBConnectionString; // Disable the OK button when initialized. Enable it if the user makes changes - ppBtnTestSQL.Visible = ppBtnTestSQL.Enabled = CanMigrateRoAccessToSql(roDbInfo); - ppTxtSQL.Visible = ppTxtSQL.Enabled = CanMigrateRoAccessToSql(roDbInfo); - ppLblSQL.Visible = CanMigrateRoAccessToSql(roDbInfo); + ppBtnTestSQL.Visible = ppBtnTestSQL.Enabled = ppTxtSQL.Visible = ppTxtSQL.Enabled = ppLblSQL.Visible = CanMigrateRoAccessToSql(); ppBtnOk.Enabled = false; } - private bool CanMigrateRoAccessToSql(RODbInfo rODbi) + private bool CanMigrateRoAccessToSql() { // C2017-003: This method is used to determine whether the sql server version can be used & if there is data. // A command line argument 'RoInSql'. For now, this argument must be used to allow code to run for ro->sql. Later @@ -92,10 +60,12 @@ namespace VEPROMS } private void ppBtnFldrDlg_Click(object sender, EventArgs e) { - FolderBrowserDialog dlgROFolder = new FolderBrowserDialog(); - // Initialize the starting location in the Browser window - dlgROFolder.SelectedPath = ppTxtPath.Text; - if (dlgROFolder.ShowDialog() == DialogResult.OK) + FolderBrowserDialog dlgROFolder = new FolderBrowserDialog + { + // Initialize the starting location in the Browser window + SelectedPath = ppTxtPath.Text + }; + if (dlgROFolder.ShowDialog() == DialogResult.OK) { ppTxtPath.Text = dlgROFolder.SelectedPath; } @@ -141,7 +111,7 @@ namespace VEPROMS catch (SqlException) { } } } - catch (Exception ex) {} + catch (Exception) { } if (canconnect) roDb.DBConnectionString = (ppTxtSQL.Text == null || ppTxtSQL.Text == "") ? "cstring" : ppTxtSQL.Text; else @@ -228,7 +198,7 @@ namespace VEPROMS string rofstPath = ppTxtPath.Text + @"\ro.fst"; if (!File.Exists(rofstPath)) { - MessageBox.Show("No existing ro.fst in path " + ppTxtPath.Text + ". Check for invalid path"); + MessageBox.Show($"No existing ro.fst in path {ppTxtPath.Text}. Check for invalid path"); return; } string connectstr = ppTxtSQL.Text != null && ppTxtSQL.Text != "" ? ppTxtExt.Text : "cstring"; @@ -242,8 +212,8 @@ namespace VEPROMS private void frmRODbProperties_Load(object sender, EventArgs e) { Location = ParentLocation; - ppRTxtName.Text = (_roDbInfo == null) ? null : _roDbInfo.ROName; - ppTxtPath.Text = (_roDbInfo == null) ? null : _roDbInfo.FolderPath; + ppRTxtName.Text = _roDbInfo?.ROName; + ppTxtPath.Text = _roDbInfo?.FolderPath; ppTxtSQL.Text = (_roDbInfo == null) ? null : (_roDbInfo.DBConnectionString == "cstring") ? null : _roDbInfo.DBConnectionString; RODbConfig cfg = (_roDbInfo == null) ? new RODbConfig() : new RODbConfig(_roDbInfo); // Note that the Graphic Extension data is shown in a non-editable text box here because @@ -251,15 +221,17 @@ namespace VEPROMS // the file system. Otherwise it is derived from the top node - and changed from folder // properties on the top node. And lastly, it is the code default. ppTxtExt.Text = cfg.GetDefaultGraphicExtension(); - ppLblGraphicFileExtLoc.Text = (cfg == null) ? null : cfg.GetDefaultGraphicExtensionLocation(); + ppLblGraphicFileExtLoc.Text = cfg?.GetDefaultGraphicExtensionLocation(); ppBtnOk.Enabled = false; if (_roDbInfo == null) { string newFolderPath = null; - FolderBrowserDialog dlgROFolder = new FolderBrowserDialog(); - dlgROFolder.RootFolder = Environment.SpecialFolder.MyComputer; - dlgROFolder.SelectedPath = ppTxtPath.Text; - if (dlgROFolder.ShowDialog() == DialogResult.OK) + FolderBrowserDialog dlgROFolder = new FolderBrowserDialog + { + RootFolder = Environment.SpecialFolder.MyComputer, + SelectedPath = ppTxtPath.Text + }; + if (dlgROFolder.ShowDialog() == DialogResult.OK) { newFolderPath = dlgROFolder.SelectedPath; RODbInfoList allRODBs = RODbInfoList.Get(); @@ -275,8 +247,6 @@ namespace VEPROMS } ppTxtPath.Text = newFolderPath; } - // Initialize the enabled status for the OK button to false. - //ppBtnOk.Enabled = false; ppTxtPath.TextChanged += ppTxtPath_TextChanged; } void ppTxtPath_TextChanged(object sender, EventArgs e) @@ -313,7 +283,7 @@ namespace VEPROMS } catch (Exception ex) { - MessageBox.Show("Connection failed: " + ex); + MessageBox.Show($"Connection failed: {ex}"); } } diff --git a/PROMS/VEPROMS User Interface/frmSI.cs b/PROMS/VEPROMS User Interface/frmSI.cs index 2f409572..08e650fa 100644 --- a/PROMS/VEPROMS User Interface/frmSI.cs +++ b/PROMS/VEPROMS User Interface/frmSI.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; @@ -12,14 +10,16 @@ namespace VEPROMS { public partial class frmSI : Form { - private StepTabRibbon _MyStepTabRibbon; - private Dictionary _DicStepRtb; - private Dictionary _DicCheckBox; - private bool DoFolder = true; - private SI SIDialogDef = null; - private string OrigConfig = null; - private FolderInfo MyFolderInfo = null; - private DocVersionInfo MyDocVersionInfo = null; + private readonly StepTabRibbon _MyStepTabRibbon; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicStepRtb; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicCheckBox; + private readonly bool DoFolder = true; + private readonly SI SIDialogDef = null; + private readonly string OrigConfig = null; + private readonly FolderInfo MyFolderInfo = null; + private readonly DocVersionInfo MyDocVersionInfo = null; public frmSI(SI siDialogDef, string config, bool doFolder, FolderInfo fi, DocVersionInfo dvi) { DoFolder = doFolder; @@ -36,22 +36,23 @@ namespace VEPROMS private void InitializeSpecificControls() { - this.Text = SIDialogDef.Caption; - this.Location = new Point((int)SIDialogDef.x * 2, (int)SIDialogDef.y * 2); + Text = SIDialogDef.Caption; + Location = new Point((int)SIDialogDef.x * 2, (int)SIDialogDef.y * 2); int maxx = 0; int maxy = 0; int xB4Scroll = 900; int yB4Scroll = 630; - this.panelSI.AutoScroll = false; + panelSI.AutoScroll = false; foreach (SILabel lbl in SIDialogDef.LabelList) { - Label wlbl = new Label(); - wlbl.Text = lbl.text; - wlbl.Location = new Point((int)lbl.x * 2, (int)lbl.y * 2); - wlbl.AutoSize = true; - //wlbl.Size = new Size((int)lbl.width * 2, (int)lbl.height * 2); - wlbl.Visible = true; - this.panelSI.Controls.Add(wlbl); + Label wlbl = new Label + { + Text = lbl.text, + Location = new Point((int)lbl.x * 2, (int)lbl.y * 2), + AutoSize = true, + Visible = true + }; + panelSI.Controls.Add(wlbl); maxx = ((int)lbl.x * 2 + (int)lbl.width * 2) > maxx ? ((int)lbl.x * 2 + (int)lbl.width * 2) : maxx; maxy = ((int)lbl.y * 2 + (int)lbl.height * 2) > maxy ? ((int)lbl.y * 2 + (int)lbl.height * 2) : maxy; } @@ -70,7 +71,7 @@ namespace VEPROMS // (Removed the frmSI specific contextmenustrip1) tb.FieldToEdit = E_FieldToEdit.PSI; tb.BorderStyle = BorderStyle.FixedSingle; - tb.Enter += new System.EventHandler(this.FieldStepRTB_Enter); + tb.Enter += new System.EventHandler(FieldStepRTB_Enter); // see if config has data for this field, i.e. search for the 'name' // B2019-133 continuation of B2018-057 Replace non-breaking hyphen with hyphen. string val = (DoFolder ? folderConfig.GetValue("SI", fld.name) : dvConfig.GetValue("SI", fld.name)).Replace("\\u8209?", "-"); @@ -78,12 +79,12 @@ namespace VEPROMS StringBuilder sb = new StringBuilder(); sb.Append(@"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset2 Arial;}"); sb.Append(@"{\f1\fnil\fcharset0 Arial;}}{\colortbl ;\red255\green0\blue0;}"); // C2017-036 Microsoft removed Arial Unicode MS with Word16 - sb.Append(@"\viewkind4\uc1\pard\sl-240\slmult0\fs" + (int)(this.Font.SizeInPoints*2) + " " + dt.StartText + @"}"); + sb.Append(@"\viewkind4\uc1\pard\sl-240\slmult0\fs" + (int)(Font.SizeInPoints*2) + " " + dt.StartText + @"}"); tb.Rtf = sb.ToString(); tb.Location = new Point((int)fld.x * 2, (int)fld.y * 2); tb.Size = new Size((int)fld.width * 2, (int)fld.height * 2); tb.Visible = true; - this.panelSI.Controls.Add(tb); + panelSI.Controls.Add(tb); maxx = ((int)fld.x * 2 + (int)fld.width * 2) > maxx ? ((int)fld.x * 2 + (int)fld.width * 2) : maxx; maxy = ((int)fld.y * 2 + (int)fld.height * 2) > maxy ? ((int)fld.y * 2 + (int)fld.height * 2) : maxy; } @@ -96,8 +97,8 @@ namespace VEPROMS cb.Visible = true; cb.Width = (int)fld.width * 2; string val = DoFolder ? folderConfig.GetValue("SI", fld.name) : dvConfig.GetValue("SI", fld.name); - cb.Checked = val!=null && val!="" && val.ToUpper()[0] == 'Y' ? true : false; - this.panelSI.Controls.Add(cb); + cb.Checked = val !=null && val!="" && val.ToUpper()[0] == 'Y'; + panelSI.Controls.Add(cb); maxx = ((int)fld.x * 2 + (int)fld.width * 2) > maxx ? ((int)fld.x * 2 + (int)fld.width * 2) : maxx; maxy = ((int)fld.y * 2 + (int)fld.height * 2) > maxy ? ((int)fld.y * 2 + (int)fld.height * 2) : maxy; } @@ -105,19 +106,19 @@ namespace VEPROMS if (maxx > xB4Scroll) { maxx = xB4Scroll; - this.panelSI.Width = xB4Scroll; - this.panelSI.AutoScroll = true; + panelSI.Width = xB4Scroll; + panelSI.AutoScroll = true; } else - this.panelSI.Width = maxx + 50; + panelSI.Width = maxx + 50; if (maxy > yB4Scroll) { maxy = yB4Scroll; - this.panelSI.Height = yB4Scroll; - this.panelSI.AutoScroll = true; + panelSI.Height = yB4Scroll; + panelSI.AutoScroll = true; } else - this.panelSI.Height = maxy + 50; + panelSI.Height = maxy + 50; if (SIDialogDef.ButtonsOnBottom == null || SIDialogDef.ButtonsOnBottom.ToUpper() == "NO") { btnOk.Location = new Point(maxx+70, 30); @@ -189,29 +190,20 @@ namespace VEPROMS } } DialogResult = DialogResult.OK; - this.Close(); + Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; - this.Close(); + Close(); } - // B2017-024 - added a clip board context menu - private void fwdCMCbCut_Click(object sender, EventArgs e) - { - SendKeys.Send("^x"); // - } + // B2017-024 - added a clip board context menu + private void fwdCMCbCut_Click(object sender, EventArgs e) => SendKeys.Send("^x"); // - private void fwdCMCbCopy_Click(object sender, EventArgs e) - { - SendKeys.Send("^c"); // - } + private void fwdCMCbCopy_Click(object sender, EventArgs e) => SendKeys.Send("^c"); // - private void fwdCMCbPaste_Click(object sender, EventArgs e) - { - SendKeys.Send("^v"); // - } - } + private void fwdCMCbPaste_Click(object sender, EventArgs e) => SendKeys.Send("^v"); // + } } \ No newline at end of file diff --git a/PROMS/VEPROMS User Interface/frmSectionProperties.cs b/PROMS/VEPROMS User Interface/frmSectionProperties.cs index 06ee3ce2..f2ccb8e5 100644 --- a/PROMS/VEPROMS User Interface/frmSectionProperties.cs +++ b/PROMS/VEPROMS User Interface/frmSectionProperties.cs @@ -1,9 +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 VEPROMS.CSLA.Library; using VEPROMS.Properties; @@ -12,6 +8,7 @@ using DevComponents.DotNetBar.Controls; using Volian.Controls.Library; using DescriptiveEnum; using System.IO; +using System.Linq; namespace VEPROMS { @@ -20,11 +17,10 @@ namespace VEPROMS private string _DefaultFormatName = null; private string _DefaultNumColumns = null; private string _DefaultPaginationStyle = null; - private string _DefaultPrintSize = null; private bool _Initializing; - private SectionConfig _SectionConfig; - private Document _DocumentToDelete = null; - private StepTabRibbon _MyStepTabRibbon; + private readonly SectionConfig _SectionConfig; + private Document _DocumentToDelete = null; + private readonly StepTabRibbon _MyStepTabRibbon; private bool _isStepSection = true; private bool _hasSectionCheckoffDefault = false; private bool _isDefaultStepSection = false; @@ -35,36 +31,30 @@ namespace VEPROMS InitializeComponent(); btnGeneral.PerformClick(); // always start with General tab or button ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID); - //if (sectionConfig.Number.Length > 0) - // this.Text = string.Format("{0} {1} Properties", sectionConfig.Number, sectionConfig.Title); - //else - // this.Text = string.Format("{0} Properties", sectionConfig.Title); if (sectionConfig.Number.Length > 0) - this.Text = string.Format("{0} {1} Properties", ii.DisplayNumber, ii.DisplayText); + Text = $"{ii.DisplayNumber} {ii.DisplayText} Properties"; else - this.Text = string.Format("{0} Properties", ii.DisplayText); + Text = $"{ii.DisplayText} Properties"; ppSectTitleStpRTB.Font = ppSectTitleStpRTB.FormatFont = new System.Drawing.Font("Microsoft Sans Serif", 10F); ppSectTitleStpRTB.FieldToEdit = E_FieldToEdit.Text; ppSectTitleStpRTB.BorderStyle = BorderStyle.Fixed3D; ppSectTitleStpRTB.MyItemInfo = ii; ppSectTitleStpRTB.RefreshDisplay(true); - ppSectNumberStpRTB.Font = this.ppSectNumberStpRTB.FormatFont = new System.Drawing.Font("Microsoft Sans Serif", 10F); + ppSectNumberStpRTB.Font = ppSectNumberStpRTB.FormatFont = new System.Drawing.Font("Microsoft Sans Serif", 10F); ppSectNumberStpRTB.FieldToEdit = E_FieldToEdit.Number; ppSectNumberStpRTB.BorderStyle = BorderStyle.Fixed3D; ppSectNumberStpRTB.MyItemInfo = ii; ppSectNumberStpRTB.RefreshDisplay(true); - _MyStepTabRibbon = new StepTabRibbon(); - //_MyStepTabRibbon.Dock = System.Windows.Forms.DockStyle.Top; - //_MyStepTabRibbon.Location = new System.Drawing.Point(0, 0); - _MyStepTabRibbon.Name = "displayTabRibbon1"; - _MyStepTabRibbon.Visible = false; + _MyStepTabRibbon = new StepTabRibbon + { + Name = "displayTabRibbon1", + Visible = false + }; // B2017-272 disable/enable the Steps and Word radio buttons based on the section types defined in the format // and the type of an existing section or if we are creating a new section. // Move the check of creating a new section into CheckAvailableSectionTypes() CheckAvaibleSectionTypes(); - //// if creating a new section, enable the StepSect and WordSect radio buttons - //rbStepSect.Enabled = rbWordSect.Enabled = !(ii.HasWordContent || ii.HasStepContent); // if this is an auto table of contents (mydocstyle == null if new section, so must check for that first) if (ii.IsAutoTOCSection) @@ -181,15 +171,14 @@ namespace VEPROMS { // find first section in list that has originalsteps (flags a default section) int defsctId = 0; - foreach (SectionInfo si in _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections) + foreach (SectionInfo si in _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections.OfType()) { - SectionConfig sc = si.MyConfig as SectionConfig; - if (si.ItemID != _SectionConfig.MySection.ItemID && sc != null && sc.Section_OriginalSteps == "Y") - { - defsctId = si.ItemID; - break; - } - } + if (si.ItemID != _SectionConfig.MySection.ItemID && si.MyConfig is SectionConfig sc && sc.Section_OriginalSteps == "Y") + { + defsctId = si.ItemID; + break; + } + } if (defsctId != 0) { // also need to set the procedure's config sectionstart to the selected section @@ -209,19 +198,18 @@ namespace VEPROMS // this property set - it is used when printing page numbers with 'WithSteps' numbering sequence. else if (!_isDefaultStepSection && ppCbDefaultStepSection.Checked) { - foreach (SectionInfo si in _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections) + foreach (SectionInfo si in _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections.OfType()) { - SectionConfig sc = si.MyConfig as SectionConfig; - if (si.ItemID != _SectionConfig.MySection.ItemID && sc != null && sc.Section_OriginalSteps == "Y") - { - using (Section ssav = si.Get()) - { - ssav.SectionConfig.Section_OriginalSteps = "N"; - ssav.Save(); - ItemInfo.Refresh(ssav); - } - } - } + if (si.ItemID != _SectionConfig.MySection.ItemID && si.MyConfig is SectionConfig sc && sc.Section_OriginalSteps == "Y") + { + using (Section ssav = si.Get()) + { + ssav.SectionConfig.Section_OriginalSteps = "N"; + ssav.Save(); + ItemInfo.Refresh(ssav); + } + } + } // also need to set the procedure's config sectionstart to the selected section // if it is not set: using (Procedure p = Procedure.Get(_SectionConfig.MySection.MySectionInfo.MyProcedure.ItemID)) @@ -253,8 +241,8 @@ namespace VEPROMS } } } - this.DialogResult = DialogResult.OK; - this.Close(); + DialogResult = DialogResult.OK; + Close(); } public void SaveText(StepRTB myStepRTB) { @@ -269,7 +257,7 @@ namespace VEPROMS myStepRTB.ClearUndo(); } } - //private static void FinishSectionSave(Section section) + private void FinishSectionSave(Section section) { ItemInfo sectinfo = ItemInfo.Get(section.ItemID); @@ -305,7 +293,7 @@ namespace VEPROMS _DocumentToDelete = null; sectionConfigBindingSource.CancelEdit(); DialogResult = DialogResult.Cancel; - this.Close(); + Close(); } /// @@ -320,12 +308,6 @@ namespace VEPROMS // Get the default format name _DefaultFormatName = _SectionConfig.DefaultFormatSelection; SetupDefault(_DefaultFormatName, ppLblFormatDefault, ppCmbxFormat); - //if (_DefaultFormatName != null && !(_DefaultFormatName.Equals(""))) - //{ - // string defName = string.Format("{0}", _DefaultFormatName); - // ppLblFormatDefault.Text = defName; - // ppCmbxFormat.WatermarkText = defName; - //} SectionConfig.SectionColumnMode sc = _SectionConfig.Section_ColumnMode; _DefaultNumColumns = sc.ToString(); SetupDefault(EnumDescConverter.GetEnumDescription(sc), ppLblDefaultNumColumns, ppCmbxNumColumns); @@ -333,8 +315,6 @@ namespace VEPROMS //Console.WriteLine("{0}, {1}, default pagination", _SectionConfig.MySection.DisplayNumber, sp); _DefaultPaginationStyle = sp.ToString(); SetupDefault(EnumDescConverter.GetEnumDescription(sp), ppLblDefPaginationStyle, ppCmbxSectPagination); - //_DefaultPrintSize = _SectionConfig.Section_AttachmentPrintSize.ToString(); - //SetupDefault(EnumDescConverter.GetEnumDescription(_SectionConfig.Section_AttachmentPrintSize), ppLblDefaultPrintSize, ppCmbxAccPgPrintSize); _SectionConfig.ParentLookup = false; } @@ -349,7 +329,7 @@ namespace VEPROMS { if (defaultText != null && !(defaultText.Equals(""))) { - string deftext = string.Format("{0}", defaultText); + string deftext = $"{defaultText}"; lbl.Text = deftext; cmbo.WatermarkText = deftext; } @@ -365,7 +345,7 @@ namespace VEPROMS ppCmbxFormat.DisplayMember = "FullName"; ppCmbxFormat.ValueMember = "FullName"; ppCmbxFormat.DataSource = FormatUtility.GetFilteredFormatList(FormatInfoList.SortedFormatInfoList); - if (_SectionConfig.MySection.MySectionInfo.ActiveFormat != null) _cmbxformatOriginal = (int)_SectionConfig.MySection.MySectionInfo.ActiveFormat.FormatID; + if (_SectionConfig.MySection.MySectionInfo.ActiveFormat != null) _cmbxformatOriginal = (int)_SectionConfig.MySection.MySectionInfo.ActiveFormat.FormatID; if (_SectionConfig.FormatSelection != null) ppCmbxFormat.SelectedValue = _SectionConfig.FormatSelection; else @@ -373,7 +353,7 @@ namespace VEPROMS // Get the saved settings for this user // // Get setting telling us whether to display the default values on this property page - ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultSectionProp"] != null) ? Settings.Default.ShowDefaultSectionProp : false; + ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultSectionProp"] != null) && Settings.Default.ShowDefaultSectionProp; // Get the User's property page style "PropPageStyle" (this is a system wide user setting) // 1 - Button Dialog (default) @@ -382,7 +362,7 @@ namespace VEPROMS { tcSectionProp.TabsVisible = true; panSectBtns.Visible = false; - this.Width -= panSectBtns.Width; + Width -= panSectBtns.Width; } // Get the default values for the property page information @@ -419,24 +399,10 @@ namespace VEPROMS ppBtnDefaultNumColumns.Visible = false; ppCmbxNumColumns.SelectedValueChanged += new EventHandler(ppCmbxNumColumns_SelectedValueChanged); - //ppCmbxAccPgPrintSize.DataSource = EnumDetail.Details(); - //ppCmbxAccPgPrintSize.DisplayMember = "Description"; - //ppCmbxAccPgPrintSize.ValueMember = "Evalue"; - //ppCmbxAccPgPrintSize.SelectedIndex = -1; - if (!_isStepSection) ppCmbxLibDocFill(); - // check type of section from document styles to determine if the stepsection checkbox should - // be checked. - //int secindx = (int)_SectionConfig.SectionType; - //// find the index for the document style to determine whether this is a step or word section. PlantFormat pf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat; - //for (int i = 0; i < pf.DocStyles.DocStyleList.Count; i++) - //{ - // if (pf.DocStyles.DocStyleList[i].Index == secindx) - // rbStepSect.Checked = pf.DocStyles.DocStyleList[i].IsStepSection; _SectionConfig.MySection. - //} // set the StepSect radio button based on _isStepSection to ensure the proper section types are available rbStepSect.Checked = _isStepSection; @@ -455,7 +421,6 @@ namespace VEPROMS // show the automatic indent checkbox. ppCbEditableData.Enabled = _SectionConfig.MySection.MySectionInfo.Sections != null && _SectionConfig.MySection.MySectionInfo.Sections.Count > 0; ppCbEditableData.Visible = _isStepSection; // only display if we are on a step editor section - //ppCbAutoIndent.Enabled = _SectionConfig.MySection.MySectionInfo.Sections != null && _SectionConfig.MySection.MySectionInfo.Sections.Count > 0; ppCbAutoIndent.Enabled = pf.FormatData.SectData.UseMetaSections; ppCbAutoIndent.Visible = _isStepSection; // only display if we are on a step editor section @@ -493,8 +458,6 @@ namespace VEPROMS ppCbPlaceKeeper.Enabled = _isStepSection; if (!_isStepSection && (_SectionConfig.MySection.MySectionInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.Placekeeper) == E_DocStructStyle.Placekeeper) { - //ppCbPlaceKeeper.Text = "Auto Generate Placekeeper"; - //ppCbPlaceKeeper.Enabled = true; ppCbPlaceKeeper.Enabled = false; } if (ppCbPlaceKeeper.Enabled) ppCbPlaceKeeper.Checked = _SectionConfig.Section_Placekeeper == "Y"; @@ -606,7 +569,7 @@ namespace VEPROMS ppBtnConvertToDocX.Visible = false; // Don't allow save as DOCX for libraries documents ppBtnCvrtToLibDoc.Text = "Convert this Section To A Non-Library Document"; lblLibraryDocument.Text = "Library Document"; - superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Non-Library Document", "", "This button will convert the current section from a library document to a non-library document", + superTooltip1.SetSuperTooltip(ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Non-Library Document", "", "This button will convert the current section from a library document to a non-library document", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76))); } else @@ -616,17 +579,17 @@ namespace VEPROMS { ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID); if (!ii.IsAutoTOCSection) // Only show the Convert To DocX button for non-Auto Table Of Contents Section - this.ppBtnConvertToDocX.Visible = true; // Only allow save as DocX for normal word sections when the existing text is RTF. + ppBtnConvertToDocX.Visible = true; // Only allow save as DocX for normal word sections when the existing text is RTF. } else - this.ppBtnConvertToDocX.Visible = false; + ppBtnConvertToDocX.Visible = false; if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument == null) ppBtnCvrtToLibDoc.Visible = false; else { ppBtnCvrtToLibDoc.Text = "Convert this to a Library Document"; lblLibraryDocument.Text = "Select Library Document"; - superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Library Document button", "", "This button will convert the current section to a library document, allowing it t" + + superTooltip1.SetSuperTooltip(ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Library Document button", "", "This button will convert the current section to a library document, allowing it t" + "o be shared with other procedures.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76))); } } @@ -694,12 +657,11 @@ namespace VEPROMS int oldSelIndx = -1; if (!myInit) { - DocStyleList oldDocStyles = null; - opf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat; + opf = _SectionConfig.MyFormat != null ? _SectionConfig.MyFormat.PlantFormat : _SectionConfig.MyDefaultFormat.PlantFormat; if (pf != opf) { - oldDocStyles = new DocStyleList(null); - foreach (DocStyle ds in opf.DocStyles.DocStyleListActive) + DocStyleList oldDocStyles = new DocStyleList(null); + foreach (DocStyle ds in opf.DocStyles.DocStyleListActive) { if (_isStepSection && ds.IsStepSection) oldDocStyles.Add(ds); // find only step section types @@ -786,7 +748,8 @@ namespace VEPROMS } } private List SectionPropertyCheckOffList = null; - 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 SetupCheckoffsDropdowns() { if (!_isStepSection) return; // not needed for accessory pages (word attachments) @@ -794,7 +757,7 @@ namespace VEPROMS _Initializing = true; PlantFormat pf = _SectionConfig.MyFormat!=null?_SectionConfig.MyFormat.PlantFormat:_SectionConfig.MyDefaultFormat.PlantFormat; CheckOffList chkoffList = pf.FormatData.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 CheckOffHeaderList chkoffHeaderList = pf.FormatData.ProcData.CheckOffData.CheckOffHeaderList; int maxindx = pf.FormatData.ProcData.CheckOffData.CheckOffList.MaxIndexNoInherit; // B2019-013: was crashing on indexer of checkofflist. If there were UCF checkoffs but none in original format, the indexer @@ -815,10 +778,9 @@ namespace VEPROMS if (chkoffList != null && maxindx > 0 && (pf.FormatData.ProcData.CheckOffData.Menu == "Signoff") || _hasSectionCheckoffDefault) { - if (SectionPropertyCheckOffList!=null)SectionPropertyCheckOffList.Clear(); + SectionPropertyCheckOffList?.Clear(); SectionPropertyCheckOffList = new List(); // Don't put up the first item in the chkoffList, it is '{Section Default}'. - //for (int i = 1; i < chkoffList.Count; i++) int idxcnt = 0; int translatedCfgIdx = 0; _CheckOffIndex.Clear(); @@ -882,7 +844,7 @@ namespace VEPROMS { string suffix = "format "; if (_DefaultFormatName.ToUpper().Contains("FORMAT")) suffix = ""; - MessageBox.Show(string.Format("{0}\n\n{1}does not support {2} section type", _DefaultFormatName, suffix, isWordSection ? "MS Word" : "Step"), "Incompatible Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show($"{_DefaultFormatName}\n\n{suffix}does not support {(isWordSection ? "MS Word" : "Step")} section type", "Incompatible Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } @@ -918,7 +880,6 @@ namespace VEPROMS // determine if the default button and the default description text should visable ppBtnDefaultFmt.Visible = !(ppCmbxFormat.SelectedValue == null || ppCmbxFormat.SelectedIndex == -1); ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; - //if (!didDefault) SetupPpCmbxSectionType(); SetupPpCmbxSectionType(); // B2017-272 disable/enable the Steps and Word radio buttons based on the section types defined in the format // and the type of an existing section or if we are creating a new section. @@ -940,7 +901,7 @@ namespace VEPROMS return true; // valid format string suffix = "format "; if (ppCmbxFormat.SelectedValue.ToString().ToUpper().Contains("FORMAT")) suffix = ""; - MessageBox.Show(string.Format("{0}\n\n{1}does not support {2} section type", ppCmbxFormat.SelectedValue, suffix, isWordSection ? "MS Word" : "Step"), "Incompatible Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show($"{ppCmbxFormat.SelectedValue}\n\n{suffix}does not support {(isWordSection ? "MS Word" : "Step")} section type", "Incompatible Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } @@ -951,20 +912,17 @@ namespace VEPROMS _SectionConfig.SectionType = (int)(ppCmbxStyleSectionType.SelectedValue); } - #endregion + #endregion - #region Library Document tab + #region Library Document tab - /// - /// This is the Library Document button used on the button interface design - /// - /// object - /// EventArgs - private void btnLibDocs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiLibDoc, btnLibDocs); - } - private void ppBtnCvrtToLibDoc_Click(object sender, EventArgs e) + /// + /// This is the Library Document button used on the button interface design + /// + /// object + /// EventArgs + private void btnLibDocs_Click(object sender, EventArgs e) => ProcessButtonClick(tiLibDoc, btnLibDocs); + private void ppBtnCvrtToLibDoc_Click(object sender, EventArgs e) { // Double Check that this is not a step section, if so just return. if (_isStepSection) return; @@ -995,7 +953,7 @@ namespace VEPROMS ppCmbxLibDoc.Items.Clear(); ppCmbxLibDoc.WatermarkEnabled = true; ppBtnCvrtToLibDoc.Text = "Convert this to a Library Document"; - superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Library Document button", "", "This button will convert the current section to a library document, allowing it t" + + superTooltip1.SetSuperTooltip(ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Library Document button", "", "This button will convert the current section to a library document, allowing it t" + "o be shared with other procedures.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76))); return; } @@ -1038,7 +996,7 @@ namespace VEPROMS } ppBtnCvrtToLibDoc.Text = "Convert this Section To A Non-Library Document"; lblLibraryDocument.Text = "Library Document"; - superTooltip1.SetSuperTooltip(this.ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Non-Library Document", "", "This button will convert the current section from a library document to a non-library document", + superTooltip1.SetSuperTooltip(ppBtnCvrtToLibDoc, new DevComponents.DotNetBar.SuperTooltipInfo("Convert To Non-Library Document", "", "This button will convert the current section from a library document to a non-library document", null, null, DevComponents.DotNetBar.eTooltipColor.Gray, true, false, new System.Drawing.Size(250, 76))); } @@ -1070,11 +1028,6 @@ namespace VEPROMS } } - //else if (_SectionConfig.MySection.MyContent.MyEntry.MyDocument == null) - //{ - // // was creating a new document & selected to connect it to a libdoc - // _DocumentToDelete = _SectionConfig.MySection.MyContent.MyEntry.MyDocument; - //} else { // it already is a library document, just change usages... @@ -1086,34 +1039,30 @@ namespace VEPROMS } else { - throw new Exception(string.Format("Index Out Of Range Index = {0}, Count = {1}", ppCmbxLibDoc.SelectedIndex, LibDocList.Count)); + throw new Exception($"Index Out Of Range Index = {ppCmbxLibDoc.SelectedIndex}, Count = {LibDocList.Count}"); } } } - #endregion + #endregion - #region View Settings tab + #region View Settings tab - /// - /// This is the View Settings button used on the button interface design - /// - /// object - /// EventArgs - private void btnAutomation_Click(object sender, EventArgs e) + /// + /// This is the View Settings button used on the button interface design + /// + /// object + /// EventArgs + private void btnAutomation_Click(object sender, EventArgs e) => ProcessButtonClick(tiAutomation, btnAutomation); + + #endregion + + #region Generic functions used on this property page + + /// + /// Determines what labels (showing default values) are visable on the property pages + /// + private void defaultSettingsVisiblity() { - ProcessButtonClick(tiAutomation, btnAutomation); - } - - #endregion - - #region Generic functions used on this property page - - /// - /// Determines what labels (showing default values) are visable on the property pages - /// - private void defaultSettingsVisiblity() - { - //ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID); ppLblDefSettingsInfo.Visible = ppCbShwDefSettings.Checked; ppLblFormatDefault.Visible = ppCbShwDefSettings.Checked && ppBtnDefaultFmt.Visible; ppLblDefaultNumColumns.Visible = _isStepSection && ppCbShwDefSettings.Checked && ppBtnDefaultNumColumns.Visible; @@ -1160,26 +1109,7 @@ namespace VEPROMS private void tabpage_Enter(object sender, EventArgs e) { // Show or hide the labels containing the default values - //if (!_Initializing) // jsj 1-23-2017 was not showing default check upon property page entry - defaultSettingsVisiblity(); - } - /// - /// Process a change in the combo box selection - /// - /// Combo Box Name - /// string containing default text - /// button to reset to default value - /// label containing the default - private void ProcessCmbxSelectedValueChange(ComboBoxEx cmbx, string defstr, ButtonX button, Label deflabel) - { - if ((cmbx.SelectedIndex != -1) && defstr != null && defstr.Equals(cmbx.SelectedValue)) - { - button.Visible = true; - button.Focus(); - button.PerformClick(); - } - button.Visible = (cmbx.SelectedValue != null); - deflabel.Visible = (ppCbShwDefSettings.Checked) && button.Visible; + defaultSettingsVisiblity(); } /// /// Process a change in the enum combo box selection @@ -1201,30 +1131,21 @@ namespace VEPROMS cmbx.SelectedIndex = -1; // This will hide the Default button _Initializing = sav_Initializing; } - //button.Visible = ((!_FolderConfig.Name.Equals("VEPROMS")) && (cmbx.SelectedValue != null)); button.Visible = ((cmbx.SelectedValue != null) && (cmbx.SelectedIndex >= 0)); deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; } - #endregion + #endregion - private void ppSectNumberStpRTB_Enter(object sender, EventArgs e) - { - _MyStepTabRibbon.MyStepRTB = ppSectNumberStpRTB; - } + private void ppSectNumberStpRTB_Enter(object sender, EventArgs e) => _MyStepTabRibbon.MyStepRTB = ppSectNumberStpRTB; - private void ppSectTitleStpRTB_Enter(object sender, EventArgs e) - { - _MyStepTabRibbon.MyStepRTB = ppSectTitleStpRTB; - } + private void ppSectTitleStpRTB_Enter(object sender, EventArgs e) => _MyStepTabRibbon.MyStepRTB = ppSectTitleStpRTB; - private void ShowAvailableOptionsForSectionType() + private void ShowAvailableOptionsForSectionType() { lblColumns.Visible = _isStepSection; ppCmbxNumColumns.Visible = _isStepSection; lblPagination.Visible = _isStepSection; ppCmbxSectPagination.Visible = _isStepSection; - //lblPrintSize.Visible = !_isStepSection; - //ppCmbxAccPgPrintSize.Visible = !_isStepSection; ppGpbxSignoffCheckoff.Visible = _isStepSection; cbKeepWordDocMargins.Visible = !_isStepSection; ppCbDefaultStepSection.Visible = _isStepSection; @@ -1257,12 +1178,6 @@ namespace VEPROMS tcpFormat.Focus(); } - //private void ppCmbxAccPgPrintSize_SelectedValueChanged(object sender, EventArgs e) - //{ - // SectionConfig.AttPrintSize attsize = (SectionConfig.AttPrintSize)Enum.Parse(typeof(SectionConfig.AttPrintSize), _DefaultPrintSize); - // ProcessCmbxSelectionEnumChanged(ppCmbxAccPgPrintSize, attsize, ppBtnDefaultPrintSize, ppLblDefaultPrintSize); - //} - private void ppBtnDefaultPaginationStyle_Click(object sender, EventArgs e) { // Get the parent setting @@ -1285,12 +1200,9 @@ namespace VEPROMS tcpFormat.Focus(); } - private void frmSectionProperties_Shown(object sender, EventArgs e) - { - ppSectNumberStpRTB.Focus(); - } + private void frmSectionProperties_Shown(object sender, EventArgs e) => ppSectNumberStpRTB.Focus(); - private void ppCbEditableData_CheckedChanged(object sender, EventArgs e) + private void ppCbEditableData_CheckedChanged(object sender, EventArgs e) { bool isEditable = ppCbEditableData.Checked; if (!_Initializing) @@ -1353,7 +1265,7 @@ namespace VEPROMS int cntDefaultSect = 0; string defSectDesc = ""; string curSectDesc = ""; - foreach (SectionInfo si in _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections) + foreach (SectionInfo si in _SectionConfig.MySection.MySectionInfo.MyProcedure.Sections.OfType()) { SectionConfig sc = si.MyConfig as SectionConfig; if (sc != null && sc.Section_OriginalSteps == "Y") @@ -1405,10 +1317,6 @@ namespace VEPROMS ItemInfo ii = ItemInfo.Get(_SectionConfig.MySection.ItemID); DocumentInfo doclibinfo = ii.MyContent.MyEntry.MyDocument; DSOFile myfile = new DSOFile(doclibinfo); - // When trying to fix this , the update of the document waas causing a CSLA crash so I switched - // to make document - //using (Document myDoc = doclibinfo.Get()) - //{ // Open MSWord App LBWordLibrary.LBApplicationClass ap = new LBWordLibrary.LBApplicationClass(); LBWordLibrary.LBDocumentClass doc = ap.Documents.Open(myfile.FullName); @@ -1420,17 +1328,13 @@ namespace VEPROMS FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);// B2016-053 long len = fs.Length; byte[] ByteArray = new byte[len]; - int nBytesRead = fs.Read(ByteArray, 0, (int)len); + _ = fs.Read(ByteArray, 0, (int)len); fs.Close(); Document myDoc = Document.MakeDocument(null, ByteArray, doclibinfo.DocAscii, doclibinfo.Config, ".DOCX"); _SectionConfig.MySection.MyContent.MyEntry.MyDocument = myDoc; _SectionConfig.MySection.MyContent.MyEntry.Save(); - //myDoc.DocContent = ByteArray; - //myDoc.FileExtension = ".DOCX"; - //myDoc.Save(); fi.Delete();// Cleanup afterwards ppBtnConvertToDocX.Visible = false; // Hide the button after the execution is complete. - //} } private void ppCmbxFormat_DropDown(object sender, EventArgs e) @@ -1460,14 +1364,11 @@ namespace VEPROMS _SectionConfig.Section_IsFoldout = (cbIsFoldoutSection.Checked) ? "Y" : "N"; } - // B2019-165 check box added to Automation tab to prevent a duplex foldout from - // being printed on the back of the last page of the Word document that does not include duplex foldouts - private void ppCbNoDuplexFoldout_CheckedChanged(object sender, EventArgs e) - { - _SectionConfig.Section_DontIncludeDuplexFoldout = ppCbNoDuplexFoldout.Checked; - } - // C2029-025 Show or hide replace words. Can highlight replace words in editor. - private void ppCbShowRplWords_CheckedChanged(object sender, EventArgs e) + // B2019-165 check box added to Automation tab to prevent a duplex foldout from + // being printed on the back of the last page of the Word document that does not include duplex foldouts + private void ppCbNoDuplexFoldout_CheckedChanged(object sender, EventArgs e) => _SectionConfig.Section_DontIncludeDuplexFoldout = ppCbNoDuplexFoldout.Checked; + // C2029-025 Show or hide replace words. Can highlight replace words in editor. + private void ppCbShowRplWords_CheckedChanged(object sender, EventArgs e) { if (!_Initializing) { @@ -1475,15 +1376,5 @@ namespace VEPROMS } } - //private void ppBtnDefaultPrintSize_Click(object sender, EventArgs e) - //{ - // // Get the parent setting - // SectionConfig.AttPrintSize attsize = (SectionConfig.AttPrintSize)Enum.Parse(typeof(SectionConfig.AttPrintSize), _DefaultPrintSize); - // // Compare parent setting with current setting - // if (attsize != _SectionConfig.Section_AttachmentPrintSize) - // _SectionConfig.Section_AttachmentPrintSize = attsize; // this will force a database update (write) - // ppCmbxAccPgPrintSize.SelectedIndex = -1;//reset to the default Accessory page Print Size setting - // tcpFormat.Focus(); - //} } } diff --git a/PROMS/VEPROMS User Interface/frmSysOptions.cs b/PROMS/VEPROMS User Interface/frmSysOptions.cs index 7d6fd3a2..e7200866 100644 --- a/PROMS/VEPROMS User Interface/frmSysOptions.cs +++ b/PROMS/VEPROMS User Interface/frmSysOptions.cs @@ -1,32 +1,21 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Text; using System.Windows.Forms; -using DevComponents; using DevComponents.DotNetBar.Rendering; using DevComponents.DotNetBar; using VEPROMS.Properties; using Volian.Base.Library; -using DescriptiveEnum; using VEPROMS.CSLA.Library; namespace VEPROMS { public partial class frmSysOptions : DevComponents.DotNetBar.Office2007Form { - bool _initializing; - private bool _CanChangeSeparateWindowsSetting = true; + readonly bool _initializing; - public bool CanChangeSeparateWindowsSetting - { - get { return _CanChangeSeparateWindowsSetting; } - set { _CanChangeSeparateWindowsSetting = value; } - } + public bool CanChangeSeparateWindowsSetting { get; set; } = true; - private UserSettings _usersettings; + private UserSettings _usersettings; public frmSysOptions() { @@ -160,8 +149,8 @@ namespace VEPROMS //C2025-013 - Allow not continuously generate message that opening Summaries in MS Word _usersettings.SetUserSetting_MSWord_Summary_Prompt(cbMSWordPrompt.Checked); - this.DialogResult = DialogResult.OK; - this.Close(); + DialogResult = DialogResult.OK; + Close(); } private int ss_propPageStyle; @@ -197,7 +186,7 @@ namespace VEPROMS private void RestoreStartingSettings() // used with the cancel button { Settings.Default.PropPageStyle = ss_propPageStyle; - Settings.Default.SystemColor = ss_SystemColor; + Settings.Default.SystemColor = ss_SystemColor; Settings.Default.TransitionRangeColor = ss_TransRangeColor; Settings.Default.AutoPopUpAnnotations = ss_PopUPAnnotations; Settings.Default.StepTypeToolTip = ss_StepTypeToolTip; @@ -255,52 +244,30 @@ namespace VEPROMS } } - private void cbAnnotationPopup_CheckedChanged(object sender, EventArgs e) - { - Settings.Default.AutoPopUpAnnotations = cbAnnotationPopup.Checked; - } + private void cbAnnotationPopup_CheckedChanged(object sender, EventArgs e) => Settings.Default.AutoPopUpAnnotations = cbAnnotationPopup.Checked; - private void frmSysOptions_Load(object sender, EventArgs e) + private void frmSysOptions_Load(object sender, EventArgs e) { ClearAllCheckedButtons(); tcSysOpts.SelectedTab = tiIntrFaceStngs; btnIntrFaceStngs.Checked = true; - gpSeparateWindows.Enabled = CanChangeSeparateWindowsSetting; //Separate Windows only if one or less procedure sets open - } + gpSeparateWindows.Enabled = CanChangeSeparateWindowsSetting; //Separate Windows only if one or less procedure sets open + } private void cbStepTypeToolTip_CheckedChanged(object sender, EventArgs e) { Settings.Default.StepTypeToolTip = cbStepTypeToolTip.Checked; VlnSettings.StepTypeToolTip = cbStepTypeToolTip.Checked; } - private void cbTVExpand_CheckedChanged(object sender, EventArgs e) - { - Settings.Default.SaveTreeviewExpanded = cbTVExpand.Checked; - } - private void cbSeparateWindows_CheckedChanged(object sender, EventArgs e) - { - Settings.Default.SeparateWindows = cbSeparateWindows.Checked; - } - private void txbxVisioPath_Leave(object sender, EventArgs e) - { - Settings.Default.VisioPath = txbxVisioPath.Text; - } + private void cbTVExpand_CheckedChanged(object sender, EventArgs e) => Settings.Default.SaveTreeviewExpanded = cbTVExpand.Checked; + private void cbSeparateWindows_CheckedChanged(object sender, EventArgs e) => Settings.Default.SeparateWindows = cbSeparateWindows.Checked; + private void txbxVisioPath_Leave(object sender, EventArgs e) => Settings.Default.VisioPath = txbxVisioPath.Text; - private void btnCancel_Click(object sender, EventArgs e) - { - RestoreStartingSettings(); - } + private void btnCancel_Click(object sender, EventArgs e) => RestoreStartingSettings(); - private void txbxVisioPath_Leave_1(object sender, EventArgs e) - { - Settings.Default.VisioPath = txbxVisioPath.Text; - } + private void txbxVisioPath_Leave_1(object sender, EventArgs e) => Settings.Default.VisioPath = txbxVisioPath.Text; - - private void cbOTRemember_CheckedChanged(object sender, EventArgs e) - { - cbOTAutoOpen.Enabled = cbOTAutoOpen.Visible = cbShwRplWrdsColor.Checked; - } - private void cbShwRplWrdsColor_CheckedChanged(object sender, EventArgs e) + private void cbOTRemember_CheckedChanged(object sender, EventArgs e) => cbOTAutoOpen.Enabled = cbOTAutoOpen.Visible = cbShwRplWrdsColor.Checked; + private void cbShwRplWrdsColor_CheckedChanged(object sender, EventArgs e) { Settings.Default.cbShwRplWrdsColor = cbShwRplWrdsColor.Checked; VlnSettings.cbShwRplWrdsColor = cbShwRplWrdsColor.Checked; @@ -308,10 +275,7 @@ namespace VEPROMS Properties.Settings.Default.Save(); // save settings } - private void cbShwAnnoFilter_Click(object sender, EventArgs e) - { - frmVEPROMS.tv_SelectAnnotations(); - } + private void cbShwAnnoFilter_Click(object sender, EventArgs e) => frmVEPROMS.tv_SelectAnnotations(); - } + } } \ No newline at end of file diff --git a/PROMS/VEPROMS User Interface/frmVEPROMS.cs b/PROMS/VEPROMS User Interface/frmVEPROMS.cs index dd1ce0e3..744327a8 100644 --- a/PROMS/VEPROMS User Interface/frmVEPROMS.cs +++ b/PROMS/VEPROMS User Interface/frmVEPROMS.cs @@ -39,17 +39,12 @@ namespace VEPROMS StepTabPanel _SelectedStepTabPanel = null; public FindReplace dlgFindReplace = null; public VlnSpellCheck SpellChecker = null; - private Int64 _LastContentChange; - public Int64 LastContentChange - { - get { return _LastContentChange; } - set { _LastContentChange = value; } - } + public long LastContentChange { get; set; } - public void RefreshLastChange() + public void RefreshLastChange() { - lblLastChange.Text = string.Format("Last Change: {0}", MySessionInfo.LastContentChange - this.LastContentChange); + lblLastChange.Text = $"Last Change: {MySessionInfo.LastContentChange - LastContentChange}"; } public StepTabPanel SelectedStepTabPanel @@ -71,10 +66,6 @@ namespace VEPROMS } else // Step Tab Panel { - // The following line was broken into separate lines because a NullReferenceError was occurring. - // Now we should be able to tell what is wrong by which line causes the Null Reference Error - // RHM 20101217 - //SelectedDVI = value.MyStepPanel.MyProcedureItemInfo.MyProcedure.ActiveParent as DocVersionInfo; StepPanel stepPanel = value.MyStepPanel; ItemInfo itemInfo = stepPanel.MyProcedureItemInfo; ProcedureInfo procedureInfo = itemInfo.MyProcedure; @@ -101,7 +92,7 @@ namespace VEPROMS void MyStepTabRibbon_ContActionSummaryRequest(object sender, StepTabRibbonEventArgs args) { - DialogResult dr = System.Windows.Forms.DialogResult.Yes; + DialogResult dr = DialogResult.Yes; ProcedureInfo piThis = null; if (_CurrentItem != null) piThis = _CurrentItem.MyProcedure; @@ -114,17 +105,18 @@ namespace VEPROMS //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit pi.MyDocVersion.DocVersionConfig.SelectedSlave = pi.ProcedureConfig.SelectedSlave; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi) + { + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit + SelectedSlave = (pi.ProcedureConfig.SelectedSlave == 0) ? -1 : pi.ProcedureConfig.SelectedSlave, + MySessionInfo = MySessionInfo, + Automatic = true, + CreateContinuousActionSummary = true, + OpenAfterCreate = (dr == DialogResult.Yes), + Prefix = "CASTMP_" // A temporary procedure PDF is created to grab page numbers + }; - //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit - prnDlg.SelectedSlave = (pi.ProcedureConfig.SelectedSlave == 0) ? -1 : pi.ProcedureConfig.SelectedSlave; - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.Automatic = true; - prnDlg.CreateContinuousActionSummary = true; - prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); - prnDlg.Prefix = "CASTMP_"; // A temporary procedure PDF is created to grab page numbers - - prnDlg.SetupForProcedure(); + prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit @@ -133,7 +125,7 @@ namespace VEPROMS // F2022-024 Time Critical Action Summary void MyStepTabRibbon_TimeCriticalActionSummaryRequest(object sender, StepTabRibbonEventArgs args) { - DialogResult dr = System.Windows.Forms.DialogResult.Yes; + DialogResult dr = DialogResult.Yes; ProcedureInfo piThis = null; if (_CurrentItem != null) piThis = _CurrentItem.MyProcedure; @@ -146,17 +138,18 @@ namespace VEPROMS //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit pi.MyDocVersion.DocVersionConfig.SelectedSlave = pi.ProcedureConfig.SelectedSlave; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi) + { + //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit + SelectedSlave = (pi.ProcedureConfig.SelectedSlave == 0) ? -1 : pi.ProcedureConfig.SelectedSlave, + MySessionInfo = MySessionInfo, + Automatic = true, + CreateTimeCriticalActionSummary = true, + OpenAfterCreate = (dr == DialogResult.Yes), + Prefix = "TCASTMP_" // A temporary procedure PDF is created to grab page numbers + }; - //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit - prnDlg.SelectedSlave = (pi.ProcedureConfig.SelectedSlave == 0) ? -1 : pi.ProcedureConfig.SelectedSlave; - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.Automatic = true; - prnDlg.CreateTimeCriticalActionSummary = true; - prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); - prnDlg.Prefix = "TCASTMP_"; // A temporary procedure PDF is created to grab page numbers - - prnDlg.SetupForProcedure(); + prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); //added by jcb 20130718 to support create pdf button when multi-unit and user selects a unit @@ -174,7 +167,7 @@ namespace VEPROMS _SelectedROFst = null; } InitiateSearch(false); - InitiateDisplayReports(false); + InitiateDisplayReports(); } } @@ -197,24 +190,13 @@ namespace VEPROMS set { _SelectedROFst = value; } } - #endregion + #endregion - private frmVEPROMS _MyParent; - public frmVEPROMS MyParent - { - get { return _MyParent; } - set { _MyParent = value; } - } + public frmVEPROMS MyParent { get; set; } + public DocVersionInfo MyDocVersion { get; set; } = null; - private DocVersionInfo _MyDocVersion = null; - public DocVersionInfo MyDocVersion - { - get { return _MyDocVersion; } - set { _MyDocVersion = value; } - } - - // C2015-022 setup the child PROMS window - public frmVEPROMS(frmVEPROMS myParent, DocVersionInfo myDocVersion) + // C2015-022 setup the child PROMS window + public frmVEPROMS(frmVEPROMS myParent, DocVersionInfo myDocVersion) { MyParent = myParent; MyDocVersion = myDocVersion; @@ -245,17 +227,11 @@ namespace VEPROMS (tv.Nodes[0] as VETreeNode).InChildWindow = true; // tells us this folder's tree nodes are in the child window } - public void OpenItem(ItemInfo myItemInfo) - { - tc.OpenItem(myItemInfo); - } + public void OpenItem(ItemInfo myItemInfo) => tc.OpenItem(myItemInfo); - public void RefreshItem(ItemInfo myItemInfo) - { - tc.RefreshItem(myItemInfo); - } + public void RefreshItem(ItemInfo myItemInfo) => tc.RefreshItem(myItemInfo); - public void tv_FolderDelete(int folderId) + public void tv_FolderDelete(int folderId) { // Create an instance of the event args if needed var args = new vlnTreeFolderDeleteEventArgs(folderId); @@ -278,16 +254,16 @@ namespace VEPROMS // instructs the user to try again. try { - if (Properties.Settings.Default.UpdateSettings) + if (Settings.Default.UpdateSettings) { - Properties.Settings.Default.Upgrade(); - Properties.Settings.Default.UpdateSettings = false; - Properties.Settings.Default.Save(); + Settings.Default.Upgrade(); + Settings.Default.UpdateSettings = false; + Settings.Default.Save(); } } catch (Exception ex) { - _MyLog.Error(ex.GetType().Name + " - " + ex.InnerException, ex); + _MyLog.Error($"{ex.GetType().Name} - {ex.InnerException}", ex); if (ex.Message.StartsWith("Configuration system failed to initialize")) { @@ -300,44 +276,20 @@ namespace VEPROMS MessageBox.Show("Config file was corrupt, it has been deleted.\r\nTry Again", "Corrupt config file", MessageBoxButtons.OK, MessageBoxIcon.Error); - System.Diagnostics.Process.GetCurrentProcess().Kill(); + Process.GetCurrentProcess().Kill(); } } // If first time close any remaining WinWords. These will sometimes get hung in memory and cause problems. - if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length == 1) + if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length == 1) { Volian.MSWord.WordDoc.KillWordApps(); } - // cleanup from previous run: - Volian.Base.Library.TmpFile.RemoveAllTmps(); + // cleanup from previous run: + TmpFile.RemoveAllTmps(); - if (VlnSettings.DebugMode) - { - //use local data (for development/debug mode) - if (Environment.MachineName == "RMARK-PC") - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_RMARK_DEBUG"; - else if (Environment.MachineName == "WINDOWS7-RHM") - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_RMARK_DEBUG"; - else if (Environment.UserName.ToUpper() == "BODINE") - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_BODINE_DEBUG"; - else - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_LOCAL"; - } - else - { - // use server data (default) - // - except for the volian laptop and Rich's Demo version where we need to use local data - if (Environment.MachineName == "RMARK-PC") - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_RMARK_DEMO"; - else if (Environment.MachineName == "WINDOWS7-RHM") - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_RMARK_DEMO"; - else if (Environment.UserName.ToUpper() == "BODINE") - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_BODINE_DEMO"; - else - VEPROMS.CSLA.Library.Database.ConnectionName = "VEPROMS_LOCAL"; - } + Database.ConnectionName = "VEPROMS_LOCAL"; InitializeComponent(); @@ -369,15 +321,15 @@ namespace VEPROMS cmbFont.DataSource = FontFamily.Families; cmbFont.DisplayMember = "Name"; cmbFont.SelectedIndex = -1; - string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray()); - string db = Volian.Base.Library.VlnSettings.GetDB(); + string[] parameters = Environment.CommandLine.Split(" ".ToCharArray()); + string db = VlnSettings.GetDB(); if (db != null) Database.SelectedDatabase = db; //B2018-129 Most Recently Used list was being cleared. Needed to remove a (string) type case in the IF statement - if (!string.IsNullOrEmpty((string)Properties.Settings.Default["DefaultDB"])) - Database.LastDatabase = Properties.Settings.Default.DefaultDB; + if (!string.IsNullOrEmpty((string)Settings.Default["DefaultDB"])) + Database.LastDatabase = Settings.Default.DefaultDB; // Setup the Context menu for DisplaySearch including the symbols displaySearch1.SetupContextMenu(); @@ -396,12 +348,11 @@ namespace VEPROMS if ((Database.LastDatabase ?? "") != (Database.SelectedDatabase ?? "")) { - if (Properties.Settings.Default.VersionWindows != null) - Properties.Settings.Default.VersionWindows.Clear(); + Settings.Default.VersionWindows?.Clear(); - Properties.Settings.Default.MRIList = null; - Properties.Settings.Default.DefaultDB = Database.SelectedDatabase; - Properties.Settings.Default.Save(); + Settings.Default.MRIList = null; + Settings.Default.DefaultDB = Database.SelectedDatabase; + Settings.Default.Save(); } displayBookMarks.SetupBookMarks(); @@ -410,30 +361,30 @@ namespace VEPROMS // D2017-260 - Use a prefix of the server name combined with the database name for temporary MSWord sections DSOFile.TempFilePrefix = System.Text.RegularExpressions.Regex.Replace(System.Text.RegularExpressions.Regex.Replace(c, @"([^[\]]*) \[.*\]", "$1"), @"[\#\~\%\@\[\]\(\)\{\}\-. \\*<>:;""/?|]+", "_"); - ChangeLogFileName("LogFileAppender", Database.ActiveDatabase + " " + dtSunday.ToString("yyyyMMdd") + " ErrorLog.txt"); + ChangeLogFileName("LogFileAppender", $"{Database.ActiveDatabase} {dtSunday:yyyyMMdd} ErrorLog.txt"); // B2019-107 Error Log message for inconsistent PromsFixes - _MyLog.InfoFormat("\r\nSession Beginning\r\n<===={0}[SQL:{1:yyMM.ddHH}]====== User: {2}/{3} Started {4} ===============>{5}" - , Application.ProductVersion, Database.RevDate, Environment.UserDomainName, Environment.UserName, DateTime.Now.ToString("dddd MMMM d, yyyy h:mm:ss tt"), FormatInfo.Failed ?? ""); + _MyLog.InfoFormat($"\r\nSession Beginning\r\n<===={{0}}[SQL:{{1:yyMM.ddHH}}]====== User: {{2}}/{{3}} Started {{4}} ===============>{{5}}" + , Application.ProductVersion, Database.RevDate, Environment.UserDomainName, Environment.UserName, DateTime.Now.ToString("dddd MMMM d, yyyy h:mm:ss tt"), FormatInfo.Failed ?? ""); // C2022-030 Notify the user if the stored procedure in the database are not update to date // with those in the PROMSFixes.sql delivered with the PROMS executable string pfVersion = ExeInfo.GetAssocicatedPROMSFixesVersion(); - string dbpfVersion = string.Format("{0:yyMM.ddHH}", Database.RevDate); + string dbpfVersion = $"{Database.RevDate:yyMM.ddHH}"; // if pfVersion is null, that means there was a problem finding or reading the PROMSFixes.SQL file in the executable folder if (pfVersion != null && !pfVersion.Equals(dbpfVersion)) { - _MyLog.WarnFormat("PROMSFixes Version - in Data Version is {0} PROMS is Expecting Version {1}", dbpfVersion, pfVersion); + _MyLog.WarnFormat($"PROMSFixes Version - in Data Version is {dbpfVersion} PROMS is Expecting Version {pfVersion}"); StringBuilder sbMsg = new StringBuilder(); //sbMsg.Append("The SQL Stored Procedures in the Database are a different version than what PROMS is expecting."); sbMsg.Append("The SQL Stored Procedures version in the database is different than what PROMS is expecting."); sbMsg.Append("\nPROMS may not run properly until the lastest SQL Stored Procedures are installed."); - sbMsg.AppendFormat("\n\n The database has SQL Stored Procedures version: {0}", dbpfVersion); - sbMsg.AppendFormat("\n PROMS is expecting SQL Stored Procedures version: {0}", pfVersion); + sbMsg.AppendFormat($"\n\n The database has SQL Stored Procedures version: {dbpfVersion}"); + sbMsg.AppendFormat($"\n PROMS is expecting SQL Stored Procedures version: {pfVersion}"); sbMsg.Append("\n\nPlease have your DBA update the database with the PROMSFixes.sql script file that was\ndelivered with this PROMS executable."); sbMsg.Append("\n\nThe PROMSFixes.sql file is included with the PROMS installation download."); sbMsg.Append("\n\nIt can also be found in your PROMS executable folder:"); - sbMsg.AppendFormat("\n\t{0}",ExeInfo.PROMSExecutableFolderPath()); + sbMsg.AppendFormat($"\n\t{{0}}", ExeInfo.PROMSExecutableFolderPath()); FlexibleMessageBox.Show(sbMsg.ToString(),"SQL Stored Procedures Version Difference"); } @@ -449,29 +400,18 @@ namespace VEPROMS SetupFolder(1); tc.VersionID = 0; - tc.SeparateWindows = Properties.Settings.Default.SeparateWindows; + tc.SeparateWindows = Settings.Default.SeparateWindows; tv.PauseRefresh += tv_PauseRefresh; tv.UnPauseRefresh += tv_UnPauseRefresh; } - void displaySearch1_SearchComplete(object sender, DisplaySearchEventArgs args) - { - ProgBarText = string.Format("{0} Seconds", args.HowLong.TotalSeconds); - } + void displaySearch1_SearchComplete(object sender, DisplaySearchEventArgs args) => ProgBarText = $"{args.HowLong.TotalSeconds} Seconds"; - private bool _PauseRefresh = false; - public bool PauseRefresh - { - get { return _PauseRefresh; } - set { _PauseRefresh = value; } - } + public bool PauseRefresh { get; set; } = false; - void tv_UnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) - { - PauseRefresh = false; - } + void tv_UnPauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) => PauseRefresh = false; - void tv_PauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) + void tv_PauseRefresh(object sender, vlnTreeSectionInfoEventArgs args) { //_MyLog.WarnFormat("Pause"); //PauseRefresh = true; @@ -521,7 +461,7 @@ namespace VEPROMS displayHistory.AnnotationRestored += new AnnotationRestoredHandler(displayHistory_AnnotationRestored); displayReports.PrintRequest += new DisplayReportsEvent(displayReports_PrintRequest); - this.Activated += new EventHandler(frmVEPROMS_Activated); + Activated += new EventHandler(frmVEPROMS_Activated); VlnSettings.StepTypeToolTip = Settings.Default.StepTypeToolTip; VlnSettings.cbShwRplWrdsColor = Settings.Default.cbShwRplWrdsColor; @@ -578,11 +518,11 @@ namespace VEPROMS { frmVEPROMS tmp = PROMSWindowForms[k]; - if (tmp.MyDocVersion.VersionID != this.SelectedDVI.VersionID) + if (tmp.MyDocVersion.VersionID != SelectedDVI.VersionID) tmp.displayBookMarks.ResetBookMarkList(); - else if (tmp.MyParent != null) - tmp.MyParent.displayBookMarks.ResetBookMarkList(); + else + tmp.MyParent?.displayBookMarks.ResetBookMarkList(); } } @@ -607,20 +547,18 @@ namespace VEPROMS void tv_SelectDateToStartChangeBars(object sender, vlnTreeEventArgs args) { - ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) return; - tc.SaveCurrentEditItem(pi); + if (!((args.Node as VETreeNode).VEObject is ProcedureInfo pi)) return; + tc.SaveCurrentEditItem(pi); - ProcedureConfig pc = pi.MyConfig as ProcedureConfig; - if (pc == null) return; + if (!(pi.MyConfig is ProcedureConfig pc)) return; - dlgSetChangeBarStartDate cbdDlg = new dlgSetChangeBarStartDate(pc, pi); + dlgSetChangeBarStartDate cbdDlg = new dlgSetChangeBarStartDate(pc, pi); if (cbdDlg.ShowDialog() == DialogResult.OK) { using (Item itm = Item.Get(pi.ItemID)) { itm.MyContent.Config = pc.ToString(); - itm.UserID = Volian.Base.Library.VlnSettings.UserID; + itm.UserID = VlnSettings.UserID; itm.Save(); //B2019-140 Change bars do not get refreshed when approval is run. @@ -648,14 +586,9 @@ namespace VEPROMS } } - private bool _SkipRefresh = false; - public bool SkipRefresh - { - get { return _SkipRefresh; } - set { _SkipRefresh = value; } - } + public bool SkipRefresh { get; set; } = false; - void tv_Processing(object sender, vlnTreeStatusEventArgs args) + void tv_Processing(object sender, vlnTreeStatusEventArgs args) { SkipRefresh = args.MyStatus; @@ -672,7 +605,7 @@ namespace VEPROMS void tv_ProcessingComplete(object sender, vlnTreeTimeEventArgs args) { - bottomProgBar.Text = string.Format("{0} seconds - {1}", args.MyTimeSpan.TotalSeconds, args.MyMessage); + bottomProgBar.Text = $"{args.MyTimeSpan.TotalSeconds} seconds - {args.MyMessage}"; Application.DoEvents(); } @@ -688,12 +621,9 @@ namespace VEPROMS return tc.ChgId; } - ItemInfo tv_ClipboardStatus(object sender, vlnTreeEventArgs args) - { - return tc.MyCopyStep; - } + ItemInfo tv_ClipboardStatus(object sender, vlnTreeEventArgs args) => tc.MyCopyStep; - void tv_NodeCopy(object sender, vlnTreeEventArgs args) + void tv_NodeCopy(object sender, vlnTreeEventArgs args) { VETreeNode tn = args.Node as VETreeNode; ItemInfo ii = tn.VEObject as ItemInfo; @@ -720,11 +650,11 @@ namespace VEPROMS if (pi != null) //working with procedure { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; Application.DoEvents(); dlgTransitionReport dlg = new dlgTransitionReport(pi); dlg.ShowDialog(this); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } } @@ -751,7 +681,6 @@ namespace VEPROMS // don't stop the export (CheckOutType.Session was changed to CheckOutType.Folder). bool ok = MySessionInfo.CanCheckOutItem(fi.FolderID, CheckOutType.Folder, ref msg); - //bool ok = MySessionInfo.CanCheckOutItem(fi.FolderID, (args.Index == 0)? CheckOutType.Folder : CheckOutType.Session, ref msg); if (!ok) { if (args.Index == 0) @@ -817,10 +746,12 @@ namespace VEPROMS //form for exporting Electronic Procedures from DocVersionInfo if (args.AnnotationTypeId > 0) { - dlgExportImportEP dlg = new dlgExportImportEP(args.Index == 0 ? "Export" : "Import", dvi, this, args.AnnotationTypeId, args.UnitIndex); - dlg.MyNewProcedure = null; - dlg.ExternalTransitionItem = null; - dlg.ShowDialog(this); + dlgExportImportEP dlg = new dlgExportImportEP(args.Index == 0 ? "Export" : "Import", dvi, this, args.AnnotationTypeId, args.UnitIndex) + { + MyNewProcedure = null, + ExternalTransitionItem = null + }; + dlg.ShowDialog(this); MySessionInfo.CheckInItem(ownerid); @@ -833,10 +764,12 @@ namespace VEPROMS else { - dlgExportImport dlg = new dlgExportImport("Import", dvi, this);//Added frmVEPROMS Parameter - dlg.MyNewProcedure = null; - dlg.ExternalTransitionItem = null; - dlg.ShowDialog(this); + dlgExportImport dlg = new dlgExportImport("Import", dvi, this) + { + MyNewProcedure = null, + ExternalTransitionItem = null + };//Added frmVEPROMS Parameter + dlg.ShowDialog(this); MySessionInfo.CheckInItem(ownerid); @@ -917,31 +850,21 @@ namespace VEPROMS } } - static string _ErrorLogFileName; + public static string ErrorLogFileName { get; set; } - public static string ErrorLogFileName - { - get { return frmVEPROMS._ErrorLogFileName; } - set { frmVEPROMS._ErrorLogFileName = value; } - } + public static bool colorReplaceWords() => Settings.Default.cbShwRplWrdsColor; - public static bool colorReplaceWords() - { - return Properties.Settings.Default.cbShwRplWrdsColor; - } - - static bool ChangeLogFileName(string AppenderName, string NewFilename) + static bool ChangeLogFileName(string AppenderName, string NewFilename) { log4net.Repository.ILoggerRepository RootRep; RootRep = log4net.LogManager.GetRepository(); foreach (log4net.Appender.IAppender iApp in RootRep.GetAppenders()) { - if ((iApp.Name.CompareTo(AppenderName) == 0) && (iApp is log4net.Appender.FileAppender)) + if ((iApp.Name.CompareTo(AppenderName) == 0) && (iApp is log4net.Appender.FileAppender fApp)) { - log4net.Appender.FileAppender fApp = (log4net.Appender.FileAppender)iApp; string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - fApp.File = folderPath + @"\VEPROMS\" + (Volian.Base.Library.VlnSettings.GetCommand("prefix", "") + "_").TrimStart("_".ToCharArray()) + NewFilename; + fApp.File = folderPath + @"\VEPROMS\" + (VlnSettings.GetCommand("prefix", "") + "_").TrimStart("_".ToCharArray()) + NewFilename; ErrorLogFileName = fApp.File; fApp.ActivateOptions(); @@ -984,22 +907,25 @@ namespace VEPROMS else buffer = args.MyBuffer; - string fileName = Volian.Base.Library.VlnSettings.TemporaryFolder + "\\" + args.MyFilename; + string fileName = $"{VlnSettings.TemporaryFolder}\\{args.MyFilename}"; try - { - FileStream fs = new FileStream(fileName, FileMode.Create); - fs.Write(buffer, 0, buffer.Length); - fs.Close(); - System.Diagnostics.Process.Start(fileName); - } - catch (Exception ex) + { + using (FileStream fs = new FileStream(fileName, FileMode.Create)) + { + fs.Write(buffer, 0, buffer.Length); + fs.Close(); + } + + Process.Start(fileName); + } + catch (Exception) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Could not create"); sb.AppendLine(); - sb.AppendLine(fileName + "."); + sb.AppendLine($"{fileName}."); sb.AppendLine(); sb.AppendLine("If it is open, close and retry."); @@ -1007,23 +933,19 @@ namespace VEPROMS } } - void displayHistory_AnnotationRestored(AnnotationInfo restoredAnnotationInfo, ItemInfo currentItem) - { - ctrlAnnotationDetails.UpdateAnnotationGrid(currentItem); - } + void displayHistory_AnnotationRestored(AnnotationInfo restoredAnnotationInfo, ItemInfo currentItem) => ctrlAnnotationDetails.UpdateAnnotationGrid(currentItem); - void tv_ReportAllProceduresInconsistencies(object sender, vlnTreeEventArgs args) + void tv_ReportAllProceduresInconsistencies(object sender, vlnTreeEventArgs args) { - DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; - if (dvi == null) return; + if (!((args.Node as VETreeNode).VEObject is DocVersionInfo dvi)) return; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; ItemInfoList iil = ItemInfoList.GetAllInconsistencies(dvi.VersionID); - Volian.Print.Library.PDFConsistencyCheckReport rpt = new Volian.Print.Library.PDFConsistencyCheckReport(Volian.Base.Library.VlnSettings.TemporaryFolder + @"\AllInconsistencies.pdf", iil, dvi); //B2020-020 needed to pass in DocVersion to get paper size from format + Volian.Print.Library.PDFConsistencyCheckReport rpt = new Volian.Print.Library.PDFConsistencyCheckReport(VlnSettings.TemporaryFolder + @"\AllInconsistencies.pdf", iil, dvi); //B2020-020 needed to pass in DocVersion to get paper size from format rpt.BuildAllReport(dvi); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } //C2020-036 returns a string of duplicate procedure numbers separated by newlines for use in FlexibleMessageBox @@ -1041,8 +963,8 @@ namespace VEPROMS return rtn; } } - - private List dpl = new List(); //C2020-036 used to create list duplicate procedure numbers + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List dpl = new List(); //C2020-036 used to create list duplicate procedure numbers // B2017-242 added check for duplicate procedure numbers in a procedure set // This is called before doing any of the approval @@ -1054,7 +976,7 @@ namespace VEPROMS dvi.ResetProcedures(); // B2021-035: Approve All – Pasted, modified number and deleted procedures not refreshed so missing from list List pnList = new List(); - foreach (ProcedureInfo pi in dvi.Procedures) + foreach (ProcedureInfo pi in dvi.Procedures.OfType()) { if (!pnList.Contains(pi.DisplayNumber)) { @@ -1084,11 +1006,10 @@ namespace VEPROMS void tv_ApproveSomeProcedures(object sender, vlnTreeEventArgs args) { - DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; - if (dvi == null) return; + if (!((args.Node as VETreeNode).VEObject is DocVersionInfo dvi)) return; - // B2017-242 added check for duplicate procedure numbers in a procedure set - if (DuplicateProcedureNumbers(dvi, null)) + // B2017-242 added check for duplicate procedure numbers in a procedure set + if (DuplicateProcedureNumbers(dvi, null)) { // C2020-036 display list of duplicate procedure numbers FlexibleMessageBox.Show("This procedure set has two or more procedures with the same procedure number.\n\n" + @@ -1110,9 +1031,11 @@ namespace VEPROMS int ownerid = MySessionInfo.CheckOutItem(dvi.VersionID, CheckOutType.DocVersion); dvi.DocVersionConfig.SelectedSlave = args.UnitIndex; - dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, true, this); - dlg.MySessionInfo = MySessionInfo; - dlg.ShowDialog(this); + dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, true, this) + { + MySessionInfo = MySessionInfo + }; + dlg.ShowDialog(this); displayHistory.RefreshList(); MySessionInfo.CheckInItem(ownerid); @@ -1122,11 +1045,10 @@ namespace VEPROMS void tv_ApproveAllProcedures(object sender, vlnTreeEventArgs args) { - DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; - if (dvi == null) return; + if (!((args.Node as VETreeNode).VEObject is DocVersionInfo dvi)) return; - // B2017-242 added check for duplicate procedure numbers in a procedure set - if (DuplicateProcedureNumbers(dvi, null)) + // B2017-242 added check for duplicate procedure numbers in a procedure set + if (DuplicateProcedureNumbers(dvi, null)) { // C2020-036 display list of duplicate procedure numbers FlexibleMessageBox.Show("This procedure set has two or more procedures with the same procedure number.\n\n" + @@ -1148,9 +1070,11 @@ namespace VEPROMS int ownerid = MySessionInfo.CheckOutItem(dvi.VersionID, CheckOutType.DocVersion); dvi.DocVersionConfig.SelectedSlave = args.UnitIndex; - dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, this);//Added frmVEPROMS Parameter - dlg.MySessionInfo = MySessionInfo; - dlg.ShowDialog(this); + dlgApproveProcedure dlg = new dlgApproveProcedure(dvi, this) + { + MySessionInfo = MySessionInfo + };//Added frmVEPROMS Parameter + dlg.ShowDialog(this); displayHistory.RefreshList(); MySessionInfo.CheckInItem(ownerid); @@ -1213,11 +1137,10 @@ namespace VEPROMS void tv_ProcedureCheckedOutTo(object sender, vlnTreeEventArgs args) { - ProcedureInfo pi = null; - SectionInfo si = null; + SectionInfo si = null; - pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) si = (args.Node as VETreeNode).VEObject as SectionInfo; + ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; + if (pi == null) si = (args.Node as VETreeNode).VEObject as SectionInfo; UserInfo ui = UserInfo.GetByUserID(MySessionInfo.UserID); @@ -1229,11 +1152,10 @@ namespace VEPROMS void tv_ApproveProcedure(object sender, vlnTreeEventArgs args) { - ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) return; + if (!((args.Node as VETreeNode).VEObject is ProcedureInfo pi)) return; - // B2017-242 added check for duplicate procedure numbers in a procedure set? - if (DuplicateProcedureNumbers(pi.MyDocVersion, pi)) + // B2017-242 added check for duplicate procedure numbers in a procedure set? + if (DuplicateProcedureNumbers(pi.MyDocVersion, pi)) { // C2020-036 display list of duplicate procedure numbers FlexibleMessageBox.Show("Procedure number " + dupProcList + " is used by two or more procedures within this procedure set.\n\n" + @@ -1255,9 +1177,11 @@ namespace VEPROMS int ownerid = MySessionInfo.CheckOutItem(pi.ItemID, 0); pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; - dlgApproveProcedure dlg = new dlgApproveProcedure(pi, this);//Added frmVEPROMS Parameter - dlg.MySessionInfo = MySessionInfo; - dlg.ShowDialog(this); + dlgApproveProcedure dlg = new dlgApproveProcedure(pi, this) + { + MySessionInfo = MySessionInfo + };//Added frmVEPROMS Parameter + dlg.ShowDialog(this); displayHistory.RefreshList(); MySessionInfo.CheckInItem(ownerid); @@ -1267,17 +1191,18 @@ namespace VEPROMS void tv_PrintAllProcedures(object sender, vlnTreeEventArgs args) { - DocVersionInfo dvi = (args.Node as VETreeNode).VEObject as DocVersionInfo; - if (dvi == null) return; + if (!((args.Node as VETreeNode).VEObject is DocVersionInfo dvi)) return; - tc.SaveCurrentEditItem(); + tc.SaveCurrentEditItem(); dvi.DocVersionConfig.SelectedSlave = args.UnitIndex; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(dvi); - prnDlg.SelectedSlave = args.UnitIndex; - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window + DlgPrintProcedure prnDlg = new DlgPrintProcedure(dvi) + { + SelectedSlave = args.UnitIndex, + MySessionInfo = MySessionInfo + }; + prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window dvi.DocVersionConfig.SelectedSlave = 0; } @@ -1304,17 +1229,18 @@ namespace VEPROMS void tv_PrintProcedure(object sender, vlnTreeEventArgs args) { - ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) return; + if (!((args.Node as VETreeNode).VEObject is ProcedureInfo pi)) return; - tc.SaveCurrentEditItem(pi); + tc.SaveCurrentEditItem(pi); pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi); - prnDlg.SelectedSlave = args.UnitIndex; - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi) + { + SelectedSlave = args.UnitIndex, + MySessionInfo = MySessionInfo + }; + prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; } @@ -1323,10 +1249,9 @@ namespace VEPROMS { try { - ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) return; + if (!((args.Node as VETreeNode).VEObject is ProcedureInfo pi)) return; - tc.SaveCurrentEditItem(pi); + tc.SaveCurrentEditItem(pi); pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; @@ -1354,23 +1279,17 @@ namespace VEPROMS } - //Print Section - //C2025-028 Add a Quick Print Section option + //Print Section + //C2025-028 Add a Quick Print Section option - void tv_PrintSection(object sender, vlnTreeEventArgs args) - { - PrintSection(sender, args, false); - } - void tv_QPrintSection(object sender, vlnTreeEventArgs args) - { - PrintSection(sender, args, true); - } + void tv_PrintSection(object sender, vlnTreeEventArgs args) => PrintSection(sender, args, false); + void tv_QPrintSection(object sender, vlnTreeEventArgs args) => PrintSection(sender, args, true); - void PrintSection(object sender, vlnTreeEventArgs args, bool quickprint) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping sender for Debugging")] + void PrintSection(object sender, vlnTreeEventArgs args, bool quickprint) { try { - //args.Node.Parent. SectionInfo si2 = (args.Node as VETreeNode).VEObject as SectionInfo; int _prtSectID = si2.ItemID; @@ -1420,23 +1339,24 @@ namespace VEPROMS void tv_CreateContinuousActionSummary(object sender, vlnTreeEventArgs args) { - DialogResult dr = System.Windows.Forms.DialogResult.Yes; + DialogResult dr = DialogResult.Yes; - ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) return; + if (!((args.Node as VETreeNode).VEObject is ProcedureInfo pi)) return; - tc.SaveCurrentEditItem(pi); + tc.SaveCurrentEditItem(pi); pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi, true); - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.SelectedSlave = args.UnitIndex; - prnDlg.Automatic = true; - prnDlg.CreateContinuousActionSummary = true; - prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); - prnDlg.Prefix = "CASTMP_"; // prefix the temporary procedure PDF file that is generated (to grab page numbers) - prnDlg.SetupForProcedure(); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi, true) + { + MySessionInfo = MySessionInfo, + SelectedSlave = args.UnitIndex, + Automatic = true, + CreateContinuousActionSummary = true, + OpenAfterCreate = (dr == DialogResult.Yes), + Prefix = "CASTMP_" // prefix the temporary procedure PDF file that is generated (to grab page numbers) + }; + prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; @@ -1448,39 +1368,34 @@ namespace VEPROMS } void tv_CreateTimeCriticalActionSummary(object sender, vlnTreeEventArgs args) { - DialogResult dr = System.Windows.Forms.DialogResult.Yes; + DialogResult dr = DialogResult.Yes; - ProcedureInfo pi = (args.Node as VETreeNode).VEObject as ProcedureInfo; - if (pi == null) return; + if (!((args.Node as VETreeNode).VEObject is ProcedureInfo pi)) return; - tc.SaveCurrentEditItem(pi); + tc.SaveCurrentEditItem(pi); pi.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitIndex; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi, true); - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.SelectedSlave = args.UnitIndex; - prnDlg.Automatic = true; - prnDlg.CreateTimeCriticalActionSummary = true; - prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); - prnDlg.Prefix = "TCASTMP_"; // prefix the temporary procedure PDF file that is generated (to grab page numbers) - prnDlg.SetupForProcedure(); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(pi, true) + { + MySessionInfo = MySessionInfo, + SelectedSlave = args.UnitIndex, + Automatic = true, + CreateTimeCriticalActionSummary = true, + OpenAfterCreate = (dr == DialogResult.Yes), + Prefix = "TCASTMP_" // prefix the temporary procedure PDF file that is generated (to grab page numbers) + }; + prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); pi.MyDocVersion.DocVersionConfig.SelectedSlave = 0; } - void RefreshDisplayHistory(object sender) - { - displayHistory.RefreshChangeList(); - } + void RefreshDisplayHistory(object sender) => displayHistory.RefreshChangeList(); - void displayHistory_HistorySelectionChanged(object sender, DisplayHistoryEventArgs args) - { - tc.OpenItem(ItemInfo.Get(args.ItemID)); - } + void displayHistory_HistorySelectionChanged(object sender, DisplayHistoryEventArgs args) => tc.OpenItem(ItemInfo.Get(args.ItemID)); - void displayHistory_SummaryPrintRequest(object sender, DisplayHistoryReportEventArgs args) + void displayHistory_SummaryPrintRequest(object sender, DisplayHistoryReportEventArgs args) { Volian.Print.Library.PDFChronologyReport myChronoRpt = new Volian.Print.Library.PDFChronologyReport(args.ReportTitle, args.ProcedureInfo, args.AuditList, args.AnnotationList); myChronoRpt.BuildSummary(); @@ -1549,16 +1464,10 @@ namespace VEPROMS return dr; } + // Activate tmrTreeView so that the newly created Step receives focus + void tv_NodeInsert(object sender, vlnTreeEventArgs args) => tmrTreeView.Enabled = true; - void tv_NodeInsert(object sender, vlnTreeEventArgs args) - { - // Activate tmrTreeView so that the newly created Step receives focus - tmrTreeView.Enabled = true; - } - - private int _LastROFSTID = 0; - - void frmVEPROMS_Activated(object sender, EventArgs e) + void frmVEPROMS_Activated(object sender, EventArgs e) { //Volian.Base.Library.vlnStackTrace.ShowStack(); @@ -1617,14 +1526,11 @@ namespace VEPROMS } } - // Add a tree node for a procedure if this is the first procedure in the docversion, added from - // step editor (used for creating enhanced procedure in empty docversion) - void MyStepTabRibbon_AddProcToDocVersionInTree(object sender, StepTabRibbonEventArgs args) - { - tv.AdjustTree(args.Proc as ProcedureInfo); - } + // Add a tree node for a procedure if this is the first procedure in the docversion, added from + // step editor (used for creating enhanced procedure in empty docversion) + void MyStepTabRibbon_AddProcToDocVersionInTree(object sender, StepTabRibbonEventArgs args) => tv.AdjustTree(args.Proc as ProcedureInfo); - void MyStepTabRibbon_PrintRequest(object sender, StepTabRibbonEventArgs args) + void MyStepTabRibbon_PrintRequest(object sender, StepTabRibbonEventArgs args) { // Fix for B2013-173: // if the user did the print by using the shortcut keys 'Ctrl-P' the arguments sent in @@ -1724,7 +1630,7 @@ namespace VEPROMS // C2020-002 paper size is now set in the format files - default is Letter, pass this PDFReport //C2019-013 pass in sorted by information Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.TypesSelected, args.MyItemInfoList, - Volian.Base.Library.VlnSettings.TemporaryFolder + @"\searchresults.pdf", args.PaperSize, args.SortedBy); + VlnSettings.TemporaryFolder + @"\searchresults.pdf", args.PaperSize, args.SortedBy); if (args.SearchString != null) myReport.SearchString = args.SearchString; @@ -1737,7 +1643,7 @@ namespace VEPROMS annotationCount += itm.ItemAnnotationCount; if (annotationCount > 0) - myReport.ShowAnnotations = (MessageBox.Show("Show Annotations", "Include Annotations", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes); + myReport.ShowAnnotations = (MessageBox.Show("Show Annotations", "Include Annotations", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes); } myReport.Build(); @@ -1745,7 +1651,7 @@ namespace VEPROMS void displayLibDocs_PrintRequest(object sender, DisplayLibDocEventArgs args) { - Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.LibDocList, Volian.Base.Library.VlnSettings.TemporaryFolder + @"\LibDocUsage.pdf", args.PaperSize); + Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.LibDocList, VlnSettings.TemporaryFolder + @"\LibDocUsage.pdf", args.PaperSize); myReport.Build(); } @@ -1754,28 +1660,25 @@ namespace VEPROMS // C2020-002 paper size is now set in the format files - default is Letter, pass this PDFReport if (args.TypesSelected == "RO Usage") { - Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.MyItemInfoList, Volian.Base.Library.VlnSettings.TemporaryFolder + @"\ROUsageReport.pdf", args.SortUsageByProcedure, args.IncludeMissingROs, args.PaperSize); + Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.MyItemInfoList, VlnSettings.TemporaryFolder + @"\ROUsageReport.pdf", args.SortUsageByProcedure, args.IncludeMissingROs, args.PaperSize); myReport.Build(); } else if (args.TypesSelected == "Complete RO Report") { - Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.RODataFile, Volian.Base.Library.VlnSettings.TemporaryFolder + @"\CompleteROReport.pdf", args.RofstLookup, args.CompleteROReport, args.ConvertCaretToDelta, args.IncludeEmptyROFields, args.PaperSize); + Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, args.RODataFile, VlnSettings.TemporaryFolder + @"\CompleteROReport.pdf", args.RofstLookup, args.ConvertCaretToDelta, args.IncludeEmptyROFields, args.PaperSize); myReport.Build(); } else if (args.TypesSelected == "RO Summary Report") { - Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, Volian.Base.Library.VlnSettings.TemporaryFolder + @"\ROSummaryReport.pdf", args.RofstLookup, args.ROListForReport, args.PaperSize); + Volian.Print.Library.PDFReport myReport = new Volian.Print.Library.PDFReport(args.ReportTitle, VlnSettings.TemporaryFolder + @"\ROSummaryReport.pdf", args.RofstLookup, args.ROListForReport, args.PaperSize); myReport.Build(); } } - bool tv_InsertItemInfo(object sender, vlnTreeItemInfoInsertEventArgs args) - { - // Don't select the newly created Step. This will be handled by tmrTreeView - return tc.InsertRTBItem(args.MyItemInfo, args.StepText, args.InsertType, args.FromType, args.Type, false); - } + // Don't select the newly created Step. This will be handled by tmrTreeView + bool tv_InsertItemInfo(object sender, vlnTreeItemInfoInsertEventArgs args) => tc.InsertRTBItem(args.MyItemInfo, args.StepText, args.InsertType, args.FromType, args.Type, false); - private bool tv_DeleteItemInfo(object sender, vlnTreeItemInfoEventArgs args) + private bool tv_DeleteItemInfo(object sender, vlnTreeItemInfoEventArgs args) { if (displayHistory.MyEditItem != null && displayHistory.MyItemInfo.MyProcedure.ItemID == args.MyItemInfo.ItemID) displayHistory.MyEditItem = null; @@ -1801,12 +1704,9 @@ namespace VEPROMS return rtval; } - private bool tv_PasteItemInfo(object sender, vlnTreeItemInfoPasteEventArgs args) - { - return tc.PasteRTBItem(args.MyItemInfo, args.CopyStartID, args.PasteType, (int)args.Type); - } + private bool tv_PasteItemInfo(object sender, vlnTreeItemInfoPasteEventArgs args) => tc.PasteRTBItem(args.MyItemInfo, args.CopyStartID, args.PasteType, (int)args.Type); - private ItemInfo tv_SearchIncTrans(object sender, vlnTreeItemInfoEventArgs args) + private ItemInfo tv_SearchIncTrans(object sender, vlnTreeItemInfoEventArgs args) { // C2020-033: Display the search panel with Incoming Transition info for the tree view and for the editor. displaySearch1.SearchIncTransII = args.MyItemInfo; @@ -1829,161 +1729,158 @@ namespace VEPROMS public bool ClosingWithError = false; // B2019-098: prevent looping between error & exit dialog private bool _WeAreExitingPROMS = false; // B2019-101 if exiting PROMS from main window don't prompt on each child window (separate windows) - private void frmVEPROMS_FormClosing(object sender, FormClosingEventArgs e) - { - // B2017-212 If the user uses the X button in Word to close the word attachment, PROMS thinks that the user wants to close out of PROMS as well - // trap for this and close only the Word tab in PROMS - // B2017-214 added a null reference check - // B2010-071 Since we cannot tell if the user click on the X in Word or the X in PROMS, ask if the current tab - // should be closed or if we should exit PROMS or just Cancel to continue working - if (tc._MyDisplayTabItems.Count < 1) // If all thabs are closed in the editor will indicate that in the database. - { - Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID); - } - if (!_WeAreExitingPROMS && !ClosingWithError && tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0) - { - // B2019-071 dialog to ask user if we are to close one tab or exit - DlgCloseTabsOrExit dctoe = new DlgCloseTabsOrExit(MyParent == null, PROMSWindowForms.Count > 0); - dctoe.ShowDialog(); + private void frmVEPROMS_FormClosing(object sender, FormClosingEventArgs e) + { + // B2017-212 If the user uses the X button in Word to close the word attachment, PROMS thinks that the user wants to close out of PROMS as well + // trap for this and close only the Word tab in PROMS + // B2017-214 added a null reference check + // B2010-071 Since we cannot tell if the user click on the X in Word or the X in PROMS, ask if the current tab + // should be closed or if we should exit PROMS or just Cancel to continue working + if (tc._MyDisplayTabItems.Count < 1) // If all thabs are closed in the editor will indicate that in the database. + { + Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID); + } + if (!_WeAreExitingPROMS && !ClosingWithError && tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0) + { + // B2019-071 dialog to ask user if we are to close one tab or exit + DlgCloseTabsOrExit dctoe = new DlgCloseTabsOrExit(MyParent == null, PROMSWindowForms.Count > 0); + dctoe.ShowDialog(); - // B2019-101 flag that we are exiting from PROMS main window (separate windows) - _WeAreExitingPROMS = (MyParent == null && dctoe.ExitPROMS); + // B2019-101 flag that we are exiting from PROMS main window (separate windows) + _WeAreExitingPROMS = (MyParent == null && dctoe.ExitPROMS); - if (dctoe.Cancel) // B2019-071 user decided to not close any tab and not exit PROMS - so do nothing and continue working - { - e.Cancel = true; - dctoe.Close(); - return; - } + if (dctoe.Cancel) // B2019-071 user decided to not close any tab and not exit PROMS - so do nothing and continue working + { + e.Cancel = true; + dctoe.Close(); + return; + } - string stk = vlnStackTrace.StackToString(); + string stk = vlnStackTrace.StackToString(); - if (!stk.Contains("Exception")) - { - // B2018-091 Allow PROMS to close if only MSWord sections have been opened. - // B2019-071 we will now close one or all of the tabs (even step editor ones) - if (_WeAreExitingPROMS) - { - // Deactivate previous procedure tab state by user - Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID); - // Save current procedure tab state - //B2024-082 Remember Tabs Not opening in correct order - int cnt = 0; - foreach (DisplayTabItem dti in tc.MyBar.Items) - { - cnt++; - ItemInfo itminfo = dti.MyItemInfo; - string DisplayTabID = dti.MyKey; - string DisplayTabName = dti.ToString(); - // B2026-074 if a Word section, save the ItemID of the entire Word section - // else if a Step Editor section, save the ItemID of the step part the user was on - int TabItemID = itminfo.HasWordContent ? itminfo.ItemID : dti.MyStepTabPanel.MyStepTabRibbon.MyEditItem.MyItemInfo.ItemID; - Item.AddDisplayTabsState(TabItemID, DisplayTabID, DisplayTabName, MySessionInfo.UserID, cnt); - } - } + if (!stk.Contains("Exception")) + { + // B2018-091 Allow PROMS to close if only MSWord sections have been opened. + // B2019-071 we will now close one or all of the tabs (even step editor ones) + if (_WeAreExitingPROMS) + { + // Deactivate previous procedure tab state by user + Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID); + // Save current procedure tab state + //B2024-082 Remember Tabs Not opening in correct order + int cnt = 0; + foreach (DisplayTabItem dti in tc.MyBar.Items) + { + cnt++; + ItemInfo itminfo = dti.MyItemInfo; + string DisplayTabID = dti.MyKey; + string DisplayTabName = dti.ToString(); + // B2026-074 if a Word section, save the ItemID of the entire Word section + // else if a Step Editor section, save the ItemID of the step part the user was on + int TabItemID = itminfo.HasWordContent ? itminfo.ItemID : dti.MyStepTabPanel.MyStepTabRibbon.MyEditItem.MyItemInfo.ItemID; + Item.AddDisplayTabsState(TabItemID, DisplayTabID, DisplayTabName, MySessionInfo.UserID, cnt); + } + } - int n = tc._MyDisplayTabItems.Count; - while (n-- > 0 && tc._MyDisplayTabItems.Count > 0) - { - tc.CloseTabItem(tc.SelectedDisplayTabItem); - // B2019-071 close just the current tab and continue working - if (!dctoe.ExitPROMS) - { - n = 0; - e.Cancel = true; - dctoe.Close(); - return; - } - } + int n = tc._MyDisplayTabItems.Count; + while (n-- > 0 && tc._MyDisplayTabItems.Count > 0) + { + tc.CloseTabItem(tc.SelectedDisplayTabItem); + // B2019-071 close just the current tab and continue working + if (!dctoe.ExitPROMS) + { + e.Cancel = true; + dctoe.Close(); + return; + } + } - if (tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0 && dctoe.ExitPROMS) - { - _MyLog.WarnFormat(string.Format("Stack Does not contain an Exception\r\n" + - "PROMS will Not Exit. Stack : \r\n{0}", stk)); - e.Cancel = true; // If Display Items still exist don't close. - } + if (tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0 && dctoe.ExitPROMS) + { + _MyLog.WarnFormat($"Stack Does not contain an Exception\r\nPROMS will Not Exit. Stack : \r\n{stk}"); + e.Cancel = true; // If Display Items still exist don't close. + } - dctoe.Close(); - } - } + dctoe.Close(); + } + } - //C2015-022 Separate Windows - if child windows are open and we are closing the main PROMS window, give user a chance to not close PROMS and that child windows - // B2019-101 if we are exiting from PROMS main window no need to prompt user about child windows. - if (MyParent == null && PROMSWindowForms != null && PROMSWindowForms.Count > 0 && !_WeAreExitingPROMS) - { - DialogResult dr = MessageBox.Show("Close all of the child windows and exit PROMS?", "Exit PROMS", MessageBoxButtons.YesNo); - if (dr == System.Windows.Forms.DialogResult.No) - { - e.Cancel = true; - return; - } - } + //C2015-022 Separate Windows - if child windows are open and we are closing the main PROMS window, give user a chance to not close PROMS and that child windows + // B2019-101 if we are exiting from PROMS main window no need to prompt user about child windows. + if (MyParent == null && PROMSWindowForms != null && PROMSWindowForms.Count > 0 && !_WeAreExitingPROMS) + { + DialogResult dr = MessageBox.Show("Close all of the child windows and exit PROMS?", "Exit PROMS", MessageBoxButtons.YesNo); + if (dr == DialogResult.No) + { + e.Cancel = true; + return; + } + } - // This keeps PROMS from Hanging under certain circumstances - tc.ShuttingDown = true; + // This keeps PROMS from Hanging under certain circumstances + tc.ShuttingDown = true; - // B2019-161 When shutting down output the timing information (to the error log) - if (VolianTimer.TimingsOn) - VolianTimer.ShowTimers(); + // B2019-161 When shutting down output the timing information (to the error log) + if (VolianTimer.TimingsOn) + VolianTimer.ShowTimers(); - foreach (DisplayTabItem dti in tc.MyBar.Items) - { - if (dti.MyDSOTabPanel != null) - dti.MyDSOTabPanel.CloseDSO(); - else - MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active - } + foreach (DisplayTabItem dti in tc.MyBar.Items) + { + if (dti.MyDSOTabPanel != null) + dti.MyDSOTabPanel.CloseDSO(); + else + MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active + } - if (MyParent == null) - { - if (MyActivityTimer != null) - { - MyActivityTimer.Dispose(); - _MyLog.Debug("VEPROMS FormClosing - dispose timer"); - } + if (MyParent == null) + { + if (MyActivityTimer != null) + { + MyActivityTimer.Dispose(); + _MyLog.Debug("VEPROMS FormClosing - dispose timer"); + } - // C2015-022: part of separate windows upgrade close all of the child windows before closing the main PROMS window - if (PROMSWindowForms != null && PROMSWindowForms.Count > 0) - { - foreach (int k in PROMSWindowForms.Keys) - { - frmVEPROMS child = PROMSWindowForms[k]; - _RemoveFromPROMSWindowForms = false; - child._RemoveFromPROMSWindowForms = false; - child._WeAreExitingPROMS = _WeAreExitingPROMS; - child.Close(); - child.MySessionInfo.EndSession(); - } - } + // C2015-022: part of separate windows upgrade close all of the child windows before closing the main PROMS window + if (PROMSWindowForms != null && PROMSWindowForms.Count > 0) + { + foreach (int k in PROMSWindowForms.Keys) + { + frmVEPROMS child = PROMSWindowForms[k]; + _RemoveFromPROMSWindowForms = false; + child._RemoveFromPROMSWindowForms = false; + child._WeAreExitingPROMS = _WeAreExitingPROMS; + child.Close(); + child.MySessionInfo.EndSession(); + } + } - if (MySessionInfo != null) MySessionInfo.EndSession(); + MySessionInfo?.EndSession(); - // Save the location and size of the VE-PROMS application for this user - if (this.WindowState == FormWindowState.Normal) - { - Settings.Default.Location = this.Location; - Settings.Default.Size = this.Size; - } + // Save the location and size of the VE-PROMS application for this user + if (WindowState == FormWindowState.Normal) + { + Settings.Default.Location = Location; + Settings.Default.Size = Size; + } - if (this.MyVersionWindowList != null) - { - Settings.Default.VersionWindows = this.MyVersionWindowList.ToSettings(); - } + if (MyVersionWindowList != null) + { + Settings.Default.VersionWindows = MyVersionWindowList.ToSettings(); + } - Settings.Default.WindowState = this.WindowState; - Settings.Default.QATItems = ribbonControl1.QatLayout; + Settings.Default.WindowState = WindowState; + Settings.Default.QATItems = ribbonControl1.QatLayout; - SaveMRU(); + SaveMRU(); - //Settings.Default.Save(); - Volian.Base.Library.DebugPagination.Close(); - Volian.Base.Library.DebugText.Close(); - Volian.Base.Library.BaselineMetaFile.Close(); // C2018-004 create meta file for baseline compares - } - } + DebugPagination.Close(); + DebugText.Close(); + BaselineMetaFile.Close(); // C2018-004 create meta file for baseline compares + } + } - void frmVEPROMS_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e) + void frmVEPROMS_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e) { // Close any open documents tc.Dispose(); @@ -1995,7 +1892,7 @@ namespace VEPROMS { try { - System.Diagnostics.Process.GetCurrentProcess().Kill(); + Process.GetCurrentProcess().Kill(); } catch (Exception ex) { @@ -2022,10 +1919,9 @@ namespace VEPROMS { VETreeNode jj_vetn = (VETreeNode)tv.Nodes[0]; // the VEPROMS tree node string s = ((FolderConfig)jj_vetn.VEObject.MyConfig).Timeout; // get the panel heading - int result = 30; - if (!int.TryParse(s, out result)) - result = 30; - return result; + if (!int.TryParse(s, out int result)) + result = 30; + return result; } private Timer _RefreshTimer; @@ -2036,27 +1932,23 @@ namespace VEPROMS { if (_RefreshTimer == null) { - _RefreshTimer = new Timer(); - _RefreshTimer.Interval = 20000; // - _RefreshTimer.Enabled = true; - _RefreshTimer.Tick += _RefreshTimer_Tick; + _RefreshTimer = new Timer + { + Interval = 20000, // + Enabled = true + }; + _RefreshTimer.Tick += _RefreshTimer_Tick; } return _RefreshTimer; } } - private bool _RefreshTimerActive = false; + // B2019-161 When tracking timing time this action + private static readonly VolianTimer _TimeActivity = new VolianTimer("frmVEPROMS.cs _RefreshTimer_Tick", 1346); - // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("frmVEPROMS.cs _RefreshTimer_Tick", 1346); + public bool RefreshTimerActive { get; set; } = false; - public bool RefreshTimerActive - { - get { return _RefreshTimerActive; } - set { _RefreshTimerActive = value; } - } - - void _RefreshTimer_Tick(object sender, EventArgs e) + void _RefreshTimer_Tick(object sender, EventArgs e) { if (RefreshTimerActive) { @@ -2064,7 +1956,7 @@ namespace VEPROMS _TimeActivity.Open(); if (PauseRefresh) return; - RefreshChanged(this); + RefreshChanged(); _TimeActivity.Close(); } } @@ -2072,10 +1964,10 @@ namespace VEPROMS private void btnStepRTF_Click(object sender, System.EventArgs e) { // Only simulate Threaded Timer Ping if in the debugger - if (System.Diagnostics.Process.GetCurrentProcess().ProcessName.ToLower().EndsWith("vshost")) + if (Process.GetCurrentProcess().ProcessName.ToLower().EndsWith("vshost")) { PingSession(null); - StartRefreshChanged(null); + StartRefreshChanged(); } } @@ -2100,15 +1992,12 @@ namespace VEPROMS private DevComponents.DotNetBar.ButtonItem btnFormats; private DevComponents.DotNetBar.ButtonItem btnGeneralTools; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private TabItemsToClose _MyCloseTabList = new TabItemsToClose(); - private TabItemsToClose _MyCloseTabList = new TabItemsToClose(); - - public TabItemsToClose MyCloseTabList - { - get { return _MyCloseTabList; } - } - - private bool _DisablePing = false; + public TabItemsToClose MyCloseTabList => _MyCloseTabList; + + private bool _DisablePing = false; public bool DisablePing { get { return _DisablePing; } @@ -2119,7 +2008,7 @@ namespace VEPROMS } } - private void PingSession(Object obj) + private void PingSession(object obj) { MySemaphore.WaitOne(); @@ -2146,8 +2035,6 @@ namespace VEPROMS MySemaphore.Release(); } - WindowsFormsSynchronizationContext mUIContext = new WindowsFormsSynchronizationContext(); - public void MyFindNodeAndExpand(object obj) { if (tv == null || tv.SelectedNode == null) return; @@ -2181,20 +2068,16 @@ namespace VEPROMS MySemaphore.Release(); // ping session control } - private void StartRefreshChanged(Object obj) + private void StartRefreshChanged() { - //_MyLog.Debug("StartRefreshChanged"); - //if (SkipRefresh) return; MySemaphore.WaitOne(); RefreshTimerActive = !PauseRefresh; MySemaphore.Release(); } - private void RefreshChanged(Object obj) + private void RefreshChanged() { - //if (SkipRefresh) return; - //MySemaphore.WaitOne(); - Int64 lastChanged = 0; + long lastChanged = 0; //_MyLog.WarnFormat(">>> RefreshChanged"); try @@ -2245,7 +2128,6 @@ namespace VEPROMS } catch { } - //MySemaphore.Release(); //_MyLog.DebugFormat("{0},{1:X},{2:X},{3:X}", DateTime.Now.ToLongTimeString(), lastChanged, MySessionInfo.LastContentChange, MySessionInfo.LastChangedInt64); } @@ -2261,19 +2143,6 @@ namespace VEPROMS return total; } - private bool ByteArrayIsEmpty(byte[] myArray) - { - for (int i = 0; i < myArray.Length; i++) - { - if (myArray[i] != 0) - { - return false; - } - } - - return true; - } - public UserInfo MyUserInfo = null; public static UserInfo SMyUserInfo = null; // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. public VersionWindowList MyVersionWindowList; @@ -2282,14 +2151,13 @@ namespace VEPROMS public ContentInfo ci3; public Timer tmrCloseTabItems; public System.Threading.Semaphore MySemaphore = new System.Threading.Semaphore(1, 1); - private bool _frmVEPROMSloading = false; private void frmVEPROMS_Load(object sender, EventArgs e) { - // B2019-116 Use Volian.Base.Library.VlnItextFont - // This is a generic class for dealing with iTextSharp Fonts - // Code moved and consolidated from Volian.Print.Library, Volian PDF.Library and VG - Volian.Base.Library.VlnItextFont.RegisterPromsFonts(); + // B2019-116 Use Volian.Base.Library.VlnItextFont + // This is a generic class for dealing with iTextSharp Fonts + // Code moved and consolidated from Volian.Print.Library, Volian PDF.Library and VG + VlnItextFont.RegisterPromsFonts(); InitializeSecurity(); UpdateUser(); @@ -2315,19 +2183,19 @@ namespace VEPROMS //general Tools btnGeneralTools = new ButtonItem("btnGeneralTools", "General Tools"); btnGeneralTools.Visible = btnGeneralTools.Enabled = true; - btnGeneralTools.ButtonStyle = DevComponents.DotNetBar.eButtonStyle.ImageAndText; + btnGeneralTools.ButtonStyle = eButtonStyle.ImageAndText; btnGeneralTools.CanCustomize = false; - btnGeneralTools.Image = global::VEPROMS.Properties.Resources.toolbox; + btnGeneralTools.Image = Resources.toolbox; btnGeneralTools.Click += new EventHandler(btnGeneralTools_Click); itemContainer3.SubItems.Add(btnGeneralTools); // C2025-031 added tool tip messages - this.superTooltip1.SetSuperTooltip(btnManageSecurity, new SuperTooltipInfo("Manage Security", "", "Add, Modify, and Delete PROMS User Access", null, null, eTooltipColor.Gray)); - this.superTooltip1.SetSuperTooltip(btnResetSecurity, new SuperTooltipInfo("Reset Security", "", "WARNING this will \nREMOVE ALL PROMS USERS and Reset to the\nOriginal Volian Defaults", null, null, eTooltipColor.Gray)); - this.superTooltip1.SetSuperTooltip(btnAdministrativeTools, new SuperTooltipInfo("Administrative Tools", "", "Open the PROMS Adminstration Tools Window", null, null, eTooltipColor.Gray)); - this.superTooltip1.SetSuperTooltip(btnUpdateFormats, new SuperTooltipInfo("Update Formats", "", "Install New Formats \n or Re-Install Formats", null, null, eTooltipColor.Gray)); - this.superTooltip1.SetSuperTooltip(btnGeneralTools, new SuperTooltipInfo("General Tools", "", "Open the PROMS General Tools Window", null, null, eTooltipColor.Gray)); + superTooltip1.SetSuperTooltip(btnManageSecurity, new SuperTooltipInfo("Manage Security", "", "Add, Modify, and Delete PROMS User Access", null, null, eTooltipColor.Gray)); + superTooltip1.SetSuperTooltip(btnResetSecurity, new SuperTooltipInfo("Reset Security", "", "WARNING this will \nREMOVE ALL PROMS USERS and Reset to the\nOriginal Volian Defaults", null, null, eTooltipColor.Gray)); + superTooltip1.SetSuperTooltip(btnAdministrativeTools, new SuperTooltipInfo("Administrative Tools", "", "Open the PROMS Adminstration Tools Window", null, null, eTooltipColor.Gray)); + superTooltip1.SetSuperTooltip(btnUpdateFormats, new SuperTooltipInfo("Update Formats", "", "Install New Formats \n or Re-Install Formats", null, null, eTooltipColor.Gray)); + superTooltip1.SetSuperTooltip(btnGeneralTools, new SuperTooltipInfo("General Tools", "", "Open the PROMS General Tools Window", null, null, eTooltipColor.Gray)); try { @@ -2375,14 +2243,16 @@ namespace VEPROMS btnFormats.Visible = isVisible; btnSecurity.Visible = isVisible; btnAdmin.Enabled = (isVisible || HasSetAdministrator(MyUserInfo)); - - tmrCloseTabItems = new Timer(); - tmrCloseTabItems.Interval = 100; - tmrCloseTabItems.Tick += new EventHandler(tmrCloseTabItems_Tick); + + tmrCloseTabItems = new Timer + { + Interval = 100 + }; + tmrCloseTabItems.Tick += new EventHandler(tmrCloseTabItems_Tick); tmrCloseTabItems.Enabled = true; CloseSessionsNoLongerActive(); - MySessionInfo = SessionInfo.BeginSession(Environment.MachineName, System.Diagnostics.Process.GetCurrentProcess().Id); + MySessionInfo = SessionInfo.BeginSession(Environment.MachineName, Process.GetCurrentProcess().Id); if (MySessionInfo == null) { @@ -2390,7 +2260,7 @@ namespace VEPROMS Application.Exit(); } - this.LastContentChange = MySessionInfo.LastContentChange; + LastContentChange = MySessionInfo.LastContentChange; //_MyLog.WarnFormat("Original last content change {0}", this.LastContentChange); RefreshLastChange(); @@ -2404,13 +2274,14 @@ namespace VEPROMS SetCaption(tv.TopNode as VETreeNode); System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false); + // For Debugging: //System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(MySessionInfo.PingSession); //System.Diagnostics.Process xyzzy = System.Diagnostics.Process.GetCurrentProcess(); - if (!System.Diagnostics.Debugger.IsAttached)// running in Production Mode (Not in the debugger) + if (!Debugger.IsAttached)// running in Production Mode (Not in the debugger) { - System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(this.PingSession); - if (this._MyParent == null) + System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(PingSession); + if (MyParent == null) { MyActivityTimer = new System.Threading.Timer(timerDelegate, autoEvent, 10000, 10000); } @@ -2418,16 +2289,14 @@ namespace VEPROMS // get the saved location and size of the VE-PROMS application for this user - this.txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress); - this.txtSearch.KeyUp += txtSearch_KeyUp; // RHM20150506 Multi-Line ItemID TextBox - this.txtSearch.TextChanged += txtSearch_TextChanged; // RHM20150506 Multi-Line ItemID TextBox - this.btnNext.Click += btnNext_Click; // RHM20150506 Multi-Line ItemID TextBox - this.btnPrint1.Click += btnPrint1_Click; // RHM20150506 Multi-Line ItemID TextBox - this.btnPrevious.Click += btnPrevious_Click; // RHM20150506 Multi-Line ItemID TextBox - if (Settings.Default["Location"] != null) this.Location = Settings.Default.Location; - if (Settings.Default["Size"] != null) this.Size = Settings.Default.Size; - //if (Settings.Default["WindowState"] != null) this.WindowState = Settings.Default.WindowState; - //if (Settings.Default.SaveTreeviewExpanded) epProcedures.Expanded = Settings.Default.TreeviewExpanded; + txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress); + txtSearch.KeyUp += txtSearch_KeyUp; // RHM20150506 Multi-Line ItemID TextBox + txtSearch.TextChanged += txtSearch_TextChanged; // RHM20150506 Multi-Line ItemID TextBox + btnNext.Click += btnNext_Click; // RHM20150506 Multi-Line ItemID TextBox + btnPrint1.Click += btnPrint1_Click; // RHM20150506 Multi-Line ItemID TextBox + btnPrevious.Click += btnPrevious_Click; // RHM20150506 Multi-Line ItemID TextBox + if (Settings.Default["Location"] != null) Location = Settings.Default.Location; + if (Settings.Default["Size"] != null) Size = Settings.Default.Size; // if the Procedures panel was left open from the last session, then open it epProcedures.Expanded = Settings.Default.TreeviewExpanded; @@ -2436,10 +2305,10 @@ namespace VEPROMS // See if any database 'changes' need done and do them: MakeDatabaseChanges(); - if (Volian.Base.Library.VlnSettings.GetCommandFlag("NOMRU")) // B2017-193 Error occurred when a section in the MRU was being loaded as an iteminfo + if (VlnSettings.GetCommandFlag("NOMRU")) // B2017-193 Error occurred when a section in the MRU was being loaded as an iteminfo _MyMRIList = new MostRecentItemList(); else - _MyMRIList = MostRecentItemList.GetMRILst((System.Collections.Specialized.StringCollection)(Properties.Settings.Default["MRIList"])); + _MyMRIList = MostRecentItemList.GetMRILst((System.Collections.Specialized.StringCollection)(Settings.Default["MRIList"])); _MyMRIList.AfterRemove += new ItemInfoEvent(_MyMRIList_AfterRemove); SetupMRU(); @@ -2449,19 +2318,15 @@ namespace VEPROMS { if (Settings.Default.SaveTreeviewExpanded && _MyMRIList.Count > 0) { - _frmVEPROMSloading = true; // C2015-022 so we don't try to create child windows when proms is first starting and position in the procedure tree - tv.AdjustTree(_MyMRIList[0].MyItemInfo.MyProcedure); tv.SelectedNode.Expand(); SetCaption(tv.SelectedNode as VETreeNode); - - _frmVEPROMSloading = false; } } //get version windows settings - MyVersionWindowList = VersionWindowList.GetVersionWindowList(Properties.Settings.Default.VersionWindows); - tc.SyncEnhancedDocuments = Properties.Settings.Default.SyncEnhancedDocuments; + MyVersionWindowList = VersionWindowList.GetVersionWindowList(Settings.Default.VersionWindows); + tc.SyncEnhancedDocuments = Settings.Default.SyncEnhancedDocuments; // Assign the Procedure Panel's title (heading) epProcedures.TitleText = getProcedurePanelHeading(); // get the panel heading @@ -2478,7 +2343,6 @@ namespace VEPROMS displayBookMarks.MyDisplayTabControl = tc; // allows bookmark selection to bring up steps/docs office2007StartButton1.MouseDown += new MouseEventHandler(office2007StartButton1_MouseDown); - //displayRO.EnabledChanged += new EventHandler(displayRO_EnabledChanged); tc.Enter += new EventHandler(tc_Enter); tc.Leave += new EventHandler(tc_Leave); @@ -2488,7 +2352,7 @@ namespace VEPROMS tc.RefreshEnhancedDocument += tc_RefreshEnhancedDocument; tc.CopyStepSelected += tc_CopyStepSelected; // will extend CopyStep info to all child windows (separate windows upgrade) - this.Deactivate += new EventHandler(frmVEPROMS_Deactivate); + Deactivate += new EventHandler(frmVEPROMS_Deactivate); if (VlnSettings.DemoMode) StepRTB.MyFontFamily = GetFamily("Bookman Old Style"); displaySearch1.Enter += new EventHandler(displaySearch1_Enter); @@ -2499,9 +2363,11 @@ namespace VEPROMS if (RunningNewRevision && ShowEULA() != DialogResult.OK) { - Timer tmrShutDown = new Timer(); - tmrShutDown.Interval = 250; - tmrShutDown.Tick += new EventHandler(tmrShutDown_Tick); + Timer tmrShutDown = new Timer + { + Interval = 250 + }; + tmrShutDown.Tick += new EventHandler(tmrShutDown_Tick); tmrShutDown.Enabled = true; } else @@ -2509,21 +2375,18 @@ namespace VEPROMS tmrAutomatic.Enabled = true; } - //// Shutoff UpdateFormats for Production Mode - //if (Volian.Base.Library.VlnSettings.ProductionMode) - // btnAdmin.Visible = false; - StepTabRibbon.PasteNoReturnsSetting = Properties.Settings.Default.PasteNoReturns; - StepTabRibbon.PastePlainTextSetting = Properties.Settings.Default.PastePlainText; - StepTabRibbon.SpecifiedVisioPath = Properties.Settings.Default.VisioPath; + StepTabRibbon.PasteNoReturnsSetting = Settings.Default.PasteNoReturns; + StepTabRibbon.PastePlainTextSetting = Settings.Default.PastePlainText; + StepTabRibbon.SpecifiedVisioPath = Settings.Default.VisioPath; Activate(); // RHM20150506 Multi-line ItemID TextBox if (MyParent == null) { - this.txtSearch.Text = Volian.Base.Library.VlnSettings.GetItemIDs().Replace(",", "\r\n"); + txtSearch.Text = VlnSettings.GetItemIDs().Replace(",", "\r\n"); // Open First Item - if (!string.IsNullOrEmpty(this.txtSearch.Text) && this.txtSearch.Text.Length > 0 && !this.txtSearch.Text.Contains("\r\n")) + if (!string.IsNullOrEmpty(txtSearch.Text) && txtSearch.Text.Length > 0 && !txtSearch.Text.Contains("\r\n")) { CurrentID = txtSearch.Text; } @@ -2572,7 +2435,7 @@ namespace VEPROMS // We were running into performace and random hanging issues with the Word tabs - maybe windows event related. if (_Procedure == null || _Procedure.HasWordContent) continue; //skip and continue with foreach OpenItem(_Procedure); - if (tc.MyEditItem == null) continue; // skip and continue with foreach + if (tc.MyEditItem == null) continue; // skip and continue with foreach // SelectedStepTabPanel needs to be set so the print buttons on the ribbon will work. SelectedStepTabPanel = tc.MyEditItem.MyStepPanel.MyStepTabPanel; @@ -2595,19 +2458,17 @@ namespace VEPROMS void tc_RefreshEnhancedDocument(object sender, ItemSelectedChangedEventArgs args) { // if the procedure is opened then move to the select step - if (!Properties.Settings.Default.SeparateWindows) + if (!Settings.Default.SeparateWindows) { tc.RefreshItem(args.MyItemInfo); } else { int versionID = args.MyItemInfo.MyDocVersion.VersionID; - frmVEPROMS child = null; - - if (PROMSWindowForms.ContainsKey(versionID)) + if (PROMSWindowForms.ContainsKey(versionID)) { - child = PROMSWindowForms[versionID]; - child.RefreshItem(args.MyItemInfo); + frmVEPROMS child = PROMSWindowForms[versionID]; + child.RefreshItem(args.MyItemInfo); } } } @@ -2620,7 +2481,7 @@ namespace VEPROMS { frmVEPROMS tmp = PROMSWindowForms[k]; - if (tmp.MyDocVersion.VersionID != this.SelectedDVI.VersionID) + if (tmp.MyDocVersion.VersionID != SelectedDVI.VersionID) tmp.tc.MyCopyStep = tc.MyCopyStep; else if (tmp.MyParent != null) tmp.MyParent.tc.MyCopyStep = tc.MyCopyStep; @@ -2638,21 +2499,21 @@ namespace VEPROMS foreach (SessionInfo si in sil) { - if (si.DTSEnd == null && si.MachineName == Environment.MachineName && si.UserID == Volian.Base.Library.VlnSettings.UserID) + if (si.DTSEnd == null && si.MachineName == Environment.MachineName && si.UserID == VlnSettings.UserID) { try { - System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(si.ProcessID); + System.Diagnostics.Process p = Process.GetProcessById(si.ProcessID); } - catch (Exception ex)// Process not found - { + catch (Exception)// Process not found + { // Remove Session record associated with a closed process Session.Delete(si.SessionID); } } else if (si.DTSEnd == null) { - i = i + 1; + i++; } } @@ -2672,7 +2533,7 @@ namespace VEPROMS { if (_PROMSWindowForms == null) { - if (_MyParent == null) + if (MyParent == null) _PROMSWindowForms = new Dictionary(); else _PROMSWindowForms = MyParent.PROMSWindowForms; @@ -2695,9 +2556,8 @@ namespace VEPROMS return; } - frmVEPROMS child = null; - - if (PROMSWindowForms.ContainsKey(versionID)) + frmVEPROMS child; + if (PROMSWindowForms.ContainsKey(versionID)) { child = PROMSWindowForms[versionID]; // use existing child window } @@ -2788,7 +2648,7 @@ namespace VEPROMS // RHM20150507 Table Scrunch // B2018-033 VCS SAG-6 Steps 3 and 9 and SACRG1 Step 13 // Set default Scrunching flags - private TableScrunching _DefaultScrunchingRules = TableScrunching.AllPhases; + private readonly TableScrunching _DefaultScrunchingRules = TableScrunching.AllPhases; void btnPrint1_Click(object sender, EventArgs e) { @@ -2806,7 +2666,7 @@ namespace VEPROMS } } - DialogResult dr = System.Windows.Forms.DialogResult.Yes; + DialogResult dr = DialogResult.Yes; // RHM20150507 Table Scrunch Rtf2Pdf.AllowTableScrunching = cbScrunch.Checked ? _DefaultScrunchingRules : TableScrunching.None; @@ -2815,15 +2675,16 @@ namespace VEPROMS { ProcedureInfo proc = dicProcs[key]; - DlgPrintProcedure prnDlg = new DlgPrintProcedure(proc, true); - prnDlg.MySessionInfo = MySessionInfo; - prnDlg.Prefix = proc.MyDocVersion.VersionID.ToString() + "_"; - prnDlg.Automatic = true; - prnDlg.OpenAfterCreate = (dr == System.Windows.Forms.DialogResult.Yes); - prnDlg.SetupForProcedure(); + DlgPrintProcedure prnDlg = new DlgPrintProcedure(proc, true) + { + MySessionInfo = MySessionInfo, + Prefix = proc.MyDocVersion.VersionID.ToString() + "_", + Automatic = true, + OpenAfterCreate = (dr == DialogResult.Yes) + }; + prnDlg.SetupForProcedure(); prnDlg.CreatePDF(); - //prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window } } @@ -2954,9 +2815,10 @@ namespace VEPROMS } - //C2024-036 IntelliSense - //Collection to block for task to complete - private BlockingCollection blockingQueueFilter = new BlockingCollection(); + //C2024-036 IntelliSense + //Collection to block for task to complete + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private BlockingCollection blockingQueueFilter = new BlockingCollection(); //C2024-036 IntelliSense // When Text Changes, Perform the filtering @@ -3003,28 +2865,28 @@ namespace VEPROMS //Step 1: reload the base tree VETreeNode tbase = (VETreeNode)tv.Nodes[0]; tbase.ChildrenLoaded = false; - this.Invoke((Action) (() => { tbase.RefreshNode(); })); + Invoke((Action) (() => { tbase.RefreshNode(); })); if (!string.IsNullOrEmpty(fltrtxt)) { //Step 2: Expand all TreeNodes - this.Invoke((Action)(() => { LoadAllProcedures(tbase); })); + Invoke((Action)(() => { LoadAllProcedures(tbase); })); //Step 3: get items that match filter to those containing the title or number List filterlist = GetMatchingTreeNodes(tbase, fltrtxt); //Step 4: filter to those containing the title or number - this.Invoke((Action)(() => {FilterTreeNodes(tbase, filterlist);})); + Invoke((Action)(() => {FilterTreeNodes(tbase, filterlist);})); //Step 5: refresh the view - this.Invoke((Action)(() => {tv.Update();})); + Invoke((Action)(() => {tv.Update();})); //Step 6: select 1st procedure in tree view - this.Invoke((Action)(() => {SelectFirstProcedure(filterlist);})); + Invoke((Action)(() => {SelectFirstProcedure(filterlist);})); } //Step 7: set progress bar as done - this.Invoke((Action)(() => {ProgBarText = "Filtering Complete";})); + Invoke((Action)(() => {ProgBarText = "Filtering Complete";})); } @@ -3046,17 +2908,11 @@ namespace VEPROMS tv.Focus(); } - void btnPrevious_Click(object sender, EventArgs e) - { - CurrentID = FindPreviousLine(); - } + void btnPrevious_Click(object sender, EventArgs e) => CurrentID = FindPreviousLine(); - void btnNext_Click(object sender, EventArgs e) - { - CurrentID = FindNextLine(); - } + void btnNext_Click(object sender, EventArgs e) => CurrentID = FindNextLine(); - public string CurrentID + public string CurrentID { get { @@ -3097,13 +2953,12 @@ namespace VEPROMS if (txtSearch.SelectionLength > 0) txtSearch.SelectionLength = 0; - string sub = txtSearch.Text; int selStart = 0; if (txtSearch.SelectionStart == 0) return null; if (txtSearch.SelectionStart > 2) { - sub = txtSearch.Text.Substring(0, txtSearch.SelectionStart - 2); + string sub = txtSearch.Text.Substring(0, txtSearch.SelectionStart - 2); if (sub.Contains("\n")) { selStart = sub.LastIndexOf("\r\n") + 2; @@ -3187,52 +3042,56 @@ namespace VEPROMS tc.SelectedDisplayTabItem = dti; dti.SelectedItemInfo = ii; tv.AdjustTree(ii); - lblItemID.Text = string.Format("ItemID = {0}", ii.ItemID); + lblItemID.Text = $"ItemID = {ii.ItemID}"; } else { - MessageBox.Show(string.Format("Looking for: {0}", str), "No item found"); + MessageBox.Show($"Looking for: {str}", "No item found"); } } private static ItemInfo GetItemInfoFromString(string str) // RHM20150506 Multi-Line ItemID TextBox { ItemInfo ii = null; - int id = 0; - ContentInfo ci = null; + ContentInfo ci = null; - if (str.ToUpper().StartsWith("C=")) - { - if (int.TryParse(str.Substring(2), out id)) - ci = ContentInfo.Get(id); + int id; + if (str.ToUpper().StartsWith("C=")) + { + if (int.TryParse(str.Substring(2), out id)) + ci = ContentInfo.Get(id); - if (ci != null) - ii = ci.ContentItems[0]; - } - else - { - if (int.TryParse(str, out id)) - ii = ItemInfo.Get(id); - } + if (ci != null) + ii = ci.ContentItems[0]; + } + else + { + if (int.TryParse(str, out id)) + ii = ItemInfo.Get(id); + } - return ii; + return ii; } void btnAdministrativeTools_Click(object sender, EventArgs e) { - frmBatchRefresh frm = new frmBatchRefresh(MySessionInfo, this); - frm.ProgressBar = bottomProgBar; - frm.ShowDialog(this); + frmBatchRefresh frm = new frmBatchRefresh(MySessionInfo, this) + { + ProgressBar = bottomProgBar + }; + frm.ShowDialog(this); } void btnGeneralTools_Click(object sender, EventArgs e) { - frmGenTools frm = new frmGenTools(MySessionInfo, this); - frm.ProgressBar = bottomProgBar; - frm.ShowDialog(this); + frmGenTools frm = new frmGenTools(MySessionInfo, this) + { + ProgressBar = bottomProgBar + }; + frm.ShowDialog(this); } - private static VolianTimer _TimeActivity1 = new VolianTimer("frmVEPROMS.cs tmrCloseTabItems_Tick", 2108); + private static readonly VolianTimer _TimeActivity1 = new VolianTimer("frmVEPROMS.cs tmrCloseTabItems_Tick", 2108); void tmrCloseTabItems_Tick(object sender, EventArgs e) { @@ -3321,8 +3180,8 @@ namespace VEPROMS while (proxyUser == null) { - cms.Show(new System.Drawing.Point((System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width - cms.Width) / 2, (System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height - cms.Height) / 2)); - System.Windows.Forms.Application.DoEvents(); + cms.Show(new System.Drawing.Point((Screen.PrimaryScreen.WorkingArea.Width - cms.Width) / 2, (Screen.PrimaryScreen.WorkingArea.Height - cms.Height) / 2)); + Application.DoEvents(); } VlnSettings.UserID = proxyUser; @@ -3361,7 +3220,6 @@ namespace VEPROMS */ if ("|VLN|RICH-WINDOWS10|WINDOWS7-RHM|PAUL-PC|MICHELLE-PC|WIN-O4QLPEH7JKH|HARRY-7100|CAITLIN-PC|".Contains("|" + Environment.UserDomainName.ToUpper() + "|")) { - Random rnd = new Random(DateTime.Now.Year + DateTime.Now.DayOfYear * 1000); MessageBox.Show(this, GetSecurityKey(), "Today's Security Key"); } @@ -3378,9 +3236,9 @@ namespace VEPROMS cms.Items.Add("Choose User"); System.Windows.Forms.ToolStripMenuItem tsmi = cms.Items[0] as System.Windows.Forms.ToolStripMenuItem; - tsmi.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaption);// System.Drawing.Color.Pink; - tsmi.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaptionText); - tsmi.Font = new System.Drawing.Font(tsmi.Font, System.Drawing.FontStyle.Bold); + tsmi.BackColor = Color.FromKnownColor(KnownColor.ActiveCaption);// System.Drawing.Color.Pink; + tsmi.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText); + tsmi.Font = new System.Drawing.Font(tsmi.Font, FontStyle.Bold); UserInfoList uil = UserInfoList.Get(); foreach (UserInfo ui in uil) @@ -3391,7 +3249,7 @@ namespace VEPROMS { if (mi.EndDate == string.Empty) { - string txt = string.Format("{0} - {1}", ui.UserID, mi.MyGroup.GroupName); + string txt = $"{ui.UserID} - {mi.MyGroup.GroupName}"; ToolStripItem tsi = cms.Items.Add(txt, null, new EventHandler(User_Click)); tsi.Tag = ui; break; @@ -3405,14 +3263,12 @@ namespace VEPROMS private void User_Click(object sender, EventArgs e) { - ToolStripMenuItem tsmi = sender as ToolStripMenuItem; - - if (tsmi != null) - { - UserInfo ui = tsmi.Tag as UserInfo; - proxyUser = ui.UserID; - } - } + if (sender is ToolStripMenuItem tsmi) + { + UserInfo ui = tsmi.Tag as UserInfo; + proxyUser = ui.UserID; + } + } void btnManageSecurity_Click(object sender, EventArgs e) { @@ -3454,35 +3310,42 @@ namespace VEPROMS private static DialogResult ShowInputDialog(ref string input) { System.Drawing.Size size = new System.Drawing.Size(200, 70); - Form inputBox = new Form(); + Form inputBox = new Form + { + FormBorderStyle = FormBorderStyle.FixedDialog, + ClientSize = size, + Text = "Enter Password", + StartPosition = FormStartPosition.CenterScreen + }; - inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - inputBox.ClientSize = size; - inputBox.Text = "Enter Password"; - inputBox.StartPosition = FormStartPosition.CenterScreen; + System.Windows.Forms.TextBox textBox = new TextBox + { + Size = new System.Drawing.Size(size.Width - 10, 23), + Location = new System.Drawing.Point(5, 5), + PasswordChar = '*', + Text = input + }; + inputBox.Controls.Add(textBox); - System.Windows.Forms.TextBox textBox = new TextBox(); - textBox.Size = new System.Drawing.Size(size.Width - 10, 23); - textBox.Location = new System.Drawing.Point(5, 5); - textBox.PasswordChar = '*'; - textBox.Text = input; - inputBox.Controls.Add(textBox); + Button okButton = new Button + { + DialogResult = DialogResult.OK, + Name = "okButton", + Size = new System.Drawing.Size(75, 23), + Text = "&OK", + Location = new System.Drawing.Point(size.Width - 80 - 80, 39) + }; + inputBox.Controls.Add(okButton); - Button okButton = new Button(); - okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - okButton.Name = "okButton"; - okButton.Size = new System.Drawing.Size(75, 23); - okButton.Text = "&OK"; - okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39); - inputBox.Controls.Add(okButton); - - Button cancelButton = new Button(); - cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - cancelButton.Name = "cancelButton"; - cancelButton.Size = new System.Drawing.Size(75, 23); - cancelButton.Text = "&Cancel"; - cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39); - inputBox.Controls.Add(cancelButton); + Button cancelButton = new Button + { + DialogResult = DialogResult.Cancel, + Name = "cancelButton", + Size = new System.Drawing.Size(75, 23), + Text = "&Cancel", + Location = new System.Drawing.Point(size.Width - 80, 39) + }; + inputBox.Controls.Add(cancelButton); DialogResult result = inputBox.ShowDialog(); @@ -3519,23 +3382,24 @@ namespace VEPROMS void tmrShutDown_Tick(object sender, EventArgs e) { (sender as Timer).Enabled = false; - this.Close(); + Close(); } private DialogResult ShowEULA() { string eulaFile = string.Format(@"\{0}", VlnSettings.EULAfile); - string strEULA = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + eulaFile; - //string strEULA = System.Environment.CurrentDirectory + eulaFile; - frmViewTextFile ViewFile = new frmViewTextFile(strEULA, RichTextBoxStreamType.PlainText); - ViewFile.Text = "End-User License Agreement"; - ViewFile.ButtonText = "Agree"; + string strEULA = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + eulaFile; + frmViewTextFile ViewFile = new frmViewTextFile(strEULA, RichTextBoxStreamType.PlainText) + { + Text = "End-User License Agreement", + ButtonText = "Agree" + }; - if (ViewFile.ShowDialog() == DialogResult.OK) + if (ViewFile.ShowDialog() == DialogResult.OK) { System.Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; string thisVersion = ver.Major.ToString() + "." + ver.Minor.ToString(); - Properties.Settings.Default.LastVersion = thisVersion; + Settings.Default.LastVersion = thisVersion; return DialogResult.OK; } @@ -3546,19 +3410,16 @@ namespace VEPROMS { get { - string lastVersion = Properties.Settings.Default.LastVersion; + string lastVersion = Settings.Default.LastVersion; System.Version ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; - string thisVersion = ver.Major.ToString() + "." + ver.Minor.ToString(); + string thisVersion = $"{ver.Major}.{ver.Minor}"; return thisVersion != lastVersion; } } - void displayHistory_Enter(object sender, EventArgs e) - { - tc.HideCaret(); - } + void displayHistory_Enter(object sender, EventArgs e) => tc.HideCaret(); - void AnnotationTypeInfoList_ListChanged() + void AnnotationTypeInfoList_ListChanged() { displaySearch1.SetupAnnotationSearch(ctrlAnnotationDetails, tc); ctrlAnnotationDetails.SetupAnnotations(displaySearch1); @@ -3566,7 +3427,7 @@ namespace VEPROMS private void RunAutomatic() { - string[] parameters = System.Environment.CommandLine.Split(" ".ToCharArray()); + string[] parameters = Environment.CommandLine.Split(" ".ToCharArray()); bool ranAuto = false; foreach (string parameter in parameters) @@ -3611,8 +3472,6 @@ namespace VEPROMS } prnDlg.AllowDateTimePrefixSuffix = false; //C2018-033 don't append any selected date/time pdf file prefix or suffix (defined in working draft properties) prnDlg.ShowDialog(this); // RHM 20120925 - Center dialog over PROMS window - //prnDlg.FormClosed += new FormClosedEventHandler(prnDlg_FormClosed); - //while (!_RunNext) Application.DoEvents(); } @@ -3622,7 +3481,7 @@ namespace VEPROMS BaseLnSettings.blBaseLine = false; if (ranAuto) { - this.Close(); + Close(); } } } @@ -3642,38 +3501,23 @@ namespace VEPROMS ribbonControl1.Expanded = !ribbonControl1.Expanded; } - void frmVEPROMS_Deactivate(object sender, EventArgs e) - { - tc.HideCaret(); // Hide the pseudo cursor (caret) - } + void frmVEPROMS_Deactivate(object sender, EventArgs e) => tc.HideCaret(); // Hide the pseudo cursor (caret) - void tc_Leave(object sender, EventArgs e) + void tc_Leave(object sender, EventArgs e) { if (tc.ShuttingDown) return; tc.ShowCaret();// Show the pseudo cursor (caret) } - void tc_Enter(object sender, EventArgs e) - { - tc.HideCaret();// Hide the pseudo cursor (caret) - } + void tc_Enter(object sender, EventArgs e) => tc.HideCaret();// Hide the pseudo cursor (caret) - void displaySearch1_Enter(object sender, EventArgs e) - { - tc.HideCaret();// Hide the pseudo cursor (caret) - } + void displaySearch1_Enter(object sender, EventArgs e) => tc.HideCaret();// Hide the pseudo cursor (caret) - void ctrlAnnotationDetails_Enter(object sender, EventArgs e) - { - tc.HideCaret();// Hide the pseudo cursor (caret) - } + void ctrlAnnotationDetails_Enter(object sender, EventArgs e) => tc.HideCaret();// Hide the pseudo cursor (caret) - void _MyMRIList_AfterRemove(object sender) - { - SetupMRU(); - } + void _MyMRIList_AfterRemove(object sender) => SetupMRU(); - private void SetupButtons() + private void SetupButtons() { if (!VlnSettings.DebugMode) { @@ -3691,8 +3535,8 @@ namespace VEPROMS { // C2024-007: On Proms main form, allow for control of whether the FontMenu // combo box is displayed. Only done when running in debugmode - cmbFont.Visible = Volian.Base.Library.VlnSettings.GetCommandFlag("FontMenu"); - lblDummy.Visible = !Volian.Base.Library.VlnSettings.GetCommandFlag("FontMenu"); + cmbFont.Visible = VlnSettings.GetCommandFlag("FontMenu"); + lblDummy.Visible = !VlnSettings.GetCommandFlag("FontMenu"); } } @@ -3703,10 +3547,11 @@ namespace VEPROMS icRecentDocs.SubItems.Clear(); if (_MyMRIList.Count > 0) { - LabelItem lblItem = new LabelItem(); - lblItem.Text = "Recent Documents:"; - icRecentDocs.SubItems.Add(lblItem); - //icRecentDocs.SubItems.Add(); + LabelItem lblItem = new LabelItem + { + Text = "Recent Documents:" + }; + icRecentDocs.SubItems.Add(lblItem); for (int i = 0; i < _MyMRIList.Count; i++) { MostRecentItem mri = _MyMRIList[i]; @@ -3728,15 +3573,14 @@ namespace VEPROMS { ButtonItem btnItem = (ButtonItem)sender; MostRecentItem mri = _MyMRIList.Add((int)(btnItem.Tag)); - //SaveMRU(); SetupMRU(); if (mri != null) tc.OpenItem(mri.MyItemInfo); } private void SaveMRU() { - if (_MyMRIList != null) Properties.Settings.Default.MRIList = _MyMRIList.ToSettings(); - Properties.Settings.Default.TreeviewExpanded = epProcedures.Expanded; - Properties.Settings.Default.Save(); + if (_MyMRIList != null) Settings.Default.MRIList = _MyMRIList.ToSettings(); + Settings.Default.TreeviewExpanded = epProcedures.Expanded; + Settings.Default.Save(); } #endregion @@ -3749,24 +3593,6 @@ namespace VEPROMS { if (_MyMRIList.Add(node.VEObject) != null) SetupMRU(); - #region Sample Display Table Code - // display an exiting table in that rtf grid thing - //if ((_LastStepInfo.MyContent.Type == 20007) || (_LastStepInfo.MyContent.Type == 20009)) - //{ - // //MessageBox.Show("Source Grid"); - // //frmTable newtable1 = new frmTable(_LastStepInfo.MyContent.Text); - // //newtable1.ShowDialog(); - // //MessageBox.Show("IGrid"); - // //frmIGrid newtable2 = new frmIGrid(_LastStepInfo.MyContent.Text); - // //newtable2.ShowDialog(); - // //MessageBox.Show("GridView"); //standard Visual Studio Control - // //frmGridView newtable3 = new frmGridView(_LastStepInfo.MyContent.Text); - // //newtable3.ShowDialog(); - // MessageBox.Show("FlexCell"); - // frmFlexCell newtable4 = new frmFlexCell(_LastStepInfo.MyContent.Text); - // newtable4.ShowDialog(); - //} - #endregion ItemInfo ii = node.VEObject as ItemInfo; if (ii != null) tc.OpenItem(ii); SetCaption(node); @@ -3778,21 +3604,16 @@ namespace VEPROMS { VETreeNode vNode = (VETreeNode)args.Node; IVEDrillDownReadOnly veObj = vNode.VEObject; - SectionInfo mySection = veObj as SectionInfo; - if (mySection != null && mySection.MyContent.MyEntry != null) - { - // if it is a word section, find the DisplayTabItem; - DisplayTabItem tabItem = tc.GetProcDisplayTabItem(mySection); - if (tabItem != null) tabItem.MyStepTabPanel.MyStepPanel.Reset(); - } - // Don't select the newly created Step. This will be handled by tmrTreeView - //SetupNodes((VETreeNode)args.Node); - } - private void tv_NodeSelect(object sender, vlnTreeEventArgs args) - { - SetupNodes((VETreeNode)args.Node); - } - private void SetCaption(VETreeNode tn) + if (veObj is SectionInfo mySection && mySection.MyContent.MyEntry != null) + { + // if it is a word section, find the DisplayTabItem; + DisplayTabItem tabItem = tc.GetProcDisplayTabItem(mySection); + tabItem?.MyStepTabPanel.MyStepPanel.Reset(); + } + // Don't select the newly created Step. This will be handled by tmrTreeView + } + private void tv_NodeSelect(object sender, vlnTreeEventArgs args) => SetupNodes((VETreeNode)args.Node); + private void SetCaption(VETreeNode tn) { StringBuilder caption = new StringBuilder(); string sep = string.Empty; @@ -3806,41 +3627,22 @@ namespace VEPROMS } tn = (VETreeNode)tn.Parent; } - caption.Insert(0, VEPROMS.CSLA.Library.Database.DBServer + sep); - this.Text = caption.ToString(); + caption.Insert(0, Database.DBServer + sep); + Text = caption.ToString(); } void tv_OpenItem(object sender, vlnTreeItemInfoEventArgs args) { tc.OpenItem(args.MyItemInfo); } - /// - /// When the treeview is clicked - a timer is set - /// This is done because the focus is returned to the treeview after the click event - /// This approach did not work and was replaced with the code below. - /// The problem was that each time the treeview was clicked, the last selected node - /// was opened again, or the edit window was repositioned. - /// If the item was deleted and another treenode expanded, the click to expand the - /// node would cause the deleted node to be selected. - /// - /// - /// - //private void tv_Click(object sender, EventArgs e) - //{ - //tv.Enabled = false; - //tmrTreeView.Enabled = true; - //} - /// - /// This opens nodes if the mouse is within the bounds of a node. - /// By using the timer, the focus can be passed to the edit window. - /// - /// - /// - void tv_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) - { - _ExpandingTree = false; - } + /// + /// This opens nodes if the mouse is within the bounds of a node. + /// By using the timer, the focus can be passed to the edit window. + /// + /// + /// + void tv_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) => _ExpandingTree = false; - void tv_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) + void tv_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (_ExpandingTree) { @@ -3882,7 +3684,7 @@ namespace VEPROMS } } private frmVEPROMS selectedChildWindow = null; // C2015-022 used for separate windows - private static VolianTimer _TimeActivity2 = new VolianTimer("frmVEPROMS.cs tmrTreeView_Tick", 2697); + private static readonly VolianTimer _TimeActivity2 = new VolianTimer("frmVEPROMS.cs tmrTreeView_Tick", 2697); /// /// This event is fired from the timer after the treeview click event completes /// @@ -3890,18 +3692,15 @@ namespace VEPROMS /// private void tmrTreeView_Tick(object sender, EventArgs e) { - - _TimeActivity2.Open(); bool giveTvFocus = true; tmrTreeView.Enabled = false; // Timer has now fired - VETreeNode tn = tv.SelectedNode as VETreeNode; - if (tn != null) giveTvFocus = !SetupNodes(tn); - tv.Enabled = true; + if (tv.SelectedNode is VETreeNode tn) giveTvFocus = !SetupNodes(tn); + tv.Enabled = true; if (giveTvFocus) tv.Focus(); _TimeActivity2.Close(); } - private static VolianTimer _TimeActivity3 = new VolianTimer("frmVEPROMS.cs tmrAutomatic_Tick", 2711); + private static readonly VolianTimer _TimeActivity3 = new VolianTimer("frmVEPROMS.cs tmrAutomatic_Tick", 2711); private void tmrAutomatic_Tick(object sender, EventArgs e) { @@ -3931,7 +3730,7 @@ namespace VEPROMS #region Property Page and Grid DialogResult tv_NodeOpenProperty(object sender, vlnTreePropertyEventArgs args) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; DialogResult dr = DialogResult.Cancel; if ((int)Settings.Default["PropPageStyle"] == (int)PropPgStyle.Grid) { @@ -3946,7 +3745,7 @@ namespace VEPROMS if (!MySessionInfo.CanCheckOutItem(args.FolderConfig.MyFolder.FolderID, CheckOutType.Folder, ref message)) { MessageBox.Show(this, message, "Folder Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return DialogResult.None; } int ownerID = MySessionInfo.CheckOutItem(args.FolderConfig.MyFolder.FolderID, CheckOutType.Folder); @@ -3965,14 +3764,16 @@ namespace VEPROMS if (!MySessionInfo.CanCheckOutItem(args.DocVersionConfig.MyDocVersion.VersionID, CheckOutType.DocVersion, ref message)) { MessageBox.Show(this, message, "Working Draft Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return DialogResult.None; } int ownerID = MySessionInfo.CheckOutItem(args.DocVersionConfig.MyDocVersion.VersionID, CheckOutType.DocVersion); - frmVersionsProperties frmver = new frmVersionsProperties(args.DocVersionConfig); - frmver.ProgressBar = bottomProgBar; - frmver.DisplaySearch1 = displaySearch1; //B2017-230 provide access to global search - dr = frmver.ShowDialog(); + frmVersionsProperties frmver = new frmVersionsProperties(args.DocVersionConfig) + { + ProgressBar = bottomProgBar, + DisplaySearch1 = displaySearch1 //B2017-230 provide access to global search + }; + dr = frmver.ShowDialog(); if (frmver._showApplicSearchResults) //B2017-230 open global search with places that specifiy the applicabilty that the user tried to delete { toolsPanel.Expanded = true; @@ -3988,7 +3789,7 @@ namespace VEPROMS { message = message.Replace("\r\nWould You like to open the procedure in View Only Mode?", ""); MessageBox.Show(this, message, "Procedure Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return DialogResult.None; } int ownerID = MySessionInfo.CheckOutItem(args.ProcedureConfig.MyProcedure.ItemID, CheckOutType.Procedure); @@ -3998,21 +3799,13 @@ namespace VEPROMS } else if (args.SectionConfig != null) { - //// If this is a word document, close any edit sessions... - //ItemInfo ii = null; - //using (Section tmp = args.SectionConfig.MySection) - //{ - // ii = ItemInfo.Get(tmp.ItemID); - // if (!ii.IsStepSection) tc.CloseWordItem(ii); - //} - frmSectionProperties frmsec = new frmSectionProperties(args.SectionConfig); string message = string.Empty; if (!MySessionInfo.CanCheckOutItem(args.SectionConfig.MySection.MySectionInfo.MyProcedure.ItemID, CheckOutType.Procedure, ref message)) { message = message.Replace("\r\nWould You like to open the procedure in View Only Mode?", ""); MessageBox.Show(this, message, "Procedure Already Checked Out", MessageBoxButtons.OK, MessageBoxIcon.Warning); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return DialogResult.None; } int ownerID; @@ -4033,152 +3826,48 @@ namespace VEPROMS MySessionInfo.CheckInItem(ownerID); } } - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; return dr; } - #endregion - #endregion + #endregion + #endregion - #region ColorStuff - /// - /// Get a System.Drawing.Color from an Argb or color name - /// - /// Color Name or "[(alpha,)red,green,blue]" - /// - private static Color cGetColor(string strColor) - { - // This was copied from frmFolderProperties.CS - Color rtnColor; - if (strColor == null || strColor.Equals("")) - rtnColor = Color.White; - else - { - if (strColor[0] == '[') - { - string[] parts = strColor.Substring(1, strColor.Length - 2).Split(",".ToCharArray()); - int parts_cnt = 0; - foreach (string s in parts) - { - parts[parts_cnt] = parts[parts_cnt].TrimStart(' '); // remove preceeding blanks - parts_cnt++; - } - if (parts_cnt == 3) - rtnColor = Color.FromArgb(Int32.Parse(parts[0]), Int32.Parse(parts[1]), Int32.Parse(parts[2])); - else - rtnColor = Color.FromArgb(Int32.Parse(parts[0].Substring(2)), Int32.Parse(parts[1].Substring(2)), Int32.Parse(parts[2].Substring(2)), Int32.Parse(parts[3].Substring(2))); - } - else rtnColor = Color.FromName(strColor); - } - return rtnColor; - } - //private void SetupEditorColors(DisplayPanel vlnCSLAPanel1, TabPage pg) - //{ - // // setup color - // if (_LastFolderInfo == null) - // { - // // user didn't select a FolderInfo type of node. - // // walk up the tree to find the first FolderInfo node type - // VETreeNode tn = (VETreeNode)(tv.SelectedNode); - // while (tn != null && tn.VEObject.GetType() != typeof(FolderInfo)) - // tn = (VETreeNode)tn.Parent; - // _LastFolderInfo = (FolderInfo)(tn.VEObject); - // _LastFolder = _LastFolderInfo.Get(); - // } + #region Progress Bar - // if ((_LastFolderInfo.FolderConfig.Color_editbackground != null) && !(_LastFolderInfo.FolderConfig.Color_editbackground.Equals(""))) - // { - // vlnCSLAPanel1.ActiveColor = cGetColor(_LastFolderInfo.FolderConfig.Color_editbackground); - // } - // if ((_LastFolderInfo.FolderConfig.Default_BkColor != null) && !(_LastFolderInfo.FolderConfig.Default_BkColor.Equals(""))) - // { - // vlnCSLAPanel1.InactiveColor = _LastFolderInfo.FolderConfig.Default_BkColor; - // vlnCSLAPanel1.TabColor = vlnCSLAPanel1.InactiveColor; - // vlnCSLAPanel1.PanelColor = vlnCSLAPanel1.InactiveColor; - // pg.BackColor = vlnCSLAPanel1.InactiveColor; - // } - //} - #endregion + /// + /// Used for the status bar in the lower left corner of the main screen + /// + /// + /// + void tn_LoadingChildrenSQL(object sender, VETreeNodeEventArgs args) => ProgBarText = "Loading SQL"; - #region Table Insert Sample 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); - //} + /// + /// Used for the status bar in the lower left corner of the main screen + /// + /// + /// + void tn_LoadingChildrenValue(object sender, VETreeNodeEventArgs args) => ProgBarValue = args.Value; - //private void TablePickerDlg(object sender, EventArgs e, Point loc, int top) - //{ - // Accentra.Controls.TablePicker tp = new Accentra.Controls.TablePicker(); - // tp.Location = loc; - // tp.Top += top; - // tp.Show(); - // while (tp.Visible) - // { - // Application.DoEvents(); - // System.Threading.Thread.Sleep(0); - // } - // // This was used to display a dialog containing a table grid - // // using a product called Source Grid - was for demo purposes only - // // - // //if (!tp.Cancel) - // //{ - // // frmTable newtable = new frmTable(tp.SelectedRows, tp.SelectedColumns); - // // newtable.Show(); - // //} - //} - #endregion - - #region Progress Bar - - /// - /// Used for the status bar in the lower left corner of the main screen - /// - /// - /// - void tn_LoadingChildrenSQL(object sender, VETreeNodeEventArgs args) - { - ProgBarText = "Loading SQL"; - } - - /// - /// Used for the status bar in the lower left corner of the main screen - /// - /// - /// - void tn_LoadingChildrenValue(object sender, VETreeNodeEventArgs args) - { - ProgBarValue = args.Value; - } - - /// - /// Used for the status bar in the lower left corner of the main screen - /// - /// - /// - void tn_LoadingChildrenMax(object sender, VETreeNodeEventArgs args) + /// + /// Used for the status bar in the lower left corner of the main screen + /// + /// + /// + void tn_LoadingChildrenMax(object sender, VETreeNodeEventArgs args) { //_MyLog.DebugFormat("tn_LoadingChildrenMax \n{0}", Volian.Base.Library.vlnStackTrace.StackToStringLocal(2, 10)); ProgBarMax = args.Value; ProgBarText = "Loading..."; } - /// - /// Used for the status bar in the lower left corner of the main screen - /// - /// - /// - void tn_LoadingChildrenDone(object sender, VETreeNodeEventArgs args) - { - if (VlnSettings.DebugMode) - ProgBarText = args.Info + " Seconds"; - else - ProgBarText = ""; - } + /// + /// Used for the status bar in the lower left corner of the main screen + /// + /// + /// + void tn_LoadingChildrenDone(object sender, VETreeNodeEventArgs args) => ProgBarText = VlnSettings.DebugMode ? $"{args.Info} Seconds" : ""; - public int ProgBarMax + public int ProgBarMax { get { return bottomProgBar.Maximum; } set { bottomProgBar.Maximum = value; } @@ -4202,51 +3891,6 @@ namespace VEPROMS #endregion - #region Find/Replace and Search - - /// - /// Find/Replace button on the ribbon - /// Display the Find/Replace dialog - /// - /// - /// - //private void btnFindRplDlg_Click_1(object sender, EventArgs e) - //{ - // FindReplace frmFindRepl = new FindReplace(); - // frmFindRepl.Show(); - //} - - /// - /// Global Search button on the ribbon - /// Opens the Information Pannel and selects the Results tab - /// - /// - /// - //private void btnGlbSrch_Click(object sender, EventArgs e) - //{ - // toolsPanel.Expanded = true; - // toolsTabs.SelectedTab = toolstabResults; - //} - - #endregion - - #region Similar Steps - - /// - /// Similar Steps button on the ribbon - /// Opens the Information Pannel and selects the Results tab - /// - /// - /// - private void btnSimStps_Click(object sender, EventArgs e) - { - //infoPanel.Expanded = true; - //infoTabs.SelectedTab = toolstabResults; - //btnSimStpsRslt.Checked = true; - } - - #endregion - #region Help/About /// @@ -4261,29 +3905,23 @@ namespace VEPROMS about.ShowDialog(); } - /// - /// Volian Web button on the ribbon - /// display the Volian web site on a pop up form - /// - /// - /// - private void btnVlnWeb_Click(object sender, EventArgs e) - { - //VlnWeb veWWW = new VlnWeb(); - //veWWW.Show(); - System.Diagnostics.Process sdp = System.Diagnostics.Process.Start("http://www.volian.com"); - //sdp.WaitForInputIdle(); - } + /// + /// Volian Web button on the ribbon + /// display the Volian web site on a pop up form + /// + /// + /// + private void btnVlnWeb_Click(object sender, EventArgs e) => _ = Process.Start("http://www.volian.com"); - #endregion + #endregion - #region Ribbon - /// - /// This Opens the treeView or opens the selected item in the TreeView - /// - /// - /// - private void btnOpen_Click(object sender, EventArgs e) + #region Ribbon + /// + /// This Opens the treeView or opens the selected item in the TreeView + /// + /// + /// + private void btnOpen_Click(object sender, EventArgs e) { if (!epProcedures.Expanded) // If panel not expanded - expand it. { @@ -4294,39 +3932,34 @@ namespace VEPROMS } else { - // TODO: DeleteMe - //VETreeNode tn = (VETreeNode)(tv.SelectedNode); tv.OpenNode(); } } private void btnNew_Click(object sender, EventArgs e) { if (!epProcedures.Expanded) return; - VETreeNode vtn = tv.SelectedNode as VETreeNode; - if (vtn == null) return; // nothing was selected. - if (btnNew.SubItems.Count > 0) return; // submenu will be displayed + if (!(tv.SelectedNode is VETreeNode vtn)) return; // nothing was selected. + if (btnNew.SubItems.Count > 0) return; // submenu will be displayed vtn.Expand(); - // Determine type of 'new' based on tree node's object type. The - // only options here are those that would not have created, based on - // containers, a submenu (see the office2007buttonstartbutton1_click code) - FolderInfo fi = vtn.VEObject as FolderInfo; - if (fi != null) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.Folder); - return; - } + // Determine type of 'new' based on tree node's object type. The + // only options here are those that would not have created, based on + // containers, a submenu (see the office2007buttonstartbutton1_click code) + if (vtn.VEObject is FolderInfo) + { + tv.tv_NodeNew(vlnTreeView.MenuSelections.Folder); + return; + } - DocVersionInfo dvi = vtn.VEObject as DocVersionInfo; - if (dvi != null) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.Procedure); - return; - } + if (vtn.VEObject is DocVersionInfo) + { + tv.tv_NodeNew(vlnTreeView.MenuSelections.Procedure); + return; + } - // All other types are handled with sub-menus. + // All other types are handled with sub-menus. - } + } /// /// Options button on the dialog that appears when the V icon is clicked (top left of application window) @@ -4336,38 +3969,36 @@ namespace VEPROMS /// private void btnOptions_Click(object sender, EventArgs e) { - frmSysOptions VeSysOpts = new frmSysOptions(); - VeSysOpts.CanChangeSeparateWindowsSetting = !tc.MoreThanOneProcedureSetIsOpen; - VeSysOpts.ShowDialog(); - StepTabRibbon.PasteNoReturnsSetting = Properties.Settings.Default.PasteNoReturns; - StepTabRibbon.PastePlainTextSetting = Properties.Settings.Default.PastePlainText; - StepTabRibbon.SpecifiedVisioPath = Properties.Settings.Default.VisioPath; - tc.SyncEnhancedDocuments = Properties.Settings.Default.SyncEnhancedDocuments; - tc.SeparateWindows = Properties.Settings.Default.SeparateWindows; + frmSysOptions VeSysOpts = new frmSysOptions + { + CanChangeSeparateWindowsSetting = !tc.MoreThanOneProcedureSetIsOpen + }; + VeSysOpts.ShowDialog(); + StepTabRibbon.PasteNoReturnsSetting = Settings.Default.PasteNoReturns; + StepTabRibbon.PastePlainTextSetting = Settings.Default.PastePlainText; + StepTabRibbon.SpecifiedVisioPath = Settings.Default.VisioPath; + tc.SyncEnhancedDocuments = Settings.Default.SyncEnhancedDocuments; + tc.SeparateWindows = Settings.Default.SeparateWindows; } - /// - /// Exit button on the dialog that appears when the V icon is clicked (top left of application window) - /// note that the "V icon" is also called the Office 2007 Start Button - /// - /// - /// - private void btnExit_Click(object sender, EventArgs e) - { - this.Close(); - } - #endregion + /// + /// Exit button on the dialog that appears when the V icon is clicked (top left of application window) + /// note that the "V icon" is also called the Office 2007 Start Button + /// + /// + /// + private void btnExit_Click(object sender, EventArgs e) => Close(); + #endregion - #region InfoTabRO + #region InfoTabRO - private void infotabRO_Click(object sender, EventArgs e) + private void infotabRO_Click(object sender, EventArgs e) { infoPanel.Expanded = true; infoTabs.SelectedTab = infotabRO; displayRO.ProgressBar = bottomProgBar; - displayRO.MyRTB = (SelectedStepTabPanel == null) ? null : - SelectedStepTabPanel.MyStepPanel.SelectedEditItem == null ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB; + displayRO.MyRTB = SelectedStepTabPanel?.MyStepPanel.SelectedEditItem?.MyStepRTB; displayRO.LoadTree(this); //B2022-026 RO Memory reduction coding (Jakes Merge) } @@ -4381,19 +4012,12 @@ namespace VEPROMS if (tc == null || tc.SelectedDisplayTabItem == null) return; if (SelectedStepTabPanel == null) return; displayTransition.MyRTB = SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB; - //displayTransition.RangeColor = global::VEPROMS.Properties.Settings.Default.TransitionRangeColor; - // RHM - The follwing line was reseting the settings on the transtion panel to "not" show the currently selected transition. - //displayTransition.CurTrans = null; } - #endregion + #endregion - #region InfoTabLibDocs - private void tabItemLibDocs_Click(object sender, EventArgs e) - { - displayLibDocs.RefreshLibDocPanel(tc); - //displayLibDocs.LibDocListFillIn(tc); - } - private void tv_SectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args) + #region InfoTabLibDocs + private void tabItemLibDocs_Click(object sender, EventArgs e) => displayLibDocs.RefreshLibDocPanel(tc); + private void tv_SectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args) { if (!args.MySectionInfo.IsStepSection) tc.CloseWordItem(args.MySectionInfo, args.IsDeleting); else @@ -4424,7 +4048,7 @@ namespace VEPROMS { infoPanel.Expanded = true; infoTabs.SelectedTab = infotabTags; - displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem; + displayTags.MyEditItem = SelectedStepTabPanel?.MyStepPanel.SelectedEditItem; displayTags.Mydvi = SelectedDVI; } #endregion @@ -4434,14 +4058,15 @@ namespace VEPROMS { infoPanel.Expanded = true; infoTabs.SelectedTab = infotabTags; - displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem; + displayTags.MyEditItem = SelectedStepTabPanel?.MyStepPanel.SelectedEditItem; } #endregion #region PanelSupport private void tc_WordSectionClose(object sender, WordSectionEventArgs args) { - if (!args.MySectionInfo.IsStepSection) tc.CloseWordItem(args.MySectionInfo); + if (!args.MySectionInfo.IsStepSection) + tc.CloseWordItem(args.MySectionInfo); } private void tc_WordSectionDeleted(object sender, WordSectionEventArgs args) { @@ -4461,9 +4086,8 @@ namespace VEPROMS // require refresh of the lib doc panel. if (toolsTabs.SelectedTab == tabItemLibDocs && args.MyItemInfo.IsSection) { - SectionInfo si = args.MyItemInfo as SectionInfo; - if (si != null && (si.MyContent.MyEntry.MyDocument.LibTitle ?? "") != "") displayLibDocs.RefreshLibDocPanel(tc); - } + if (args.MyItemInfo is SectionInfo si && (si.MyContent.MyEntry.MyDocument.LibTitle ?? "") != "") displayLibDocs.RefreshLibDocPanel(tc); + } displayHistory.RefreshChangeList(); } private void tc_PanelTabDisplay(object sender, StepPanelTabDisplayEventArgs args) @@ -4495,7 +4119,6 @@ namespace VEPROMS { infoPanel.Expanded = true; infoTabs.SelectedTab = infotabTags; - displayTags.HighlightChangeStep(); } else if (args.PanelTabName == "Change Image Size") { @@ -4616,8 +4239,8 @@ 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); - this.dlgFindReplace.ToggleReplaceTab(isReviewer ? E_ViewMode.View : E_ViewMode.Edit); + pnl.MyStepTabPanel.MyStepTabRibbon.SetButtonAndMenuEnabling(); + dlgFindReplace.ToggleReplaceTab(isReviewer ? E_ViewMode.View : E_ViewMode.Edit); pnl.MyStepTabPanel.MyStepTabRibbon.ToggleFindReplaceToolTip(isReviewer); } } @@ -4625,8 +4248,8 @@ namespace VEPROMS private void tc_StepPanelModeChange(object sender, StepRTBModeChangeEventArgs args) { - this.lblEditView.Text = args.ViewMode == E_ViewMode.Edit ? "Edit" : "View"; - this.dlgFindReplace.ToggleReplaceTab(args.ViewMode); + lblEditView.Text = args.ViewMode == E_ViewMode.Edit ? "Edit" : "View"; + dlgFindReplace.ToggleReplaceTab(args.ViewMode); // 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 // B2021-044 Added a null reference check. Happend when nothing is opened but a search for Incoming Transitions was done @@ -4637,26 +4260,6 @@ namespace VEPROMS private ItemInfo _CurrentItem = null; private StepRTB _LastStepRTB = null; - //private Timer _TmrRefreshItem = null; - //public Timer TmrRefreshItem - //{ - // get - // { - // if (_TmrRefreshItem == null) - // { - // _TmrRefreshItem = new Timer(); - // _TmrRefreshItem.Interval = 1000; // one second - // _TmrRefreshItem.Tick += _TmrRefreshItem_Tick; - // } - // return _TmrRefreshItem; - // } - //} - //private StepRTB _RefreshRTB = null; - //void _TmrRefreshItem_Tick(object sender, EventArgs e) - //{ - // _TmrRefreshItem.Enabled = false; - // if (_RefreshRTB != null) _RefreshRTB.Focus(); - //} private void tc_ItemSelectedChanged(object sender, ItemSelectedChangedEventArgs args) { @@ -4695,12 +4298,11 @@ namespace VEPROMS } else { - lblItemID.Text = string.Format("ItemID = {0}", args.MyItemInfo.ItemID); + lblItemID.Text = $"ItemID = {args.MyItemInfo.ItemID}"; lblItemID.ForeColor = Color.DarkBlue; if (_CurrentItem != args.MyItemInfo) { - if (_CurrentItem != null) _CurrentItem.Deleted -= new ItemInfoEvent(_CurrentItem_Deleted); _CurrentItem = args.MyItemInfo; } @@ -4814,8 +4416,6 @@ namespace VEPROMS displayHistory.MyEditItem = args.MyEditItem; lblEditView.Text = args.MyEditItem.MyStepPanel.VwMode == E_ViewMode.Edit ? "Edit" : "View"; - _CurrentItem.Deleted -= new ItemInfoEvent(_CurrentItem_Deleted); - _CurrentItem.Deleted += new ItemInfoEvent(_CurrentItem_Deleted); dlgFindReplace.MyEditItem = args.MyEditItem; SpellChecker.MyEditItem = args.MyEditItem; } @@ -4913,16 +4513,11 @@ namespace VEPROMS displayRO.Enabled = displayTransition.Enabled = _LastStepRTB.EditMode; else // going out of edit mode in a cell of the grid. { - if (this.ActiveControl != tc || (!_LastStepRTB.Parent.Focused && (infotabRO.IsSelected || infotabTransition.IsSelected))) return; + if (ActiveControl != tc || (!_LastStepRTB.Parent.Focused && (infotabRO.IsSelected || infotabTransition.IsSelected))) return; displayRO.Enabled = displayTransition.Enabled = _LastStepRTB.EditMode; } } - void _CurrentItem_Deleted(object sender) - { - //displayBookMarks.DeleteItemBookMarkPanel(_CurrentItem); - } - #endregion #region Annotations @@ -4967,7 +4562,6 @@ namespace VEPROMS infoPanel.Expanded = true; infoTabs.SelectedTab = infotabTransition; if (SelectedStepTabPanel == null) return; - //displayTransition.RangeColor = global::VEPROMS.Properties.Settings.Default.TransitionRangeColor; displayTransition.MyRTB = SelectedStepTabPanel.MyStepPanel.SelectedEditItem.MyStepRTB; displayTransition.CurTrans = args.MyLinkText.MyTransitionInfo; } @@ -5014,220 +4608,168 @@ namespace VEPROMS if (!tv.Focused && tc.SelectedDisplayTabItem != null && tc.SelectedDisplayTabItem.SelectedItemInfo != null) tv.AdjustTree(tc.SelectedDisplayTabItem.SelectedItemInfo); - VETreeNode vtn = tv.SelectedNode as VETreeNode; - if (vtn == null) return; - StepInfo stpinf = vtn.VEObject as StepInfo; - if (stpinf == null || !stpinf.IsRNOPart) //B2017-037 is this a RNO step type element - don't allow insert before/after - btnNew.Enabled = true; - vtn.Expand(); + if (!(tv.SelectedNode is VETreeNode vtn)) return; + if (!(vtn.VEObject is StepInfo stpinf) || !stpinf.IsRNOPart) //B2017-037 is this a RNO step type element - don't allow insert before/after + btnNew.Enabled = true; + vtn.Expand(); - // Folders can have either folders & docversions, but - // not a mix. - FolderInfo fi = vtn.VEObject as FolderInfo; - if (fi != null) - { - // Enable/disable the New button based on the user's security settings at the current folder level - // B2015-193 - btnNew.Enabled = UserInfo.CanCreateFolders(MyUserInfo, fi); + // Folders can have either folders & docversions, but + // not a mix. + if (vtn.VEObject is FolderInfo fi) + { + // Enable/disable the New button based on the user's security settings at the current folder level + // B2015-193 + btnNew.Enabled = UserInfo.CanCreateFolders(MyUserInfo, fi); - // if at top, 'VEPROMS', folder and childfolders below this only - // option is to create a new (sub)folder, i.e. no submenu items. - if (fi.ChildFolderCount > 0 && fi.MyParent == null) return; + // if at top, 'VEPROMS', folder and childfolders below this only + // option is to create a new (sub)folder, i.e. no submenu items. + if (fi.ChildFolderCount > 0 && fi.MyParent == null) return; - // submenu folders/docversion - if (fi.MyParent != null && UserInfo.CanCreateFolders(MyUserInfo, fi)) - { - ButtonItem fldbbtn = new ButtonItem("fldbtn", "Folder Before"); - ButtonItem fldabtn = new ButtonItem("fldabtn", "Folder After"); - btnNew.SubItems.Add(fldbbtn); - btnNew.SubItems.Add(fldabtn); - fldbbtn.Click += new EventHandler(fldbbtn_Click); - fldabtn.Click += new EventHandler(fldabtn_Click); - } - ButtonItem fldbtn = new ButtonItem("fldbtn", "Folder"); - btnNew.SubItems.Add(fldbtn); - fldbtn.Click += new EventHandler(fldbtn_Click); + // submenu folders/docversion + if (fi.MyParent != null && UserInfo.CanCreateFolders(MyUserInfo, fi)) + { + ButtonItem fldbbtn = new ButtonItem("fldbtn", "Folder Before"); + ButtonItem fldabtn = new ButtonItem("fldabtn", "Folder After"); + btnNew.SubItems.Add(fldbbtn); + btnNew.SubItems.Add(fldabtn); + fldbbtn.Click += new EventHandler(fldbbtn_Click); + fldabtn.Click += new EventHandler(fldabtn_Click); + } + ButtonItem fldbtn = new ButtonItem("fldbtn", "Folder"); + btnNew.SubItems.Add(fldbtn); + fldbtn.Click += new EventHandler(fldbtn_Click); - // offer adding a Working Draft only if the folder has no sub-folders and there is not already a Working Draft node - if (fi.ChildFolderCount == 0 && fi.FolderDocVersionCount == 0) - { - ButtonItem dvbtn = new ButtonItem("dvbtn", "Working Draft"); - btnNew.SubItems.Add(dvbtn); - dvbtn.Click += new EventHandler(dvbtn_Click); - } - return; - } + // offer adding a Working Draft only if the folder has no sub-folders and there is not already a Working Draft node + if (fi.ChildFolderCount == 0 && fi.FolderDocVersionCount == 0) + { + ButtonItem dvbtn = new ButtonItem("dvbtn", "Working Draft"); + btnNew.SubItems.Add(dvbtn); + dvbtn.Click += new EventHandler(dvbtn_Click); + } + return; + } - // DocVersions can only have procedures, so no sub-menu - DocVersionInfo dvi = vtn.VEObject as DocVersionInfo; - if (dvi != null) - { - if (!UserInfo.CanEdit(MyUserInfo, dvi)) - btnNew.Enabled = false; // reviewers cannot create a new procedure B2015-193 - return; - } + // DocVersions can only have procedures, so no sub-menu + if (vtn.VEObject is DocVersionInfo dvi) + { + if (!UserInfo.CanEdit(MyUserInfo, dvi)) + btnNew.Enabled = false; // reviewers cannot create a new procedure B2015-193 + return; + } - // Procedures can have a section added or a new procedure before - // or after. - ProcedureInfo pi = vtn.VEObject as ProcedureInfo; - if (pi != null) - { - // if user is a reviewer then don't allow adding new procedures - // bug B2015-193 - if (!UserInfo.CanEdit(MyUserInfo, pi.MyDocVersion)) - { - btnNew.Enabled = false; - return; - } - ButtonItem pbbtn = new ButtonItem("pfbtn", "Procedure Before"); - ButtonItem pabtn = new ButtonItem("pabtn", "Procedure After"); - ButtonItem sctbtn = new ButtonItem("sctbtn", "Section"); - btnNew.SubItems.Add(pbbtn); - btnNew.SubItems.Add(pabtn); - btnNew.SubItems.Add(sctbtn); - pbbtn.Click += new EventHandler(pbbtn_Click); - pabtn.Click += new EventHandler(pabtn_Click); - sctbtn.Click += new EventHandler(sctbtn_Click); - return; - } + // Procedures can have a section added or a new procedure before + // or after. + if (vtn.VEObject is ProcedureInfo pi) + { + // if user is a reviewer then don't allow adding new procedures + // bug B2015-193 + if (!UserInfo.CanEdit(MyUserInfo, pi.MyDocVersion)) + { + btnNew.Enabled = false; + return; + } + ButtonItem pbbtn = new ButtonItem("pfbtn", "Procedure Before"); + ButtonItem pabtn = new ButtonItem("pabtn", "Procedure After"); + ButtonItem sctbtn = new ButtonItem("sctbtn", "Section"); + btnNew.SubItems.Add(pbbtn); + btnNew.SubItems.Add(pabtn); + btnNew.SubItems.Add(sctbtn); + pbbtn.Click += new EventHandler(pbbtn_Click); + pabtn.Click += new EventHandler(pabtn_Click); + sctbtn.Click += new EventHandler(sctbtn_Click); + return; + } - // Sections can have sections before, after, new subsections & if is - // a step section, can have steps - SectionInfo si = vtn.VEObject as SectionInfo; - if (si != null) - { - // if user is a reviewer then don't allow adding new sections - // bug B2015-193 - if (!UserInfo.CanEdit(MyUserInfo, si.MyDocVersion)) - { - btnNew.Enabled = false; - return; - } - ButtonItem sbbtn = new ButtonItem("sbbtn", "Section Before"); - ButtonItem sabtn = new ButtonItem("sabtn", "Section After"); + // Sections can have sections before, after, new subsections & if is + // a step section, can have steps + if (vtn.VEObject is SectionInfo si) + { + // if user is a reviewer then don't allow adding new sections + // bug B2015-193 + if (!UserInfo.CanEdit(MyUserInfo, si.MyDocVersion)) + { + btnNew.Enabled = false; + return; + } + ButtonItem sbbtn = new ButtonItem("sbbtn", "Section Before"); + ButtonItem sabtn = new ButtonItem("sabtn", "Section After"); - btnNew.SubItems.Add(sbbtn); - btnNew.SubItems.Add(sabtn); - sbbtn.Click += new EventHandler(sbbtn_Click); - sabtn.Click += new EventHandler(sabtn_Click); + btnNew.SubItems.Add(sbbtn); + btnNew.SubItems.Add(sabtn); + sbbtn.Click += new EventHandler(sbbtn_Click); + sabtn.Click += new EventHandler(sabtn_Click); - if (si.IsStepSection) - { - // B2016-282: Don't allow insert of subsections off Word Section. - if (si.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) - { - ButtonItem subbtn = new ButtonItem("subbtn", "SubSection"); - btnNew.SubItems.Add(subbtn); - subbtn.Click += new EventHandler(subbtn_Click); - } - ButtonItem stpbtn = new ButtonItem("stpbtn", "New Step"); - btnNew.SubItems.Add(stpbtn); - stpbtn.Click += new EventHandler(stpbtn_Click); - } - return; - } + if (si.IsStepSection) + { + // B2016-282: Don't allow insert of subsections off Word Section. + if (si.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) + { + ButtonItem subbtn = new ButtonItem("subbtn", "SubSection"); + btnNew.SubItems.Add(subbtn); + subbtn.Click += new EventHandler(subbtn_Click); + } + ButtonItem stpbtn = new ButtonItem("stpbtn", "New Step"); + btnNew.SubItems.Add(stpbtn); + stpbtn.Click += new EventHandler(stpbtn_Click); + } + return; + } - // Steps can have steps before or after only. - StepInfo stpi = vtn.VEObject as StepInfo; - if (stpi != null) - { - // if user is a reviewer then don't allow adding new procedures, sections, or steps - // bug B2015-193 - if (!UserInfo.CanEdit(MyUserInfo, stpi.MyDocVersion)) - { - btnNew.Enabled = false; - return; - } - ButtonItem stpbbtn = new ButtonItem("stpbbtn", "New Step Before"); - ButtonItem stpabtn = new ButtonItem("stpabtn", "New Step After"); - btnNew.SubItems.Add(stpbbtn); - btnNew.SubItems.Add(stpabtn); - stpbbtn.Click += new EventHandler(stpbbtn_Click); - stpabtn.Click += new EventHandler(stpabtn_Click); - return; - } - btnNew.Enabled = false; // should not get this far, but just in case turn off the New button + // Steps can have steps before or after only. + if (vtn.VEObject is StepInfo stpi) + { + // if user is a reviewer then don't allow adding new procedures, sections, or steps + // bug B2015-193 + if (!UserInfo.CanEdit(MyUserInfo, stpi.MyDocVersion)) + { + btnNew.Enabled = false; + return; + } + ButtonItem stpbbtn = new ButtonItem("stpbbtn", "New Step Before"); + ButtonItem stpabtn = new ButtonItem("stpabtn", "New Step After"); + btnNew.SubItems.Add(stpbbtn); + btnNew.SubItems.Add(stpabtn); + stpbbtn.Click += new EventHandler(stpbbtn_Click); + stpabtn.Click += new EventHandler(stpabtn_Click); + return; + } + btnNew.Enabled = false; // should not get this far, but just in case turn off the New button } - void fldabtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.FolderAfter); - } + void fldabtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.FolderAfter); - void fldbbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.FolderBefore); - } + void fldbbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.FolderBefore); - void stpabtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.StepAfter); - } + void stpabtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.StepAfter); - void stpbbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.StepBefore); - } + void stpbbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.StepBefore); - void subbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.Section); - } + void subbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.Section); - void sabtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.SectionAfter); - } + void sabtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.SectionAfter); - void sbbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.SectionBefore); - } + void sbbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.SectionBefore); - void stpbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.Step); - } + void stpbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.Step); - void sctbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.Section); - } + void sctbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.Section); - void pabtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.ProcedureAfter); - } + void pabtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.ProcedureAfter); - void pbbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.ProcedureBefore); - } + void pbbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.ProcedureBefore); - void dvbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.DocVersion); - } + void dvbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.DocVersion); + + void fldbtn_Click(object sender, EventArgs e) => tv.tv_NodeNew(vlnTreeView.MenuSelections.Folder); - void fldbtn_Click(object sender, EventArgs e) - { - tv.tv_NodeNew(vlnTreeView.MenuSelections.Folder); - } - private void btnSave_Click(object sender, EventArgs e) - { - } #endregion #region PanelEvents private void infoPanel_Click(object sender, EventArgs e) { - displayTags.MyEditItem = (SelectedStepTabPanel == null) ? null : SelectedStepTabPanel.MyStepPanel.SelectedEditItem; + displayTags.MyEditItem = SelectedStepTabPanel?.MyStepPanel.SelectedEditItem; displayTags.Mydvi = SelectedDVI; } - //private void tv_SectionShouldClose(object sender, vlnTreeSectionInfoEventArgs args) - //{ - // if (!args.MySectionInfo.IsStepSection) tc.CloseWordItem(args.MySectionInfo); - //} private void infotabResults_Click(object sender, EventArgs e) { @@ -5238,7 +4780,7 @@ namespace VEPROMS { if (toolsPanel.Expanded) { - if (displaySearch1.Mydocversion == null)//!displaySearch1.OpenDocFromSearch) + if (displaySearch1.Mydocversion == null) { if (SelectedDVI != null) { @@ -5253,17 +4795,17 @@ namespace VEPROMS private void toosTabReports_Click(object sender, EventArgs e) { toolsPanel.Expanded = true; - InitiateDisplayReports(true); + InitiateDisplayReports(); } - private void InitiateDisplayReports(bool reportFocus) + private void InitiateDisplayReports() { if (toolsPanel.Expanded) { if (SelectedDVI != null) displayReports.Mydocversion = SelectedDVI; - displayReports.advTreeProcSetsFillIn(reportFocus); - displayReports.advTreeROFillIn(reportFocus); + displayReports.advTreeProcSetsFillIn(); + displayReports.advTreeROFillIn(); displayReports.SelectReferencedObjectTab(); // to enable RO selection } } @@ -5300,7 +4842,7 @@ namespace VEPROMS myfolder = myfolder.MyParent; } Clipboard.Clear(); - DataObject mydo = new DataObject(DataFormats.Text, string.Format("{0} - {1}", fPath, myitem.ShortPath)); + DataObject mydo = new DataObject(DataFormats.Text, $"{fPath} - {myitem.ShortPath}"); Clipboard.SetDataObject(mydo); } } @@ -5338,19 +4880,16 @@ namespace VEPROMS } } - private void expandPanelExpandedChanging(object sender, ExpandedChangeEventArgs e) - { - _panelExpandedChanging = true; - } + private void expandPanelExpandedChanging(object sender, ExpandedChangeEventArgs e) => _panelExpandedChanging = true; - private void toolsPanel_ExpandedChanged(object sender, ExpandedChangeEventArgs e) + private void toolsPanel_ExpandedChanged(object sender, ExpandedChangeEventArgs e) { _panelExpandedChanging = false; expandableSplitter4.Enabled = toolsPanel.Expanded; if (toolsPanel.Expanded) { InitiateSearch(true); - InitiateDisplayReports(true); + InitiateDisplayReports(); } } @@ -5384,35 +4923,27 @@ namespace VEPROMS scListdlg.Show(); } - private void cmbFont_SelectedIndexChanged(object sender, EventArgs e) + private void cmbFont_SelectedIndexChanged(object sender, EventArgs e) => StepRTB.MyFontFamily = cmbFont.SelectedValue as FontFamily; + + private void lblResolution_Click(object sender, EventArgs e) { - StepRTB.MyFontFamily = cmbFont.SelectedValue as FontFamily; - } - - - - private void lblResolution_Click(object sender, EventArgs e) - { - if (this.WindowState != FormWindowState.Normal) + if (WindowState != FormWindowState.Normal) { - this.WindowState = FormWindowState.Normal; + WindowState = FormWindowState.Normal; } - else if (this.Size.Width != 1280) + else if (Size.Width != 1280) { - this.Size = new Size(1280, 800); + Size = new Size(1280, 800); } else { - this.Size = new Size(1024, 768); + Size = new Size(1024, 768); } } - private void frmVEPROMS_Resize(object sender, EventArgs e) - { - lblResolution.Text = string.Format("Resolution {0} x {1}", Size.Width, Size.Height); - } + private void frmVEPROMS_Resize(object sender, EventArgs e) => lblResolution.Text = $"Resolution {Size.Width} x {Size.Height}"; - private void office2007StartButton1_MouseDown(object sender, MouseEventArgs e) + private void office2007StartButton1_MouseDown(object sender, MouseEventArgs e) { // Refresh the MostRecentlyUsedList _MyMRIList.Refresh(); @@ -5443,7 +4974,7 @@ namespace VEPROMS { if (mypath == null) { - string fmtPath = Properties.Settings.Default.FormatPath ?? ""; + string fmtPath = Settings.Default.FormatPath ?? ""; DirectoryInfo di = null; do @@ -5460,8 +4991,8 @@ namespace VEPROMS fmtPath = di.FullName; } while (((fmtPath ?? "") == "") || (!di.Exists || !Directory.Exists(di.FullName + @"\fmtall") || !Directory.Exists(di.FullName + @"\genmacall"))); - Properties.Settings.Default.FormatPath = fbd.SelectedPath; - Properties.Settings.Default.Save(); + Settings.Default.FormatPath = fbd.SelectedPath; + Settings.Default.Save(); mypath = di.FullName; } @@ -5473,7 +5004,7 @@ namespace VEPROMS Format.UpdateFormats(fmtPathAll, genmacPathAll); Format.FormatLoaded -= new FormatEvent(Format_FormatLoaded); - _MyLog.WarnFormat("Formats in {0} updated to {1}", Database.SelectedDatabase, fmtPathAll); + _MyLog.WarnFormat($"Formats in {Database.SelectedDatabase} updated to {fmtPathAll}"); } void Format_FormatLoaded(object sender, FormatEventArgs args) @@ -5506,14 +5037,14 @@ namespace VEPROMS { try { - frmSendErrorLog frm = new frmSendErrorLog(Properties.Settings.Default.OutlookEmail, Properties.Settings.Default["SMTPServer"].ToString(), Properties.Settings.Default["SMTPUser"].ToString(), ErrorLogFileName); + frmSendErrorLog frm = new frmSendErrorLog(Settings.Default.OutlookEmail, Settings.Default["SMTPServer"].ToString(), Settings.Default["SMTPUser"].ToString(), ErrorLogFileName); if (frm.ShowDialog(this) == DialogResult.OK) { - Properties.Settings.Default.OutlookEmail = frm.OutlookEmail; - Properties.Settings.Default.SMTPServer = frm.SMTPServer; - Properties.Settings.Default.SMTPUser = frm.SMTPUser; - Properties.Settings.Default.Save(); + Settings.Default.OutlookEmail = frm.OutlookEmail; + Settings.Default.SMTPServer = frm.SMTPServer; + Settings.Default.SMTPUser = frm.SMTPUser; + Settings.Default.Save(); MessageBox.Show("PROMS Error Log successfully sent to Volian support"); } @@ -5528,7 +5059,7 @@ namespace VEPROMS private void btnShowErrFld_Click(object sender, EventArgs e) { string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - path = path + @"\Documents\VEPROMS"; + path += @"\Documents\VEPROMS"; if (Directory.Exists(path)) { Process.Start("explorer.exe", path); @@ -5538,7 +5069,7 @@ namespace VEPROMS private void btnShowPrtFld_Click(object sender, EventArgs e) { string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); - path = path + @"\AppData\Local\Temp\VEPROMS"; + path += @"\AppData\Local\Temp\VEPROMS"; if (Directory.Exists(path)) { Process.Start("explorer.exe", path); @@ -5550,25 +5081,25 @@ namespace VEPROMS // C2019-024 Display the PROMS User Manual when user click on the option in the Help drop down menu // PROMS looks for "PROMSmanual.pdf" in the executable folder. If not found, a message box will display. - string promsUserManual = System.Windows.Forms.Application.StartupPath + @"\PROMSManual.pdf"; + string promsUserManual = Application.StartupPath + @"\PROMSManual.pdf"; try { if (File.Exists(promsUserManual)) { - System.Diagnostics.Process sdp = System.Diagnostics.Process.Start(promsUserManual); + System.Diagnostics.Process sdp = Process.Start(promsUserManual); sdp.WaitForInputIdle(); } else { MessageBox.Show("The PROMS User Manual is not available for viewing.\nDetails are in the error log.", "View User Manual"); - _MyLog.WarnFormat("PROMS User Manual not found: {0}", promsUserManual); + _MyLog.WarnFormat($"PROMS User Manual not found: {promsUserManual}"); } } catch (Exception ex) { MessageBox.Show("Could not open the PROMS User Manual.\nDetails are in the error log.", "View User Manual"); - string str = string.Format("Could not open {0}", promsUserManual); + string str = $"Could not open {promsUserManual}"; _MyLog.Error(str, ex); } } @@ -5582,8 +5113,8 @@ namespace VEPROMS { lock (this) { - if (!this.Contains(dti)) - this.Push(dti); + if (!Contains(dti)) + Push(dti); } } @@ -5591,7 +5122,7 @@ namespace VEPROMS { lock (this) { - return this.Pop(); + return Pop(); } } @@ -5601,7 +5132,7 @@ namespace VEPROMS { lock (this) { - return this.Count; + return Count; } } } @@ -5611,21 +5142,10 @@ namespace VEPROMS public class VersionWindow { - private int _VersionID; - public int VersionID - { - get { return _VersionID; } - set { _VersionID = value; } - } + public int VersionID { get; set; } + public int DBId { get; set; } - private int _DBId; - public int DBId - { - get { return _DBId; } - set { _DBId = value; } - } - - private Rectangle _MyRectangle; + private Rectangle _MyRectangle; public Rectangle MyRectangle { get { return _MyRectangle; } @@ -5635,17 +5155,13 @@ namespace VEPROMS 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]); } - public override string ToString() - { - RectangleConverter rc = new RectangleConverter(); - return string.Format("{0}~{1}", _VersionID, rc.ConvertToString(_MyRectangle)); - } - } + public override string ToString() => $"{VersionID}~{new RectangleConverter().ConvertToString(_MyRectangle)}"; + } public class VersionWindowList : List { @@ -5684,7 +5200,7 @@ namespace VEPROMS { if (vw.VersionID == versionWindow.VersionID) { - this.Remove(vw); + Remove(vw); break; } } diff --git a/PROMS/VEPROMS User Interface/frmVersionsProperties.cs b/PROMS/VEPROMS User Interface/frmVersionsProperties.cs index 3f8617e9..605ae912 100644 --- a/PROMS/VEPROMS User Interface/frmVersionsProperties.cs +++ b/PROMS/VEPROMS User Interface/frmVersionsProperties.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 System.IO; using VEPROMS.CSLA.Library; @@ -28,45 +25,36 @@ namespace VEPROMS private List _Apples; private List _DeletedApples; private List _Enhanced; - private DocVersionConfig _DocVersionConfig; - private string _OrgPDFPath; // B2024-030 used to save last PDF path + private readonly DocVersionConfig _DocVersionConfig; + private readonly string _OrgPDFPath; // B2024-030 used to save last PDF path // Default values private string _DefaultFormatName = null; - private string _DefaultROPrefix = null; - private string _DefaultImagePrefix = null; private string _DefaultWatermark = null; private string _DefaultChgBarType = null; private string _DefaultChgBarLoc = null; private string _DefaultChgBarText = null; private string _DefaultChgBarUsrMsg1 = null; private string _DefaultChgBarUsrMsg2 = null; - private bool _DefaultDisableDuplex = false; - private DisplaySearch _DisplaySearch1 = null; - - private bool _Initializing = false; + private bool _Initializing = false; private System.IO.StreamWriter swROUpdate; - private ProgressBarItem _ProgressBar = null; - private RODbInfo _CurRoDbInfo = null; + private RODbInfo _CurRoDbInfo = null; private ROFstInfo _SelectedROFst; - private List NewEnhVersions = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List NewEnhVersions = new List(); private bool doingNew = false; private bool _EnhNeedToUnlink = false; private int _InitialIndex = -2; // added as part of code change C2017-004. this also makes it consistent with section properties private int? _cmbxformatOriginal = null; - #endregion + #endregion - #region Properties - - public DisplaySearch DisplaySearch1 - { - get { return _DisplaySearch1; } - set { _DisplaySearch1 = value; } - } + #region Properties - // For the initial release, we are assuming there will be only one rofst for a docversion. Changes will be needed here if more than 1. - public ROFstInfo SelectedROFst + public DisplaySearch DisplaySearch1 { get; set; } = null; + + // For the initial release, we are assuming there will be only one rofst for a docversion. Changes will be needed here if more than 1. + public ROFstInfo SelectedROFst { get { @@ -81,17 +69,13 @@ namespace VEPROMS set { _SelectedROFst = value; } } - public ProgressBarItem ProgressBar - { - get { return _ProgressBar; } - set { _ProgressBar = value; } - } + public ProgressBarItem ProgressBar { get; set; } = null; - #endregion + #endregion - #region Constructors + #region Constructors - public frmVersionsProperties(DocVersionConfig docVersionConfig) + public frmVersionsProperties(DocVersionConfig docVersionConfig) { _DocVersionConfig = docVersionConfig; docVersionConfig.RefreshMyEnhancedDocuments(); @@ -103,7 +87,7 @@ namespace VEPROMS _Initializing = false; //build the caption - this.Text = string.Format("{0} Properties", _DocVersionConfig.Name); + Text = string.Format("{0} Properties", _DocVersionConfig.Name); } #endregion @@ -147,9 +131,11 @@ namespace VEPROMS srchtxt = myGrid.GetSearchableText(); } - List retlist = new List(); - retlist.Add(srchtxt); - retlist.Add(xml); + List retlist = new List + { + srchtxt, + xml + }; return retlist; } @@ -164,7 +150,6 @@ namespace VEPROMS docVersionConfigBindingSource.DataSource = _DocVersionConfig; - //formatInfoListBindingSource.DataSource = FormatInfoList.Get(); imageCodecInfoBindingSource.DataSource = ImageCodecInfo.GetImageDecoders(); ppCmbxFormat.DataSource = null; @@ -185,7 +170,7 @@ namespace VEPROMS // Get the saved settings for this user // Get setting telling us whether to display the default values on this property page - ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultVersionProp"] != null) ? Settings.Default.ShowDefaultVersionProp : false; + ppCbShwDefSettings.Checked = (Settings.Default["ShowDefaultVersionProp"] != null) && Settings.Default.ShowDefaultVersionProp; // Get the User's property page style "PropPageStyle" (this is a system wide user setting) // 1 - Button Dialog (default) @@ -194,7 +179,7 @@ namespace VEPROMS { tcVersions.TabsVisible = true; panVerBtns.Visible = false; - this.Width -= panVerBtns.Width; + Width -= panVerBtns.Width; } // Get the default values for the property page information @@ -298,12 +283,14 @@ namespace VEPROMS } else { - Button btnPC = new Button(); - btnPC.Text = "Add Applicability to Working Draft"; - btnPC.Width = 250; - btnPC.Location = new Point(25, 271); - btnPC.Parent = tcpGeneral; - btnPC.Click += new EventHandler(btnPC_Click); + Button btnPC = new Button + { + Text = "Add Applicability to Working Draft", + Width = 250, + Location = new Point(25, 271), + Parent = tcpGeneral + }; + btnPC.Click += new EventHandler(btnPC_Click); btnApplicability.Visible = false; tiApplicability.Visible = false; } @@ -394,12 +381,14 @@ namespace VEPROMS } if (validEmptyEnhancedExists) { - Button btnEnh = new Button(); - btnEnh.Text = "Link to Enhanced Document(s)"; - btnEnh.Width = 220; - btnEnh.Location = new Point(290, 271); - btnEnh.Parent = tcpGeneral; - btnEnh.Click += new EventHandler(btnEnh_Click); + Button btnEnh = new Button + { + Text = "Link to Enhanced Document(s)", + Width = 220, + Location = new Point(290, 271), + Parent = tcpGeneral + }; + btnEnh.Click += new EventHandler(btnEnh_Click); } } btnEnhanced.Visible = false; @@ -425,7 +414,7 @@ namespace VEPROMS DocVersionInfo dvi = DocVersionInfo.Get(_DocVersionConfig.MyEnhancedDocuments[0].VersionID); DVEnhancedDocument dvedUseData = _DocVersionConfig.MyEnhancedDocuments[0]; DocVersionConfig dvc = dvi.MyConfig as DocVersionConfig; - EnhancedMiniConfig ecfg = new EnhancedMiniConfig(0, dvi.VersionID, "?", dvi.SearchDVPath, dvedUseData.Name, dvedUseData.Type.ToString(), dvedUseData.PdfToken, dvedUseData.PdfX.ToString()); + EnhancedMiniConfig ecfg = new EnhancedMiniConfig(0, dvi.VersionID, dvi.SearchDVPath, dvedUseData.Name, dvedUseData.Type.ToString(), dvedUseData.PdfToken, dvedUseData.PdfX.ToString()); cbxEnhVersions.Items.Add(dvi.SearchDVPath); tbEnhName.Enabled = false; tbEnhType.Enabled = false; @@ -466,7 +455,7 @@ namespace VEPROMS { DocVersionInfo dvi = DocVersionInfo.Get(dved.VersionID); DocVersionConfig dvc = dvi.MyConfig as DocVersionConfig; - EnhancedMiniConfig ecfg = new EnhancedMiniConfig(0, dvi.VersionID, "?", dvi.SearchDVPath, dved.Name, dved.Type.ToString(), dved.PdfToken, dved.PdfX.ToString()); + EnhancedMiniConfig ecfg = new EnhancedMiniConfig(0, dvi.VersionID, dvi.SearchDVPath, dved.Name, dved.Type.ToString(), dved.PdfToken, dved.PdfX.ToString()); cbxEnhVersions.Items.Add(dvi.SearchDVPath); _Enhanced.Add(ecfg); } @@ -549,47 +538,6 @@ namespace VEPROMS } } - private string AddSlaveNode(MiniConfig mc) - { - System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); - xd.LoadXml(_DocVersionConfig.ToString()); - System.Xml.XmlNodeList nl = xd.SelectNodes("//Slave"); - int max = 0; - - foreach (System.Xml.XmlNode n in nl) - { - max = int.Parse(n.Attributes.GetNamedItem("index").InnerText); - } - - max++; - - System.Xml.XmlNode nn = xd.CreateElement("Slave"); - AddSlaveAttribute(nn, "index", max.ToString()); - AddSlaveAttribute(nn, "ID", mc.ID); - AddSlaveAttribute(nn, "Name", mc.Name); - AddSlaveAttribute(nn, "Number", mc.Number); - AddSlaveAttribute(nn, "Text", mc.Text); - AddSlaveAttribute(nn, "ProcedureNumber", mc.ProcedureNumber); - AddSlaveAttribute(nn, "SetID", mc.SetID); - AddSlaveAttribute(nn, "SetName", mc.SetName); - AddSlaveAttribute(nn, "OtherID", mc.OtherID); - AddSlaveAttribute(nn, "OtherName", mc.OtherName); - AddSlaveAttribute(nn, "OtherNumber", mc.OtherNumber); - AddSlaveAttribute(nn, "OtherText", mc.OtherText); - - System.Xml.XmlNode sn = xd.SelectSingleNode("//Slaves"); - sn.AppendChild(nn); - - return xd.OuterXml; - } - - private void AddSlaveAttribute(System.Xml.XmlNode nn, string name, string value) - { - System.Xml.XmlAttribute xa = nn.OwnerDocument.CreateAttribute(name); - xa.InnerText = value; - nn.Attributes.SetNamedItem(xa); - } - private void btnVersionsPropOK_Click(object sender, EventArgs e) { //B2024-030 Check the PDF Location path and prompt to create the folders if needed @@ -683,8 +631,8 @@ namespace VEPROMS { dved.PdfX = Convert.ToInt32(emc.PdfXOffset); } - catch (Exception ex) - { + catch (Exception) + { dved.PdfX = 10; } } @@ -698,8 +646,8 @@ namespace VEPROMS { ipdfx = Convert.ToInt32(emc.PdfXOffset); } - catch (Exception ex) - { + catch (Exception) + { ipdfx = (emc.PdfToken == null || emc.PdfToken == "") ? 0 : 10; } @@ -709,8 +657,8 @@ namespace VEPROMS { itype = Convert.ToInt32(emc.Type); } - catch (Exception ex) - { + catch (Exception) + { itype = 1; } @@ -773,20 +721,20 @@ namespace VEPROMS if (_EnhNeedToUnlink) { - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; _DocVersionConfig.MyDocVersion.MyDocVersionInfo.DoUnlinkEnhancedDocVersion(); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } // B2019-132 update the association count for this working draft _DocVersionConfig.MyDocVersion.MyDocVersionInfo.RefreshDocVersionAssociations(); - this.Close(); + Close(); } private void btnFldrPropCancel_Click(object sender, EventArgs e) { docVersionConfigBindingSource.CancelEdit(); - this.Close(); + Close(); } /// @@ -832,13 +780,15 @@ namespace VEPROMS // Get the ro path - there is no 'default' if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount < 0 && _DocVersionConfig.MyDocVersion.DocVersionAssociations.Count == 0) - ;// The line above refreshes the data +#pragma warning disable CS0642 // Possible mistaken empty statement + ;// The line above refreshes the data +#pragma warning restore CS0642 // Possible mistaken empty statement - if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount > 0) + if (_DocVersionConfig.MyDocVersion.DocVersionAssociationCount > 0) { RODbInfo rdi = RODbInfo.GetJustRODB(SelectedROFst.RODbID); - tbRoDb.Text = string.Format("{0} ({1})", rdi.ROName, rdi.FolderPath); + tbRoDb.Text = $"{rdi.ROName} ({rdi.FolderPath})"; ppBtnRoToSql.Visible = ppBtnRoToSql.Enabled = CanMigrateRoAccessToSql(rdi); // C2017-003: make button visible if ro migration is doable _CurRoDbInfo = rdi; } @@ -851,7 +801,7 @@ namespace VEPROMS foreach (RODbInfo rdi in RODbInfoList.Get()) { - int i = cmbRoDb.Items.Add(string.Format("{0} ({1})", rdi.ROName, rdi.FolderPath)); + int i = cmbRoDb.Items.Add($"{rdi.ROName} ({rdi.FolderPath})"); if (rdi.RODbID == myrodbid) { @@ -958,10 +908,12 @@ namespace VEPROMS if (tmp == null) { MessageBox.Show("Invalid ro fst directory, use the Property dialog to fix directory path to ro.fst."); - frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, rdi); - dlgROProperties.ProgressBar = ProgressBar; + frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, rdi) + { + ProgressBar = ProgressBar + }; - if (dlgROProperties.ShowDialog() == DialogResult.OK) + if (dlgROProperties.ShowDialog() == DialogResult.OK) { tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); // only allow update if association, and the RO update was not done and/or not completed @@ -975,7 +927,7 @@ namespace VEPROMS cmbRoDb.Visible = ppBtnRoDbBrowse.Visible = false; tbRoDb.Visible = btnRoDbProperties.Visible = true; - tbRoDb.Text = string.Format("{0} ({1})", tmp.MyRODb.ROName, tmp.MyRODb.FolderPath); + tbRoDb.Text = $"{tmp.MyRODb.ROName} ({tmp.MyRODb.FolderPath})"; // C2017-003: See if the selected ro database has been converted to sql and if not, make visible a button to convert the data. RODbInfo rodbi = RODbInfo.GetJustRODB(tmp.MyRODb.RODbID); @@ -1007,12 +959,14 @@ namespace VEPROMS private void ppBtnRoDbBrowse_Click(object sender, EventArgs e) { - frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst == null ? null : SelectedROFst.MyRODb); - dlgROProperties.ParentLocation = Location; + frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst?.MyRODb) + { + ParentLocation = Location + }; - // if a user has entered a valid rodb, then this docversion will be conntected to it - change - // to a non-editable text box and the button becomes a properties button rather than browse. - if (dlgROProperties.ShowDialog() == DialogResult.OK) + // if a user has entered a valid rodb, then this docversion will be conntected to it - change + // to a non-editable text box and the button becomes a properties button rather than browse. + if (dlgROProperties.ShowDialog() == DialogResult.OK) { cmbRoDb.Items.Clear(); _DocVersionConfig.MyDocVersion.Reset_DocVersionAssociations(); @@ -1075,12 +1029,9 @@ namespace VEPROMS } - private void frmVersionsProperties_Shown(object sender, EventArgs e) - { - ppRTxtName.Focus(); - } + private void frmVersionsProperties_Shown(object sender, EventArgs e) => ppRTxtName.Focus(); - private void ppRTxtName_Leave(object sender, EventArgs e) + private void ppRTxtName_Leave(object sender, EventArgs e) { if (string.IsNullOrEmpty(ppRTxtName.Text)) { @@ -1089,12 +1040,9 @@ namespace VEPROMS } } - private void btnApplicability_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiApplicability, btnApplicability); - } + private void btnApplicability_Click(object sender, EventArgs e) => ProcessButtonClick(tiApplicability, btnApplicability); - private void lbApplicabilities_SelectedIndexChanged(object sender, EventArgs e) + private void lbApplicabilities_SelectedIndexChanged(object sender, EventArgs e) { if (lbApplicabilities.SelectedIndex > -1) { @@ -1106,11 +1054,12 @@ namespace VEPROMS private void btnNewApple_Click(object sender, EventArgs e) { - MiniConfig cfg = new MiniConfig(); + MiniConfig cfg = new MiniConfig + { + Name = "New Applicability" + }; - cfg.Name = "New Applicability"; - - if (_Apples == null) + if (_Apples == null) { _Apples = new List(); } @@ -1147,7 +1096,7 @@ namespace VEPROMS if (_showApplicSearchResults) { _showApplicSearchResults = false; - _DisplaySearch1.SearchResults = null; + DisplaySearch1.SearchResults = null; } Cursor.Current = Cursors.WaitCursor; @@ -1159,9 +1108,9 @@ namespace VEPROMS if (MessageBox.Show(string.Format("Cannot remove an Applicability that is being use in {0} places.\n\nDo you want to view locations via Search Results?\n\nThe Search panel will open when you exit the property page.", placesUsed.Count), "Applicability In Use", MessageBoxButtons.YesNo) == DialogResult.Yes) { _showApplicSearchResults = true; - _DisplaySearch1.SearchResults = placesUsed; - _DisplaySearch1.ReportTitle = string.Format("{0} Applicability", cfg.Name); - _DisplaySearch1.TypesSelected = string.Format("These Locations Specify The \"{0}\" Applicability", cfg.Name); + DisplaySearch1.SearchResults = placesUsed; + DisplaySearch1.ReportTitle = string.Format("{0} Applicability", cfg.Name); + DisplaySearch1.TypesSelected = string.Format("These Locations Specify The \"{0}\" Applicability", cfg.Name); } return true; @@ -1187,7 +1136,7 @@ namespace VEPROMS bsApples.DataSource = null; bsApples.DataSource = _Apples; // C2018-010: When removing an applicability, info on right side still contains old content. Do refreshes and reset datasource to fix this. - this.lbApplicabilities.Refresh(); + lbApplicabilities.Refresh(); if (_Apples != null && _Apples.Count > 0) { @@ -1204,12 +1153,9 @@ namespace VEPROMS dlgPL.ShowDialog(); } - private void btnEnhanced_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiEnhanced, btnEnhanced); - } + private void btnEnhanced_Click(object sender, EventArgs e) => ProcessButtonClick(tiEnhanced, btnEnhanced); - private void lbEnhanced_SelectedIndexChanged(object sender, EventArgs e) + private void lbEnhanced_SelectedIndexChanged(object sender, EventArgs e) { if (!_Initializing && lbEnhanced.SelectedIndex > -1 && !doingNew) { @@ -1225,12 +1171,14 @@ namespace VEPROMS _Initializing = true; doingNew = true; - // the 'New' button is only enabled for Source documents. - EnhancedMiniConfig cfg = new EnhancedMiniConfig(); - cfg.Name = "New Enhanced"; + // the 'New' button is only enabled for Source documents. + EnhancedMiniConfig cfg = new EnhancedMiniConfig + { + Name = "New Enhanced" + }; - // need to have a unique number for this enhanced link, find largest and then increment by 1. - int maxtype = -1; + // need to have a unique number for this enhanced link, find largest and then increment by 1. + int maxtype = -1; if (_DocVersionConfig.MyEnhancedDocuments != null && _DocVersionConfig.MyEnhancedDocuments.Count > 0) { @@ -1451,40 +1399,36 @@ namespace VEPROMS } } - #region (General Tab) + #region (General Tab) - /// - /// This is the General button used on the button interface design - /// - /// object - /// EventArgs - private void btnGeneral_Click(object sender, EventArgs e) + /// + /// This is the General button used on the button interface design + /// + /// object + /// EventArgs + private void btnGeneral_Click(object sender, EventArgs e) => ProcessButtonClick(tiGeneral, btnGeneral); + + #endregion + + #region (Referenced Objects) + + /// + /// This is the Referenced Objects button used on the button interface design + /// + /// object + /// EventArgs + private void btnRefObjs_Click(object sender, EventArgs e) => ProcessButtonClick(tiRefObjs, btnRefObjs); + + private void btnRoDbProperties_Click(object sender, EventArgs e) { - ProcessButtonClick(tiGeneral, btnGeneral); - } + frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst?.MyRODb) + { + ParentLocation = Location + }; - #endregion - - #region (Referenced Objects) - - /// - /// This is the Referenced Objects button used on the button interface design - /// - /// object - /// EventArgs - private void btnRefObjs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiRefObjs, btnRefObjs); - } - - private void btnRoDbProperties_Click(object sender, EventArgs e) - { - frmRODbProperties dlgROProperties = new frmRODbProperties(_DocVersionConfig.MyDocVersion, SelectedROFst == null ? null : SelectedROFst.MyRODb); - dlgROProperties.ParentLocation = Location; - - if (dlgROProperties.ShowDialog() == DialogResult.OK) + if (dlgROProperties.ShowDialog() == DialogResult.OK) { - tbRoDb.Text = string.Format("{0} ({1})", SelectedROFst.MyRODb.ROName, SelectedROFst.MyRODb.FolderPath); + tbRoDb.Text = $"{SelectedROFst.MyRODb.ROName} ({SelectedROFst.MyRODb.FolderPath})"; // only allow update if association, and the RO update was not done and/or not completed ppBtnUpRoVals.Enabled = !_DocVersionConfig.MyDocVersion.ROfstLastCompleted || _DocVersionConfig.MyDocVersion.NewerRoFst; } @@ -1521,7 +1465,7 @@ namespace VEPROMS if (!File.Exists(rofstPath)) { FinalProgressBarMessage = "No existing RO.FST"; - MessageBox.Show("No existing ro.fst in path " + rdi.FolderPath + ". Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox + MessageBox.Show($"No existing ro.fst in path {rdi.FolderPath}. Check for invalid path", "No existing RO.FST"); //B2017-125 added title to messagebox break; } @@ -1581,29 +1525,26 @@ namespace VEPROMS private void ContentInfo_StaticContentInfoChange(object sender, StaticContentInfoEventArgs args) { if (args.Type == "RO") - swROUpdate.Write(string.Format("Fixed Referenced Object for {1}({4}){0}Old Text: {2}{0}New Text: {3}{0}{0}", Environment.NewLine, (sender as ItemInfo).ShortPath, args.OldValue, args.NewValue, (sender as ItemInfo).ItemID)); + swROUpdate.Write($"Fixed Referenced Object for {(sender as ItemInfo).ShortPath}({(sender as ItemInfo).ItemID}){Environment.NewLine}Old Text: {args.OldValue}{Environment.NewLine}New Text: {args.NewValue}{Environment.NewLine}{Environment.NewLine}"); } - #endregion + #endregion - #region (Output Settings) + #region (Output Settings) - /// - /// This is the Output Settings button used on the button interface design - /// - /// object - /// EventArgs - private void btnOutputSettings_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiOutputSettings, btnOutputSettings); - } + /// + /// This is the Output Settings button used on the button interface design + /// + /// object + /// EventArgs + private void btnOutputSettings_Click(object sender, EventArgs e) => ProcessButtonClick(tiOutputSettings, btnOutputSettings); - /// - /// Selection in Watermark combo box changed. - /// - /// object - /// EventArgs - private void ppCmbxWatermark_SelectedValueChanged(object sender, EventArgs e) + /// + /// Selection in Watermark combo box changed. + /// + /// object + /// EventArgs + private void ppCmbxWatermark_SelectedValueChanged(object sender, EventArgs e) { if (!_Initializing) { @@ -1889,26 +1830,6 @@ namespace VEPROMS deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; } - /// - /// Process a change in the combo box selection - /// - /// Combo Box Name - /// string containing default text - /// button to reset to default value - /// label containing the default - private void ProcessCmbxSelectedValueChange(ComboBoxEx cmbx, string defstr, ButtonX button, Label deflabel) - { - if (cmbx.SelectedIndex > -1 && !string.IsNullOrEmpty(defstr) && defstr.Equals(cmbx.SelectedValue)) - { - button.Visible = true; - button.Focus(); - button.PerformClick(); - } - - button.Visible = cmbx.SelectedValue != null; - deflabel.Visible = ppCbShwDefSettings.Checked && button.Visible; - } - /// /// Set the watermark and default label /// @@ -1925,34 +1846,28 @@ namespace VEPROMS } } - #endregion + #endregion - #region (MergedOutputSettings) + #region (MergedOutputSettings) - private void btnMergedOutputSettngs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiMergedOutputSettings, btnMergedOutputSettngs); - } + private void btnMergedOutputSettngs_Click(object sender, EventArgs e) => ProcessButtonClick(tiMergedOutputSettings, btnMergedOutputSettngs); - #endregion + #endregion - #region Library Documents + #region Library Documents - /// - /// This is the Library Documents button used on the button interface design - /// - /// object - /// EventArgs - private void btnLibDocs_Click(object sender, EventArgs e) - { - ProcessButtonClick(tiLibDocs, btnLibDocs); - } + /// + /// This is the Library Documents button used on the button interface design + /// + /// object + /// EventArgs + private void btnLibDocs_Click(object sender, EventArgs e) => ProcessButtonClick(tiLibDocs, btnLibDocs); - #endregion + #endregion - #endregion + #endregion - private void tbRoDb_TextChanged(object sender, EventArgs e) + private void tbRoDb_TextChanged(object sender, EventArgs e) { } @@ -1972,10 +1887,7 @@ namespace VEPROMS #region Fields private static int lastindex = 0; - - private bool _isDeleted; - private bool _isDirty; - private int _index; + private int _index; private int _versionID; private string _versionPathName; private string _name; @@ -1983,25 +1895,17 @@ namespace VEPROMS private string _pdfToken; private string _pdfXOffset; - #endregion + #endregion - #region Properties + #region Properties - [XmlIgnore] - public bool IsDeleted - { - get { return _isDeleted; } - set { _isDeleted = value; } - } + [XmlIgnore] + public bool IsDeleted { get; set; } - [XmlIgnore] - public bool IsDirty - { - get { return _isDirty; } - set { _isDirty = value; } - } + [XmlIgnore] + public bool IsDirty { get; set; } - [XmlAttribute("index")] + [XmlAttribute("index")] public int Index { get { return _index; } @@ -2063,10 +1967,10 @@ namespace VEPROMS _type = string.Empty; _pdfToken = string.Empty; _pdfXOffset = string.Empty; - _isDirty = false; + IsDirty = false; } - public EnhancedMiniConfig(int index, int versionid, string id, string versionPathName, string name, string type, string pdftoken, string pdfxoffset) + public EnhancedMiniConfig(int index, int versionid, string versionPathName, string name, string type, string pdftoken, string pdfxoffset) { _index = index; _versionID = versionid; @@ -2075,20 +1979,17 @@ namespace VEPROMS _type = type; _pdfToken = pdftoken; _pdfXOffset = pdfxoffset; - _isDirty = false; + IsDirty = false; } - #endregion + #endregion - #region Public Methods + #region Public Methods - public override string ToString() - { - return Name; - } + public override string ToString() => Name; - #endregion - } + #endregion + } #endregion @@ -2101,10 +2002,7 @@ namespace VEPROMS #region Fields private static int lastindex = 0; - - private bool _isDeleted; - private bool _isDirty; - private int _index; + private int _index; private string _iD; private string _name; private string _number; @@ -2117,25 +2015,17 @@ namespace VEPROMS private string _otherNumber; private string _otherText; - #endregion + #endregion - #region Properties + #region Properties - [XmlIgnore] - public bool IsDeleted - { - get { return _isDeleted; } - set { _isDeleted = value; } - } + [XmlIgnore] + public bool IsDeleted { get; set; } - [XmlIgnore] - public bool IsDirty - { - get { return _isDirty; } - set { _isDirty = value; } - } + [XmlIgnore] + public bool IsDirty { get; set; } - [XmlAttribute("index")] + [XmlAttribute("index")] public int Index { get { return _index; } @@ -2237,7 +2127,7 @@ namespace VEPROMS _otherName = string.Empty; _otherNumber = string.Empty; _otherText = string.Empty; - _isDirty = false; + IsDirty = false; } public MiniConfig(int index, string id, string name, string number, string text, string procedurenumber, string setid, string setname, string otherid, string othername, string othernumber, string othertext) @@ -2254,25 +2144,19 @@ namespace VEPROMS _otherName = othername; _otherNumber = othernumber; _otherText = othertext; - _isDirty = false; + IsDirty = false; } - #endregion + #endregion - #region Public Methods + #region Public Methods - public override string ToString() - { - return Name; - } + public override string ToString() => Name; - public string MyXml - { - get { return GenericSerializer.StringSerialize(this); } - } + public string MyXml => GenericSerializer.StringSerialize(this); - #endregion - } + #endregion + } #endregion diff --git a/PROMS/VEPROMS.CSLA.Library/Config/AnnotationConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/AnnotationConfig.cs index feb430cd..834a7233 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/AnnotationConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/AnnotationConfig.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace VEPROMS.CSLA.Library @@ -11,35 +9,23 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class AnnotationConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + private readonly XMLProperties _Xp; + public AnnotationConfig(string xml) { if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - public AnnotationConfig() - { - _Xp = new XMLProperties(); - } - public override string ToString() + public AnnotationConfig() => _Xp = new XMLProperties(); + public override string ToString() { string s = _Xp.ToString(); if (s == "" || s == "") return string.Empty; return s; } - public string GetValue(string group, string item) - { - return _Xp[group, item]; - } - public void SetValue(string group, string item, string newvalue) - { - _Xp[group, item] = newvalue; - } + public string GetValue(string group, string item) => _Xp[group, item]; + public void SetValue(string group, string item, string newvalue) => _Xp[group, item] = newvalue; - } + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/AnnotationTypeConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/AnnotationTypeConfig.cs index 83511c5a..8ac17f65 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/AnnotationTypeConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/AnnotationTypeConfig.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace VEPROMS.CSLA.Library @@ -9,12 +7,9 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class AnnotationTypeConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } - public AnnotationTypeConfig(string xml) + private readonly XMLProperties _Xp; + + public AnnotationTypeConfig(string xml) { if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); @@ -48,16 +43,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["PrintableText", "XLocation"]; if (s == string.Empty) return 0; - int tst = 0; + int tst; try { tst = int.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0; } - return int.Parse(s); + return tst; } set { diff --git a/PROMS/VEPROMS.CSLA.Library/Config/AssocConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/AssocConfig.cs index 97f03639..520ce3bf 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/AssocConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/AssocConfig.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace VEPROMS.CSLA.Library @@ -9,21 +7,14 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class AssociationConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _Association == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _Association == null; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors - private Association _Association; + private readonly Association _Association; public AssociationConfig(Association association) { _Association = association; @@ -31,7 +22,7 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - private AssociationInfo _AssociationInfo; + private readonly AssociationInfo _AssociationInfo; public AssociationConfig(AssociationInfo association) { _AssociationInfo = association; @@ -39,24 +30,17 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - public AssociationConfig(string xml) - { - _Xp = new XMLProperties(xml); - } - public AssociationConfig() + public AssociationConfig(string xml) => _Xp = new XMLProperties(xml); + public AssociationConfig() { string xml = ""; _Xp = new XMLProperties(xml); } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - public Association MyAssociation - { get { return _Association; } } - #region RODefaults // From proc.ini - [Category("Referenced Objects")] + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + public Association MyAssociation => _Association; + #region RODefaults // From proc.ini + [Category("Referenced Objects")] [DisplayName("Default RO Prefix")] [RefreshProperties(RefreshProperties.All)] [Description("Setpoint Prefix")] @@ -146,9 +130,8 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - } + return s == "" || s == "" ? string.Empty : s; + } + #endregion + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ColorConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/ColorConfig.cs index 347e5ccc..a40dbdb6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ColorConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ColorConfig.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Text.RegularExpressions; using System.Drawing; @@ -8,9 +7,9 @@ namespace VEPROMS.CSLA.Library { public static class ColorConfig { - private static Regex byARGB = new Regex(@"Color \[A=([0-9]*), R=([0-9]*), G=([0-9]*), B=([0-9]*)\]"); - private static Regex byName = new Regex(@"Color \[(.*)\]"); - private static Regex byRGB = new Regex(@"[0-9]*,[0-9]*,[0-9]*"); + private static readonly Regex byARGB = new Regex(@"Color \[A=([0-9]*), R=([0-9]*), G=([0-9]*), B=([0-9]*)\]"); + private static readonly Regex byName = new Regex(@"Color \[(.*)\]"); + private static readonly Regex byRGB = new Regex(@"[0-9]*,[0-9]*,[0-9]*"); public static Color ColorFromString(string sColor) { if (sColor == string.Empty) return Color.Empty; @@ -59,12 +58,7 @@ namespace VEPROMS.CSLA.Library return ConvertRGBToName[tmp.Name]; return tmp; } - public static Color FindKnownColor(Color tmp) - { - if (ConvertRGBToName.ContainsKey(tmp.Name)) - return ConvertRGBToName[tmp.Name]; - return tmp; - } + public static Color FindKnownColor(Color tmp) => ConvertRGBToName.ContainsKey(tmp.Name) ? ConvertRGBToName[tmp.Name] : tmp; - } + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ConfigEnum.cs b/PROMS/VEPROMS.CSLA.Library/Config/ConfigEnum.cs index 15dcad8e..9750c022 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ConfigEnum.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ConfigEnum.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; using DescriptiveEnum; namespace VEPROMS.CSLA.Library { - //class ConfigEnum - //{ //C2022-004 Added option for Unit Specific Watermark [TypeConverter(typeof(EnumDescConverter))] public enum PrintWatermark : int diff --git a/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs index 876f711c..aaa6089d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/DocVersionConfig.cs @@ -1,20 +1,14 @@ using System; using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using System.Drawing; -using DescriptiveEnum; using System.Xml; namespace VEPROMS.CSLA.Library { public partial class DVEnhancedDocuments : List { - public void Add(string name, int type, int versionID, int pdfX, string pdfToken) - { - Add(new DVEnhancedDocument(name, type, versionID,pdfX,pdfToken)); - } - public static DVEnhancedDocuments Load(XMLProperties _Xp) + public void Add(string name, int type, int versionID, int pdfX, string pdfToken) => Add(new DVEnhancedDocument(name, type, versionID, pdfX, pdfToken)); + public static DVEnhancedDocuments Load(XMLProperties _Xp) { DVEnhancedDocuments eds = new DVEnhancedDocuments(); // B2020-060: don't return null, caused null reference later foreach (XmlNode xn in _Xp.XmlContents.SelectNodes("//Enhanced")) @@ -37,7 +31,7 @@ namespace VEPROMS.CSLA.Library { // B2018-025: If there is config data in the source pointing to a non-existent enhanced, remove // this from the internal data structure so no errors will occur: - XmlNode xnx = _Xp.XmlContents.SelectSingleNode(string.Format("//Enhanced[@VersionID='{0}']", dvid)); + XmlNode xnx = _Xp.XmlContents.SelectSingleNode($"//Enhanced[@VersionID='{dvid}']"); xnx.ParentNode.RemoveChild(xnx); } } @@ -71,37 +65,12 @@ namespace VEPROMS.CSLA.Library public partial class DVEnhancedDocument { - private string _Name; - public string Name - { - get { return _Name; } - set { _Name = value; } - } - private int _Type; - public int Type - { - get { return _Type; } - set { _Type = value; } - } - private int _VersionID; - public int VersionID - { - get { return _VersionID; } - set { _VersionID = value; } - } - private int _PdfX; - public int PdfX - { - get { return _PdfX; } - set { _PdfX = value; } - } - private string _PdfToken; - public string PdfToken - { - get { return _PdfToken; } - set { _PdfToken = value; } - } - public DVEnhancedDocument() { ;} + public string Name { get; set; } + public int Type { get; set; } + public int VersionID { get; set; } + public int PdfX { get; set; } + public string PdfToken { get; set; } + public DVEnhancedDocument() { ;} public DVEnhancedDocument(string name,int type, int versionID, int pdfX, string pdfToken) { Name = name; @@ -110,23 +79,17 @@ namespace VEPROMS.CSLA.Library PdfX = pdfX; PdfToken = pdfToken; } - public override string ToString() - { - return string.Format("{0}.ItemID={1}", Name,VersionID); - } - } + public override string ToString() => $"{Name}.ItemID={VersionID}"; + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class DocVersionConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - // B2018-025: Allow refresh of enhanced document data structure, RefreshMyEnhancedDocuments, and remove link data, RemoveEnhancedLink. - public void RefreshMyEnhancedDocuments() - { - _MyEnhancedDocuments = null; - } + // B2018-025: Allow refresh of enhanced document data structure, RefreshMyEnhancedDocuments, and remove link data, RemoveEnhancedLink. + public void RefreshMyEnhancedDocuments() => _MyEnhancedDocuments = null; - public void RemoveEnhancedLink(int dvid) + public void RemoveEnhancedLink(int dvid) { // from this config, remove the link to the input dvid (DocVersionId: XmlNode xnx = _Xp.XmlContents.SelectSingleNode(string.Format("//Enhanced[@VersionID='{0}']", dvid)); @@ -198,19 +161,12 @@ namespace VEPROMS.CSLA.Library } } - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _DocVersion == null; } - } - #endregion + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _DocVersion == null; + #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors @@ -221,15 +177,8 @@ namespace VEPROMS.CSLA.Library get { return _Xp.ParentLookup; } set { _Xp.ParentLookup = value; } } - //private bool _AncestorLookup; - ////PROPGRID: Hide AncestorLookup - //[Browsable(false)] - //public bool AncestorLookup - //{ - // get { return _AncestorLookup; } - // set { _AncestorLookup = value; } - //} - private DocVersion _DocVersion; + + private readonly DocVersion _DocVersion; public DocVersionConfig(DocVersion docVersion) { _DocVersion = docVersion; @@ -251,20 +200,7 @@ namespace VEPROMS.CSLA.Library } return string.Empty; } - - //private string Xp_LookInAncestorFolderInfo(object sender, XMLPropertiesArgs args) - //{ - // if (args.AncestorLookup || ParentLookup) - // { - // for (FolderInfo folder = _DocVersionInfo.MyFolder; folder != null; folder = folder.MyParent) - // { - // string retval = folder.FolderConfig.GetValue(args.Group, args.Item); - // if (retval != string.Empty) return retval; - // } - // } - // return string.Empty; - //} - private DocVersionInfo _DocVersionInfo; + private readonly DocVersionInfo _DocVersionInfo; public DocVersionConfig(DocVersionInfo docVersionInfo) { _DocVersionInfo = docVersionInfo; @@ -283,18 +219,12 @@ namespace VEPROMS.CSLA.Library string xml = ""; _Xp = new XMLProperties(xml); } - public string GetValue(string group, string item) - { - return _Xp[group, item]; - } - public void SetValue(string group, string item, string newvalue) - { - _Xp[group, item] = newvalue; - } - #endregion + public string GetValue(string group, string item) => _Xp[group, item]; + public void SetValue(string group, string item, string newvalue) => _Xp[group, item] = newvalue; + #endregion - #region Local Properties - [Category("General")] + #region Local Properties + [Category("General")] [DisplayName("Name")] [Description("Name")] public string Name @@ -376,15 +306,14 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion + return s == "" || s == "" ? string.Empty : s; + } + #endregion - // + // - #region RODefaults // From proc.ini - [Category("Referenced Objects")] + #region RODefaults // From proc.ini + [Category("Referenced Objects")] [DisplayName("Default RO Prefix")] [RefreshProperties(RefreshProperties.All)] [Description("Setpoint Prefix")] @@ -500,13 +429,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_Printer"); } } - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintWatermark : int - //{ - // None = 0, Reference, Draft, Master, Sample, - // [Description("Information Only")] - // InformationOnly - //} [Category("Print Settings")] [DisplayName("Watermark")] @@ -584,23 +506,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_DuplexBlankPageText"); } } - //// Change Bar Use from 16-bit code: - //// No Default - //// Without Change Bars - //// With Default Change Bars - //// With User Specified Change Bars - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBar : int - //{ - // [Description("No Default, Select Before Printing")] - // SelectBeforePrinting = 0, - // [Description("Without Change Bars")] - // Without, - // [Description("With Default Change Bars")] - // WithDefault, - // [Description("Use Custom Change Bars")] - // WithUserSpecified - //} [Category("Format Settings")] [DisplayName("Change Bars")] @@ -642,23 +547,7 @@ namespace VEPROMS.CSLA.Library } } } - //// User Specified Change Bar Location from16-bit code: - //// With Text - //// Outside Box - //// AER on LEFT, RNO on Right - //// To the Left of Text - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBarLoc : int - //{ - // [Description("With Text")] - // WithText = 0, - // [Description("Outside Box")] - // OutsideBox, - // [Description("AER on Left RNO on Right")] - // AERleftRNOright, - // [Description("To the Left of the Text")] - // LeftOfText - //} + [Category("Format Settings")] [DisplayName("Change Bar Position")] [RefreshProperties(RefreshProperties.All)] @@ -700,26 +589,6 @@ namespace VEPROMS.CSLA.Library } } - //// Change Bar Text from16-bit code: - //// Date and Change ID - //// Revision Number - //// Change ID - //// No Change Bar Message - //// User Defined Message - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBarText : int - //{ - // [Description("Date and Change ID")] - // DateChgID = 0, - // [Description("Revision Number")] - // RevNum, - // [Description("Change ID")] - // ChgID, - // [Description("No Change Bar Text")] - // None, - // [Description("Custom Change Bar Text")] - // UserDef - //} [Category("Format Settings")] [DisplayName("Change Bar Text Type")] [Description("Change Bar Text")] @@ -1053,8 +922,6 @@ namespace VEPROMS.CSLA.Library { if (_SaveChangesToDocVersionConfig) { - string parval = _Xp.ParentValue("PrintSettings", "AlwaysOverwritePDF"); - _Xp["PrintSettings", "AlwaysOverwritePDF"] = value.ToString(); OnPropertyChanged("Print_AlwaysOverwritePDF"); @@ -1081,8 +948,6 @@ namespace VEPROMS.CSLA.Library { if (_SaveChangesToDocVersionConfig) { - string parval = _Xp.ParentValue("PrintSettings", "AlwaysViewPDFAfterCreate"); - _Xp["PrintSettings", "AlwaysViewPDFAfterCreate"] = value.ToString(); OnPropertyChanged("Print_AlwaysViewPDFAfterCreate"); @@ -1109,7 +974,7 @@ namespace VEPROMS.CSLA.Library { if (_SaveChangesToDocVersionConfig) { - string parval = _Xp.ParentValue("PrintSettings", "AddBlankPagesWhenUsingDuplexFoldouts"); + _ = _Xp.ParentValue("PrintSettings", "AddBlankPagesWhenUsingDuplexFoldouts"); _Xp["PrintSettings", "AddBlankPagesWhenUsingDuplexFoldouts"] = value.ToString(); @@ -1135,7 +1000,7 @@ namespace VEPROMS.CSLA.Library { if (_SaveChangesToDocVersionConfig) { - string parval = _Xp.ParentValue("PrintSettings", "UnitNumberForPageList"); + _ = _Xp.ParentValue("PrintSettings", "UnitNumberForPageList"); _Xp["PrintSettings", "UnitNumberForPageList"] = value; @@ -1256,16 +1121,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["PrintSettings", "MergedPdfsPageNumLocX"]; if (s == string.Empty) return 0.5f; - float test = 0; - try + float test; + try { test = float.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0.5f; } - return float.Parse(s); + return test; } set { @@ -1286,16 +1151,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["PrintSettings", "MergedPdfsPageNumLocY"]; if (s == string.Empty) return 0.5f; - float test = 0; - try + float test; + try { test = float.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0.5f; } - return float.Parse(s); + return test; } set { @@ -1342,16 +1207,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["PrintSettings", "MergedPdfsLandPageNumLocX"]; if (s == string.Empty) return Print_MergedPdfsPageNumLocX; - float test = 0; - try + float test; + try { test = float.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0.5f; } - return float.Parse(s); + return test; } set { @@ -1372,16 +1237,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["PrintSettings", "MergedPdfsLandPageNumLocY"]; if (s == string.Empty) return Print_MergedPdfsPageNumLocY; - float test = 0; - try + float test; + try { test = float.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0.5f; } - return float.Parse(s); + return test; } set { @@ -1435,7 +1300,7 @@ namespace VEPROMS.CSLA.Library if (_SaveChangesToDocVersionConfig) { string s = _Xp["PrintSettings", "MergedPdfsViewAfter"]; // get the original value to see if a change - bool original = (s == string.Empty) ? false : bool.Parse(s); + bool original = s != string.Empty && bool.Parse(s); if (original == value) return; // no change. _Xp["PrintSettings", "MergedPdfsViewAfter"] = ((bool)value).ToString(); // save selected value OnPropertyChanged("Print_MergedPdfsViewAfter"); @@ -1469,6 +1334,7 @@ namespace VEPROMS.CSLA.Library { if (_SelectedSlave == value) return; _SelectedSlave = value; + // For Debugging: // if(_DocVersion != null) // Volian.Base.Library.vlnStackTrace.ShowStackLocal("SelectedSlave {0} = {1}", _DocVersion.MyDocVersionUnique, _SelectedSlave.ToString()); // else @@ -1486,13 +1352,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("Number") ?? _Xp["Unit", "Number"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Number"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "Number"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Number"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "Number"] = value; // save selected value else _Xp["Unit", "Number"] = value; OnPropertyChanged("Unit_Number"); @@ -1505,7 +1371,7 @@ namespace VEPROMS.CSLA.Library { string s = ""; if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "oldindex"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "oldindex"]; return s; } } @@ -1520,13 +1386,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("OtherNumber") ?? _Xp["Unit", "OtherNumber"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherNumber"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "OtherNumber"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherNumber"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "OtherNumber"] = value; // save selected value else _Xp["Unit", "OtherNumber"] = value; OnPropertyChanged("Other_Unit_Number"); @@ -1543,14 +1409,14 @@ namespace VEPROMS.CSLA.Library string s = GetCombinedSlaveValue("Name") ?? _Xp["Unit", "Name"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Name"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "Name"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Name"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "Name"] = value; // save selected value else _Xp["Unit", "Name"] = value; @@ -1568,13 +1434,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("OtherName") ?? _Xp["Unit", "OtherName"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherName"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "OtherName"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherName"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "OtherName"] = value; // save selected value else _Xp["Unit", "OtherName"] = value; OnPropertyChanged("Other_Unit_Name"); @@ -1590,13 +1456,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("Text") ?? _Xp["Unit", "Text"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Text"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "Text"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Text"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "Text"] = value; // save selected value else _Xp["Unit", "Text"] = value; OnPropertyChanged("Unit_Text"); @@ -1612,13 +1478,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("OtherText") ?? _Xp["Unit", "OtherText"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherText"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "OtherText"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherText"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "OtherText"] = value; // save selected value else _Xp["Unit", "OtherText"] = value; OnPropertyChanged("Other_Unit_Text"); @@ -1634,13 +1500,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("ID") ?? _Xp["Unit", "ID"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ID"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "ID"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ID"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "ID"] = value; // save selected value else _Xp["Unit", "ID"] = value; OnPropertyChanged("Unit_ID"); @@ -1656,13 +1522,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("OtherID") ?? _Xp["Unit", "OtherID"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherID"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "OtherID"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "OtherID"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "OtherID"] = value; // save selected value else _Xp["Unit", "OtherID"] = value; OnPropertyChanged("Other_Unit_ID"); @@ -1678,13 +1544,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("ProcedureNumber", null) ?? _Xp["Unit", "ProcedureNumber"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ProcedureNumber"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "ProcedureNumber"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ProcedureNumber"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "ProcedureNumber"] = value; // save selected value else _Xp["Unit", "ProcedureNumber"] = value; OnPropertyChanged("Unit_ProcedureNumber"); @@ -1700,13 +1566,13 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("SetName", null) ?? _Xp["ProcedureSet", "Name"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "SetName"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "SetName"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "SetName"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "SetName"] = value; // save selected value else _Xp["ProcedureSet", "Name"] = value; OnPropertyChanged("Unit_ProcedureSetName"); @@ -1722,557 +1588,18 @@ namespace VEPROMS.CSLA.Library { string s = GetCombinedSlaveValue("SetID", null) ?? _Xp["ProcedureSet", "ID"];// get the saved value if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "SetID"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "SetID"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "SetID"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "SetID"] = value; // save selected value else _Xp["ProcedureSet", "ID"] = value; OnPropertyChanged("Unit_ProcedureSetID"); } } - #endregion - #region DELETE_ME - /* - #region ColorCategory // From veproms.ini - // Note that not all possibilities from 16-bit will be added here, until - // it is determined how these will be used - [Category("Color")] - [DisplayName("ro")] - [RefreshProperties(RefreshProperties.All)] - [Description("ro")] - public string Color_ro - { - get - { - return _Xp["Color", "ro"]; - } - set - { - _Xp["Color", "ro"] = value; - OnPropertyChanged("Color_ro"); - } - } - [Category("Color")] - [DisplayName("editbackground")] - [RefreshProperties(RefreshProperties.All)] - [Description("editbackground")] - public string Color_editbackground - { - get - { - return _Xp["Color", "editbackground"]; - } - set - { - _Xp["Color", "editbackground"] = value; - OnPropertyChanged("Color_editbackground"); - } - } - [Category("Color")] - [DisplayName("black")] - [RefreshProperties(RefreshProperties.All)] - [Description("black")] - public string Color_black - { - get - { - return _Xp["Color", "black"]; - } - set - { - _Xp["Color", "black"] = value; - OnPropertyChanged("Color_black"); - } - } - [Category("Color")] - [DisplayName("blue")] - [RefreshProperties(RefreshProperties.All)] - [Description("blue")] - public string Color_blue - { - get - { - return _Xp["Color", "blue"]; - } - set - { - _Xp["Color", "blue"] = value; - OnPropertyChanged("Color_blue"); - } - } - #endregion // From veproms.ini - #region SystemPrintCategory // From veproms.ini - [Category("System Print")] - [DisplayName("Underline Width")] - [RefreshProperties(RefreshProperties.All)] - [Description("Underline Width")] - public int SysPrint_UWidth - { - get - { - string s = _Xp["SystemPrint", "UnderlineWidth"]; - if (s == string.Empty) return 10; - return int.Parse(_Xp["SystemPrint", "UnderlineWidth"]); - } - set - { - _Xp["SystemPrint", "UnderlineWidth"] = value.ToString(); - OnPropertyChanged("SysPrint_UWidth"); - } - } - [Category("System Print")] - [DisplayName("Vertical Offset")] - [RefreshProperties(RefreshProperties.All)] - [Description("Vertical Offset")] - public int SysPrint_VOffset - { - get - { - string s = _Xp["SystemPrint", "VerticalOffset"]; - if (s == string.Empty) return 0; - return int.Parse(_Xp["SystemPrint", "VerticalOffset"]); - } - set - { - _Xp["SystemPrint", "VerticalOffset"] = value.ToString(); - OnPropertyChanged("SysPrint_VOffset"); - } - } - [Category("System Print")] - [DisplayName("Stroke Width")] - [RefreshProperties(RefreshProperties.All)] - [Description("Stroke Width")] - public int SysPrint_StrokeWidth - { - get - { - string s = _Xp["SystemPrint", "StrokeWidth"]; - if (s == string.Empty) return 0; - return int.Parse(_Xp["SystemPrint", "StrokeWidth"]); - } - set - { - _Xp["SystemPrint", "StrokeWidth"] = value.ToString(); - OnPropertyChanged("SysPrint_StrokeWidth"); - } - } - [Category("System Print")] - [DisplayName("Stroke Width Bold")] - [RefreshProperties(RefreshProperties.All)] - [Description("Stroke Width Bold")] - public int SysPrint_StrokeWidthBold - { - get - { - string s = _Xp["SystemPrint", "StrokeWidthBold"]; - if (s == string.Empty) return 0; - return int.Parse(_Xp["SystemPrint", "StrokeWidthBold"]); - } - set - { - _Xp["SystemPrint", "StrokeWidthBold"] = value.ToString(); - OnPropertyChanged("SysPrint_StrokeWidthBold"); - } - } - #endregion - #region StartupCategory // From veproms.ini - [Category("Startup")] - [DisplayName("Startup MessageBox Title")] - [RefreshProperties(RefreshProperties.All)] - [Description("Startup MessageBox Title")] - public string Startup_MsgTitle - { - get - { - return _Xp["Startup", "MessageBoxTitle"]; - } - set - { - _Xp["Startup", "MessageBoxTitle"] = value; - OnPropertyChanged("Startup_MsgTitle"); - } - } - [Category("Startup")] - [DisplayName("Startup Message File")] - [RefreshProperties(RefreshProperties.All)] - [Description("Startup Message File")] - public string Startup_MsgFile - { - get - { - return _Xp["Startup", "MessageFile"]; - } - set - { - _Xp["Startup", "MessageFile"] = value; - OnPropertyChanged("Startup_MsgFile"); - } - } - #endregion - #region ProcedureListTabStopsCategory // From veproms.ini - [Category("ProcedureListTabStops")] - [DisplayName("Procedure Number Tab")] - [RefreshProperties(RefreshProperties.All)] - [Description("Procedure Number Tab")] - public int ProcListTab_Number - { - get - { - string s = _Xp["ProcedureListTabStops", "ProcedureNumberTab"]; - if (s == string.Empty) return 75; - return int.Parse(_Xp["ProcedureListTabStops", "ProcedureNumberTab"]); - } - set - { - _Xp["ProcedureListTabStops", "ProcedureNumberTab"] = value.ToString(); - OnPropertyChanged("ProcListTab_Number"); - } - } - [Category("ProcedureListTabStops")] - [DisplayName("Procedure Title Tab")] - [RefreshProperties(RefreshProperties.All)] - [Description("Procedure Title Tab")] - public int ProcListTab_Title - { - get - { - string s = _Xp["ProcedureListTabStops", "ProcedureTitleTab"]; - if (s == string.Empty) return 175; - return int.Parse(_Xp["ProcedureListTabStops", "ProcedureTitleTab"]); - } - set - { - _Xp["ProcedureListTabStops", "ProcedureTitleTab"] = value.ToString(); - OnPropertyChanged("ProcListTab_Title"); - } - } - #endregion - #region FormatCategory - public enum FormatColumns : int - { - Default=0,OneColumn,TwoColumn,ThreeColumn,FourColumns - } - [Category("Format")] - [DisplayName("Column Layout")] - [RefreshProperties(RefreshProperties.All)] - [Description("Column Layout")] - public FormatColumns Format_Columns - { - get - { - string s = _Xp["format", "columns"]; - if (s == string.Empty) return (FormatColumns)0; - return (FormatColumns)int.Parse(_Xp["format", "columns"]); - //return Enum.Parse(typeof(FormatColumns),_Xp["format", "columns"]); - } - set - { - if (value == 0) _Xp["format", "columns"] = string.Empty; - else _Xp["format", "columns"] = ((int)value).ToString(); - OnPropertyChanged("Format_Columns"); - } - } - [Category("Format")] - [DisplayName("Plant Format Name")] - [RefreshProperties(RefreshProperties.All)] - [Description("Default Plant Format")] - public string Format_Plant - { - get - { return _Xp["format", "plant"]; - } - set - { - _Xp["format", "plant"] = value; - OnPropertyChanged("Format_Plant"); - } - } - #endregion - #region DefaultsCategory // from proc.ini - [Category("Defaults")] - [DisplayName("Default Setpoint Prefix")] - [RefreshProperties(RefreshProperties.All)] - [Description("Default Setpoint Prefix")] - public string Default_SPPrefix - { - get { return _Xp["default", "spprefix"]; } - set - { - _Xp["default", "spprefix"] = value; - OnPropertyChanged("Default_SPPrefix"); - } - } - [Category("Defaults")] - [DisplayName("Default Image Prefix")] - [RefreshProperties(RefreshProperties.All)] - [Description("Default Image Prefix")] - public string Default_IMPrefix - { - get { return _Xp["default", "imprefix"]; } - set - { - _Xp["default", "imprefix"] = value; - OnPropertyChanged("RO_IMPrefix"); - } - } - #endregion - #region PrintSettingsCategory // From curset.dat - [Category("Print Settings")] - [DisplayName("Number of Copies")] - [RefreshProperties(RefreshProperties.All)] - [Description("Number of Copies")] - public int Print_NumCopies - { - get - { - string s = _Xp["PrintSettings", "numcopies"]; - if (s == string.Empty) return 1; - return int.Parse(_Xp["PrintSettings", "numcopies"]); - } - set - { - _Xp["PrintSettings", "numcopies"] = value.ToString(); - OnPropertyChanged("Print_NumCopies"); - } - } - public enum PrintPagination : int - { - Free = 0, Fixed, Auto - } - [Category("Print Settings")] - [DisplayName("Pagination")] - [RefreshProperties(RefreshProperties.All)] - [Description("Pagination")] - public PrintPagination Print_Pagination - { - get - { - string s = _Xp["PrintSettings", "Pagination"]; - if (s == string.Empty) return PrintPagination.Auto; - return (PrintPagination)int.Parse(_Xp["PrintSettings", "Pagination"]); - } - set - { - if (value == PrintPagination.Auto) _Xp["PrintSettings", "Pagination"] = string.Empty; - else _Xp["PrintSettings", "Pagination"] = ((int)value).ToString(); - OnPropertyChanged("Print_Pagination"); - } - } - public enum PrintWatermark : int - { - None = 0, Reference, Draft, Master, Sample, InformationOnly - } - [Category("Print Settings")] - [DisplayName("Watermark")] - [RefreshProperties(RefreshProperties.All)] - [Description("Watermark")] - public PrintWatermark Print_Watermark - { - get - { - string s = _Xp["PrintSettings", "Watermark"]; - if (s == string.Empty) return PrintWatermark.Draft; - return (PrintWatermark)int.Parse(_Xp["PrintSettings", "Watermark"]); - } - set - { - if (value == PrintWatermark.Draft) _Xp["PrintSettings", "Watermark"] = string.Empty; - else _Xp["PrintSettings", "Watermark"] = ((int)value).ToString(); - OnPropertyChanged("Print_Watermark"); - } - } - [Category("Print Settings")] - [DisplayName("Disable Duplex Printing")] - [RefreshProperties(RefreshProperties.All)] - [Description("Disable Duplex Printing")] - public bool Print_DisableDuplex - { - get - { - string s = _Xp["PrintSettings", "disableduplex"]; - if (s == string.Empty) return false; - return bool.Parse(_Xp["PrintSettings", "disableduplex"]); - } - set - { - _Xp["PrintSettings", "disableduplex"] = value.ToString(); - OnPropertyChanged("Print_DisableDuplex"); - } - } - // Change Bar Use from 16-bit code: - // No Default - // Without Change Bars - // With Default Change Bars - // With User Specified Change Bars - public enum PrintChangeBar : int - { - NoDefault=0, Without, WithDefault, WithUserSpecified - } - [Category("Print Settings")] - [DisplayName("Change Bar")] - [RefreshProperties(RefreshProperties.All)] - [Description("Change Bar Use")] - public PrintChangeBar Print_ChangeBar - { - get - { - string s = _Xp["PrintSettings", "ChangeBar"]; - if (s == string.Empty) return PrintChangeBar.NoDefault; - return (PrintChangeBar)int.Parse(_Xp["PrintSettings", "ChangeBar"]); - } - set - { - if (value == PrintChangeBar.NoDefault) _Xp["PrintSettings", "ChangeBar"] = string.Empty; - else _Xp["PrintSettings", "ChangeBar"] = ((int)value).ToString(); - OnPropertyChanged("Print_ChangeBar"); - } - } - // User Specified Change Bar Location from16-bit code: - // With Text - // Outside Box - // AER on LEFT, RNO on Right - // To the Left of Text - public enum PrintChangeBarLoc : int - { - WithText = 0, OutsideBox, AERleftRNOright, LeftOfText - } - [Category("Print Settings")] - [DisplayName("Change Bar Location")] - [RefreshProperties(RefreshProperties.All)] - [Description("User Specified Change Bar Location")] - public PrintChangeBarLoc Print_ChangeBarLoc - { - get - { - string s = _Xp["PrintSettings", "ChangeBarLoc"]; - if (s == string.Empty) return PrintChangeBarLoc.WithText; - return (PrintChangeBarLoc)int.Parse(_Xp["PrintSettings", "ChangeBarLoc"]); - } - set - { - if (value == PrintChangeBarLoc.WithText) _Xp["PrintSettings", "ChangeBarLoc"] = string.Empty; - else _Xp["PrintSettings", "ChangeBarLoc"] = ((int)value).ToString(); - OnPropertyChanged("Print_ChangeBarLoc"); - } - } - - // Change Bar Text from16-bit code: - // Date and Change ID - // Revision Number - // Change ID - // No Change Bar Message - // User Defined Message - public enum PrintChangeBarText : int - { - DateChgID = 0, RevNum, ChgID, None, UserDef - } - [Category("Print Settings")] - [DisplayName("Change Bar Text")] - [RefreshProperties(RefreshProperties.All)] - [Description("Change Bar Text")] - public PrintChangeBarText Print_ChangeBarText - { - get - { - string s = _Xp["PrintSettings", "ChangeBarText"]; - if (s == string.Empty) return PrintChangeBarText.DateChgID; - return (PrintChangeBarText)int.Parse(_Xp["PrintSettings", "ChangeBarText"]); - } - set - { - if (value == PrintChangeBarText.DateChgID) _Xp["PrintSettings", "ChangeBarText"] = string.Empty; - else _Xp["PrintSettings", "ChangeBarText"] = ((int)value).ToString(); - OnPropertyChanged("Print_ChangeBarText"); - } - } - - [Category("Print Settings")] - [DisplayName("User Format")] - [RefreshProperties(RefreshProperties.All)] - [Description("User Format")] - public string Print_UserFormat - { - get - { - return _Xp["PrintSettings", "userformat"]; - } - set - { - _Xp["PrintSettings", "userformat"] = value; - OnPropertyChanged("Print_UserFormat"); - } - } - - [Category("Print Settings")] - [DisplayName("User Change Bar Message1")] - [RefreshProperties(RefreshProperties.All)] - [Description("User Change Bar Message1")] - public string Print_UserCBMess1 - { - get - { - return _Xp["PrintSettings", "usercbmess1"]; - } - set - { - _Xp["PrintSettings", "usercbmess1"] = value; - OnPropertyChanged("Print_UserCBMess1"); - } - } - - [Category("Print Settings")] - [DisplayName("User Change Bar Message2")] - [RefreshProperties(RefreshProperties.All)] - [Description("User Change Bar Message2")] - public string Print_UserCBMess2 - { - get - { - return _Xp["PrintSettings", "usercbmess2"]; - } - set - { - _Xp["PrintSettings", "usercbmess2"] = value; - OnPropertyChanged("Print_UserCBMess2"); - } - } - #endregion -[Category("Defaults")] -[DisplayName("Default BackColor")] -[RefreshProperties(RefreshProperties.All)] -[Description("Default Background Color")] -public Color Default_BkColor -{ -get -{ -//return _Xp["default", "BkColor"]; -string sColor = _Xp["default", "BkColor"]; -if (sColor == string.Empty) sColor = "White"; -if (sColor[0] == '[') -{ -string[] parts = sColor.Substring(1, sColor.Length - 2).Split(",".ToCharArray()); -return Color.FromArgb(Int32.Parse(parts[0]), Int32.Parse(parts[1]), Int32.Parse(parts[2])); -} -else return Color.FromName(sColor); -} -set -{ -if (value.IsNamedColor) _Xp["default", "BkColor"] = value.Name; -else -{ -_Xp["default", "BkColor"] = string.Format("[{0},{1},{2}]", value.R, value.G, value.B); -} -OnPropertyChanged("Default_BkColor"); - -} -} -} -} -*/ #endregion #region Slave public void AddSlave(string xml) @@ -2281,16 +1608,16 @@ OnPropertyChanged("Default_BkColor"); xd.LoadXml(xml); XmlNode pn = _Xp.XmlContents.SelectSingleNode("//Slaves"); XmlNode nn = _Xp.XmlContents.ImportNode(xd.DocumentElement, true); - if (pn == null) - { - pn = _Xp.XmlContents.CreateElement("Slaves"); - _Xp.XmlContents.DocumentElement.AppendChild(pn); - } + if (pn == null) + { + pn = _Xp.XmlContents.CreateElement("Slaves"); + _Xp.XmlContents.DocumentElement.AppendChild(pn); + } pn.AppendChild(nn); } public void RemoveSlave(int index) { - XmlNode dd = _Xp.XmlContents.SelectSingleNode("//Slave[@index='" + index.ToString() + "']"); + XmlNode dd = _Xp.XmlContents.SelectSingleNode($"//Slave[@index='{index}']"); dd?.ParentNode?.RemoveChild(dd); } public int MaxSlaveIndex @@ -2315,22 +1642,19 @@ OnPropertyChanged("Default_BkColor"); foreach (XmlNode nd in nl) { string ss = nd.Attributes.GetNamedItem("index").InnerText; - s += sep + _Xp["Slave[@index='" + ss + "']", item]; + s += $"{sep}{_Xp[$"Slave[@index='{ss}']", item]}"; sep = ","; } return s; } return defaultValue; } - private string GetCombinedSlaveValue(string item) - { - return GetCombinedSlaveValue(item, "0"); - } - //end added by jcb to fix master issue byron/braidwood - #endregion - #region Enhanced - // C2019-045: For enhanced procedures, allow modifications of number & text. - [Category("Enhanced Settings")] + private string GetCombinedSlaveValue(string item) => GetCombinedSlaveValue(item, "0"); + //end added by jcb to fix master issue byron/braidwood + #endregion + #region Enhanced + // C2019-045: For enhanced procedures, allow modifications of number & text. + [Category("Enhanced Settings")] [Browsable(false)] [DisplayName("AllowMods")] [RefreshProperties(RefreshProperties.All)] diff --git a/PROMS/VEPROMS.CSLA.Library/Config/DocumentConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/DocumentConfig.cs index 49a88a0e..b6cab99f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/DocumentConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/DocumentConfig.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using System.Drawing; -using System.Text.RegularExpressions; namespace VEPROMS.CSLA.Library { @@ -12,15 +8,11 @@ namespace VEPROMS.CSLA.Library public class DocumentConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + private readonly XMLProperties _Xp; #endregion #region Constructors public Document _Document; - private DocumentInfo _DocumentInfo; + private readonly DocumentInfo _DocumentInfo; public DocumentConfig(Document document) { _Document = document; @@ -35,13 +27,10 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Properties - [Category("General")] + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Properties + [Category("General")] [DisplayName("Name")] [Description("Name")] public string Name @@ -100,48 +89,13 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("History_OriginalFileName"); } } - // RHM 20110415 - These are now stored in the PDF table. - //[Category("Printing")] - //[DisplayName("Length")] - //[Description("Length of Document in Full and Partial Pages")] - //public float Printing_Length - //{ - // get - // { - // string s = _Xp["Printing", "Length"];// get the saved value - - // return float.Parse(s); - // } - // set - // { - // _Xp["Printing", "Length"] = string.Format("{0:0.0000}", value); - // OnPropertyChanged("Printing_Length"); - // } - //} - //[Category("Printing")] - //[DisplayName("Color")] - //[Description("Color of Document Text")] - //public Color Printing_Color - //{ - // get - // { - // string sColor = _Xp["Printing", "Color"]; - // return ColorConfig.ColorFromString(sColor); - // } - // set - // { - // _Xp["Printing", "Color"] = value.ToString(); - // OnPropertyChanged("Printing_Color"); - // } - //} #endregion #region ToString public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - } + return s == "" || s == "" ? string.Empty : s; + } + #endregion + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/DynamicProperties.cs b/PROMS/VEPROMS.CSLA.Library/Config/DynamicProperties.cs index 61bc8b2c..c755a75d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/DynamicProperties.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/DynamicProperties.cs @@ -1,17 +1,13 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using System.Xml; using System.Xml.Serialization; -using System.Xml.Schema; namespace VEPROMS.CSLA.Library { public class DynamicPropertyDescriptor : PropertyDescriptor { - private PropertyDescriptor _BasePropertyDescriptor; - private ConfigDynamicTypeDescriptor _Instance; + private readonly PropertyDescriptor _BasePropertyDescriptor; + private readonly ConfigDynamicTypeDescriptor _Instance; public DynamicPropertyDescriptor(ConfigDynamicTypeDescriptor instance, PropertyDescriptor basePropertyDescriptor) : base(basePropertyDescriptor) @@ -37,16 +33,15 @@ namespace VEPROMS.CSLA.Library { _BasePropertyDescriptor.SetValue(component, value); } } [Serializable()] - public class ConfigDynamicTypeDescriptor //: ICustomTypeDescriptor//, ISupportInitialize + public class ConfigDynamicTypeDescriptor { #region Events public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(String info) { _IsDirty = true; - if (PropertyChanged != null) - PropertyChanged(this, new PropertyChangedEventArgs(info)); - } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); + } [NonSerialized] private bool _IsDirty = false; [XmlIgnore] @@ -57,54 +52,11 @@ namespace VEPROMS.CSLA.Library set { _IsDirty = value; } } #endregion - [NonSerialized] - private PropertyDescriptorCollection dynamicProps; private bool _IsReadOnly = false; internal virtual bool IsReadOnly { get { return _IsReadOnly; } set { _IsReadOnly = value; } } - public ConfigDynamicTypeDescriptor() { } - #region "TypeDescriptor Implementation" - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { - return GetProperties(); - } - public PropertyDescriptorCollection GetProperties() - { - if (dynamicProps == null) - { - PropertyDescriptorCollection baseProps = TypeDescriptor.GetProperties(this, true); - dynamicProps = new PropertyDescriptorCollection(null); - - foreach (PropertyDescriptor oProp in baseProps) - { - dynamicProps.Add(new DynamicPropertyDescriptor(this, oProp)); - } - } - return dynamicProps; - } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - #endregion } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/EnumDescConverter.cs b/PROMS/VEPROMS.CSLA.Library/Config/EnumDescConverter.cs index cd05d4a7..ec3a5715 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/EnumDescConverter.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/EnumDescConverter.cs @@ -13,8 +13,6 @@ using System; using System.ComponentModel; -using System.Drawing; -using System.Drawing.Design; using System.Reflection; using System.Collections; using System.Data; @@ -97,26 +95,26 @@ namespace DescriptiveEnum public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { - if(value is Enum && destinationType == typeof(string)) + if(value is Enum myenum && destinationType == typeof(string)) { - return EnumDescConverter.GetEnumDescription((Enum)value); + return EnumDescConverter.GetEnumDescription(myenum); } - if(value is string && destinationType == typeof(string)) + if(value is string mystr && destinationType == typeof(string)) { - return EnumDescConverter.GetEnumDescription(myVal, (string)value); + return EnumDescConverter.GetEnumDescription(myVal, mystr); } return base.ConvertTo (context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - if(value is string) + if(value is string mystr) { - return EnumDescConverter.GetEnumValue(myVal, (string)value); + return EnumDescConverter.GetEnumValue(myVal, mystr); } - if(value is Enum) + if(value is Enum myenum) { - return EnumDescConverter.GetEnumDescription((Enum)value); + return EnumDescConverter.GetEnumDescription(myenum); } return base.ConvertFrom (context, culture, value); } @@ -125,7 +123,8 @@ namespace DescriptiveEnum return true; } - public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "Keeping attributes for future extensions")] + public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { ArrayList values = new ArrayList(); FieldInfo[] fis = myVal.GetFields(); @@ -133,7 +132,6 @@ namespace DescriptiveEnum { DescriptionAttribute[] attributes =(DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); - //if (attributes.Length > 0) if (fi.Name != "value__") values.Add(fi.GetValue(fi.Name)); } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/EnumDetail.cs b/PROMS/VEPROMS.CSLA.Library/Config/EnumDetail.cs index d983be55..4e31f1ca 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/EnumDetail.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/EnumDetail.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Reflection; using System.ComponentModel; @@ -8,23 +6,13 @@ namespace VEPROMS.CSLA.Library { public class EnumDetail { - private T _EValue; - public T EValue - { - get { return _EValue; } - set { _EValue = value; } - } - private string _Name; + public T EValue { get; set; } - public string Name + public string Name { get; set; } + public EnumDetail(string name, T eValue) { - get { return _Name; } - set { _Name = value; } - } - public EnumDetail(string name, T eValue) - { - _Name = name; - _EValue = eValue; + Name = name; + EValue = eValue; } public static EnumDetail[] Details() { diff --git a/PROMS/VEPROMS.CSLA.Library/Config/FolderConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/FolderConfig.cs index 940b84d4..270ce63b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/FolderConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/FolderConfig.cs @@ -1,29 +1,18 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; using System.Drawing; -using DescriptiveEnum; namespace VEPROMS.CSLA.Library { [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] - //public class FolderConfig : INotifyPropertyChanged public class FolderConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _Folder == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _Folder == null; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors //PROPGRID: Hide ParentLookup @@ -33,19 +22,8 @@ namespace VEPROMS.CSLA.Library get { return _Xp.ParentLookup; } set { _Xp.ParentLookup = value; } } - //PROPGRID: Hide AncestorLookup - //PROPGRID: Needed to comment out [NonSerialized] in order to hide this field from the property grid - //[NonSerialized] - //[Browsable(false)] - //private bool _AncestorLookup; - //[Browsable(false)] - //public bool AncestorLookup - //{ - // get { return _AncestorLookup; } - // set { _AncestorLookup = value; } - //} - private Folder _Folder; - private FolderInfo _FolderInfo; + private readonly Folder _Folder; + private readonly FolderInfo _FolderInfo; public FolderConfig(Folder folder) { _Folder = folder; @@ -75,18 +53,6 @@ namespace VEPROMS.CSLA.Library return false; } } - //private string Xp_LookInAncestorFolderInfo(object sender, XMLPropertiesArgs args) - //{ - // if (args.AncestorLookup || ParentLookup) - // { - // for (FolderInfo folder = _FolderInfo.MyParent; folder != null; folder = folder.MyParent) - // { - // string retval = folder.FolderConfig.GetValue(args.Group, args.Item); - // if (retval != string.Empty) return retval; - // } - // } - // return string.Empty; - //} public FolderConfig(FolderInfo folderInfo) { _FolderInfo = folderInfo; @@ -100,21 +66,12 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - public FolderConfig() - { - _Xp = new XMLProperties(""); - } - public string GetValue(string group, string item) - { - return _Xp[group, item]; - } - public void SetValue(string group, string item, string newvalue) - { - _Xp[group, item] = newvalue; - } - #endregion - #region Local Properties - [Category("General")] + public FolderConfig() => _Xp = new XMLProperties(""); + public string GetValue(string group, string item) => _Xp[group, item]; + public void SetValue(string group, string item, string newvalue) => _Xp[group, item] = newvalue; + #endregion + #region Local Properties + [Category("General")] [DisplayName("Name")] [Description("Name")] public string Name @@ -189,7 +146,6 @@ namespace VEPROMS.CSLA.Library if (_Folder != null) { _Folder.MyFormat = FormatList.ToFormat(value); - //_Folder.ActiveFormat = null; } } } @@ -206,24 +162,17 @@ namespace VEPROMS.CSLA.Library return null; } } - public Folder MyFolder - { get { return _Folder; } } - public FolderInfo MyFolderInfo - { get { return _FolderInfo; } } - #endregion - #region ToString - public override string ToString() + public Folder MyFolder => _Folder; + public FolderInfo MyFolderInfo => _FolderInfo; + #endregion + #region ToString + public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - #region GraphicsCategory // From veproms.ini - public bool CanWrite(string str) - { - return true; - } + return s == "" || s == "" ? string.Empty : s; + } + #endregion + #region GraphicsCategory // From veproms.ini [Category("Referenced Objects")] [DisplayName("Graphic File Extension")] [RefreshProperties(RefreshProperties.All)] @@ -304,103 +253,6 @@ namespace VEPROMS.CSLA.Library } } #endregion - //#region ColorCategory // From veproms.ini - //// ** Note that not all possibilities from 16-bit will be added here, until - //// ** it is determined how these will be used - //// ** If this is used (unhidden), then we need to add logic to blank setting if the value - //// ** we are saving is the same as the parent's value. - - ////PROPGRID: Hide Editor Color for ROs - //[Category("Editor Settings")] - //[Browsable(false)] - //[DisplayName("Step Editor Colors - Referenced Objects")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Color used to highlight an RO in procedure text")] - //public string Color_ro - //{ - // get - // { - // return _Xp["Color", "ro"]; - // } - // set - // { - // _Xp["Color", "ro"] = value; - // OnPropertyChanged("Color_ro"); - // } - //} - ////PROPGRID: Hide Editor Color for Transitions - //[Category("Editor Settings")] - //[Browsable(false)] - //[DisplayName("Step Editor Colors - Transitions")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Color used to highlight a Transition in procedure text")] - //public string Color_transition - //{ - // get - // { - // return _Xp["Color", "transition"]; - // } - // set - // { - // _Xp["Color", "transition"] = value; - // OnPropertyChanged("Color_transition"); - // } - //} - ////PROPGRID: Hide Active Text Background Color - //[Category("Editor Settings")] - //[Browsable(false)] - //[DisplayName("Step Editor Colors - Active Background")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("editbackground")] - //public string Color_editbackground - //{ - // get - // { - // return _Xp["Color", "editbackground"]; - // } - // set - // { - // _Xp["Color", "editbackground"] = value; - // OnPropertyChanged("Color_editbackground"); - // } - //} - ////PROPGRID: Hide color setting for Black - //[Category("Color")] - //[Browsable(false)] - //[DisplayName("black")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("black")] - //public string Color_black - //{ - // get - // { - // return _Xp["Color", "black"]; - // } - // set - // { - // _Xp["Color", "black"] = value; - // OnPropertyChanged("Color_black"); - // } - //} - ////PROPGRID: Hide Color Setting for Blue - //[Category("Color")] - //[Browsable(false)] - //[DisplayName("blue")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("blue")] - //public string Color_blue - //{ - // get - // { - // return _Xp["Color", "blue"]; - // } - // set - // { - // _Xp["Color", "blue"] = value; - // OnPropertyChanged("Color_blue"); - // } - //} - //#endregion // From veproms.ini #region SystemPrintCategory // From veproms.ini [Category("Print Settings")] [DisplayName("Override Underline Thickness (dots)")] @@ -635,20 +487,6 @@ namespace VEPROMS.CSLA.Library } #endregion #region FormatCategory - //[TypeConverter(typeof(EnumDescConverter))] - //public enum FormatColumns : int - //{ - // [Description("Format Default")] - // Default = 0, - // [Description("Single Column")] - // OneColumn, - // [Description("Dual Column")] - // TwoColumn, - // [Description("Triple Column")] - // ThreeColumn, - // [Description("Quad Column")] - // FourColumns - //} [Category("Editor Settings")] [DisplayName("Step Editor Columns")] [RefreshProperties(RefreshProperties.All)] @@ -726,10 +564,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_NumCopies"); } } - //public enum PrintPagination : int - //{ - // Free = 0, Fixed, Auto - //} [Category("Print Settings")] [DisplayName("Pagination")] [RefreshProperties(RefreshProperties.All)] @@ -767,13 +601,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_Pagination"); } } - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintWatermark : int - //{ - // None = 0, Reference, Draft, Master, Sample, - // [Description("Information Only")] - // InformationOnly - //} [Category("Print Settings")] [DisplayName("Watermark")] @@ -812,23 +639,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_Watermark"); } } - // Change Bar Use from 16-bit code: - // No Default - // Without Change Bars - // With Default Change Bars - // With User Specified Change Bars - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBar : int - //{ - // [Description("Select Before Printing")] - // SelectBeforePrinting = 0, - // [Description("Without Change Bars")] - // Without, - // [Description("With Default Change Bars")] - // WithDefault, - // [Description("Use Custom Change Bars")] - // WithUserSpecified - //} [Category("Format Settings")] [DisplayName("Change Bar")] [RefreshProperties(RefreshProperties.All)] @@ -866,24 +676,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_ChangeBar"); } } - // User Specified Change Bar Location from16-bit code: - // With Text - // Outside Box - // AER on LEFT, RNO on Right - // To the Left of Text - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBarLoc : int - //{ - // [Description("With Text")] - // WithText = 0, - // [Description("Outside Box")] - // OutsideBox, - // [Description("AER on Left RNO on Right")] - // AERleftRNOright, - // [Description("To the Left of the Text")] - // LeftOfText - //} - [Category("Format Settings")] [DisplayName("Change Bar Position")] [RefreshProperties(RefreshProperties.All)] @@ -922,26 +714,6 @@ namespace VEPROMS.CSLA.Library } } - // Change Bar Text from16-bit code: - // Date and Change ID - // Revision Number - // Change ID - // No Change Bar Message - // User Defined Message - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBarText : int - //{ - // [Description("Date and Change ID")] - // DateChgID = 0, - // [Description("Revision Number")] - // RevNum, - // [Description("Change ID")] - // ChgID, - // [Description("No Change Bar Text")] - // None, - // [Description("Custom Change Bar Text")] - // UserDef - //} [Category("Format Settings")] [DisplayName("Change bar Text Type")] [RefreshProperties(RefreshProperties.All)] diff --git a/PROMS/VEPROMS.CSLA.Library/Config/FormatConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/FormatConfig.cs index d5617806..30707a17 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/FormatConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/FormatConfig.cs @@ -1,15 +1,10 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Text; using System.ComponentModel; -using DescriptiveEnum; using System.Xml; using System.Xml.Serialization; using System.Xml.Schema; -using System.Windows.Forms; using Volian.Base.Library; -using System.Drawing; namespace VEPROMS.CSLA.Library { @@ -28,13 +23,6 @@ namespace VEPROMS.CSLA.Library get { return false; } } #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } - #endregion #region Attributes [XmlAttribute("Name")] private string _Name; @@ -69,27 +57,14 @@ namespace VEPROMS.CSLA.Library } #endregion Elements #region Constructors - private Format _Format; - private FormatInfo _FormatInfo; - public FormatConfig(string xml) - { - if (xml == string.Empty) xml = ""; - } - public FormatConfig(FormatInfo fi) - { - _FormatInfo = fi; - } - public FormatConfig(Format f) - { - _Format = f; - } - public FormatConfig() - { - PlantFormat = new PlantFormatx(); - } - #endregion Constructors - #region Serialize - public string ConvertToString() + private readonly Format _Format; + private readonly FormatInfo _FormatInfo; + public FormatConfig(FormatInfo fi) => _FormatInfo = fi; + public FormatConfig(Format f) => _Format = f; + public FormatConfig() => PlantFormat = new PlantFormatx(); + #endregion Constructors + #region Serialize + public string ConvertToString() { return GenericSerializer.StringSerialize(this); } @@ -131,11 +106,8 @@ namespace VEPROMS.CSLA.Library { } - public override string ToString() - { - return "Plant Format"; - } - } + public override string ToString() => "Plant Format"; + } #endregion PlantFormat #region FormatData // FormatData maps to the PlantFormat/Format data and contains properties & data objects that are implemented for the user to @@ -202,11 +174,8 @@ namespace VEPROMS.CSLA.Library { ReplaceStrData = new ReplaceStrData(); } - public override string ToString() - { - return "Format Data"; - } - } + public override string ToString() => "Format Data"; + } #endregion FormatData #region Flags [Serializable] @@ -242,27 +211,15 @@ namespace VEPROMS.CSLA.Library [Editor(typeof(PropGridCollEditor), typeof(System.Drawing.Design.UITypeEditor))] public class ReplaceStrData : List { - [Browsable(false)] - public int Capacity { get { return base.Capacity; } } - [Browsable(false)] - public int Count { get { return base.Count; } } - public ReplaceStr this[int index] - { - get { return (ReplaceStr)base[index]; } - } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "Replace Words List Count = " + base.Count.ToString(); - } - public static ReplaceStrData Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - } + [Browsable(false)] + public new int Capacity => base.Capacity; + [Browsable(false)] + public new int Count => base.Count; + public new ReplaceStr this[int index] => (ReplaceStr)base[index]; + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => $"Replace Words List Count = {base.Count}"; + public static ReplaceStrData Get(string xml) => GenericSerializer.StringDeserialize(xml); + } #endregion ReplaceStrData #region ReplaceStr @@ -303,19 +260,10 @@ namespace VEPROMS.CSLA.Library public ReplaceStr() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return ReplaceWord; - } - public static ReplaceStr Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => ReplaceWord; + public static ReplaceStr Get(string xml) => GenericSerializer.StringDeserialize(xml); + } #endregion ReplaceStr #region CheckOffHeaders (list) [Serializable] @@ -323,23 +271,14 @@ namespace VEPROMS.CSLA.Library [Editor(typeof(PropGridCollEditor), typeof(System.Drawing.Design.UITypeEditor))] public class CheckOffHeaderList : List { - [Browsable(false)] - public int Capacity { get { return base.Capacity; } } - [Browsable(false)] - public int Count { get { return base.Count; } } - public CheckOffHeader this[int index] - { - get { return (CheckOffHeader)base[index]; } - } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "CheckOffHeader Count = " + base.Count.ToString(); - } - } + [Browsable(false)] + public new int Capacity => base.Capacity; + [Browsable(false)] + public new int Count { get { return base.Count; } } + public new CheckOffHeader this[int index] => (CheckOffHeader)base[index]; + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => $"CheckOffHeader Count = {base.Count}"; + } #endregion CheckOffHeaders #region CheckOffHeader [Serializable] @@ -382,15 +321,9 @@ namespace VEPROMS.CSLA.Library public CheckOffHeader() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return CheckOffHeading; - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => CheckOffHeading; + } #endregion CheckOffHeader #region CheckOffs (list) [Serializable] @@ -399,22 +332,13 @@ namespace VEPROMS.CSLA.Library public class CheckOffList : List { [Browsable(false)] - public int Capacity { get { return base.Capacity; } } + public new int Capacity { get { return base.Capacity; } } [Browsable(false)] - public int Count { get { return base.Count; } } - public CheckOff this[int index] - { - get { return (CheckOff)base[index]; } - } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "CheckOff Count = " + base.Count.ToString(); - } - } + public new int Count { get { return base.Count; } } + public new CheckOff this[int index] => (CheckOff)base[index]; + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => $"CheckOff Count = {base.Count}"; + } #endregion CheckOffs #region CheckOff [Serializable] @@ -457,15 +381,9 @@ namespace VEPROMS.CSLA.Library public CheckOff() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return MenuItem; - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => MenuItem; + } #endregion CheckOff #region ShwRplWds [Serializable] @@ -508,15 +426,9 @@ namespace VEPROMS.CSLA.Library public ShwRplWds() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return MenuItem; - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => MenuItem; + } #endregion ShwRplWds #region StepData (list) [Serializable] @@ -525,26 +437,14 @@ namespace VEPROMS.CSLA.Library public class StepData : List { [Browsable(false)] - public int Capacity { get { return base.Capacity; } } + public new int Capacity { get { return base.Capacity; } } [Browsable(false)] - public int Count { get { return base.Count; } } - public Step this[int index] - { - get { return (Step)base[index]; } - } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "Step Count = " + base.Count.ToString(); - } - public static StepData Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - } + public new int Count { get { return base.Count; } } + public new Step this[int index] => (Step)base[index]; + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => $"Step Count = {base.Count}"; + public static StepData Get(string xml) => GenericSerializer.StringDeserialize(xml); + } #endregion StepData #region Step [Serializable] @@ -577,28 +477,16 @@ namespace VEPROMS.CSLA.Library public Step() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return Type; - } - public static Step Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => Type; + public static Step Get(string xml) => GenericSerializer.StringDeserialize(xml); + } #endregion Step #region FontDesc [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class FontDesc { - // The Font object allows the conversion from a windows font back/forth from a string. This is how the - // data is stored in the database, i.e. a string representing the font. - private Font _Font; [XmlAttribute("Font")] [Browsable(false)] public string Font @@ -633,19 +521,10 @@ namespace VEPROMS.CSLA.Library public FontDesc() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "FontDescription"; - } - public static FontDesc Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => "FontDescription"; + public static FontDesc Get(string xml) => GenericSerializer.StringDeserialize(xml); + } #endregion Font #region DocStyles [Serializable] @@ -654,22 +533,13 @@ namespace VEPROMS.CSLA.Library public class DocStyles : List { [Browsable(false)] - public int Capacity { get { return base.Capacity; } } + public new int Capacity { get { return base.Capacity; } } [Browsable(false)] - public int Count { get { return base.Count; } } - public DocStyle this[int index] - { - get { return (DocStyle)base[index]; } - } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "Section Type Count = " + base.Count.ToString(); - } - } + public new int Count { get { return base.Count; } } + public new DocStyle this[int index] => (DocStyle)base[index]; + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => $"Section Type Count = {base.Count}"; + } #endregion DocStyles #region DocStyle [Serializable] @@ -702,15 +572,9 @@ namespace VEPROMS.CSLA.Library public DocStyle() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return Name; - } - } + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => Name; + } #endregion DocStyle #region Layout [Serializable] @@ -752,18 +616,12 @@ namespace VEPROMS.CSLA.Library public Layout() { } - public string ConvertToString() - { - return GenericSerializer.StringSerialize(this); - } - public override string ToString() - { - return "Layout"; - } - #region IXmlSerializable members - // The read & write for these is necessary since they are within same xml element, and one may be empty, so - // no attribute should be listed in the xml. - public void WriteXml(XmlWriter writer) + public string ConvertToString() => GenericSerializer.StringSerialize(this); + public override string ToString() => "Layout"; + #region IXmlSerializable members + // The read & write for these is necessary since they are within same xml element, and one may be empty, so + // no attribute should be listed in the xml. + public void WriteXml(XmlWriter writer) { if (LeftMargin != null) writer.WriteAttributeString("LeftMargin", LeftMargin.ToString()); if (PageLength != null) writer.WriteAttributeString("PageLength", PageLength.ToString()); @@ -780,12 +638,9 @@ namespace VEPROMS.CSLA.Library } } - public XmlSchema GetSchema() - { - return (null); - } - #endregion - } + public XmlSchema GetSchema() => (null); + #endregion + } #endregion Layout } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ImageConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/ImageConfig.cs index ae9eb0cd..e06a0db1 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ImageConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ImageConfig.cs @@ -7,21 +7,14 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class ImageConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _ImageInfo == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _ImageInfo == null; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors - private ImageInfo _ImageInfo; + private readonly ImageInfo _ImageInfo; public ImageConfig(ImageInfo imageInfo) { if (imageInfo == null) @@ -40,13 +33,10 @@ namespace VEPROMS.CSLA.Library string xml = ""; _Xp = new XMLProperties(xml); } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Local Properties - [Category("Image")] + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Local Properties + [Category("Image")] [Browsable(false)] [DisplayName("DataSize")] [RefreshProperties(RefreshProperties.All)] @@ -57,16 +47,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Image", "DataSize"]; if (s == string.Empty) return 0; - int tst = 0; + int tst; try { tst = int.Parse(s); } - catch (Exception ex) + catch (Exception) { return 0; } - return int.Parse(s); + return tst; } set { @@ -87,16 +77,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Image", "Width"]; if (s == string.Empty) return 0; - int tst = 0; + int tst; try { tst = int.Parse(s); } - catch (Exception ex) + catch (Exception) { return 0; } - return int.Parse(s); + return tst; } set { @@ -117,16 +107,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Image", "Height"]; if (s == string.Empty) return 0; - int tst = 0; + int tst; try { tst = int.Parse(s); } - catch (Exception ex) + catch (Exception) { return 0; } - return int.Parse(s); + return tst; } set { @@ -141,9 +131,8 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - } + return s == "" || s == "" ? string.Empty : s; + } + #endregion + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ProcConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/ProcConfig.cs index d3a5468f..4c2efe56 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ProcConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ProcConfig.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using DescriptiveEnum; using System.Xml; namespace VEPROMS.CSLA.Library @@ -11,18 +8,11 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class ProcedureConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged, IItemConfig { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _Procedure == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _Procedure == null; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors //PROPGRID: Hide ParentLookup @@ -32,24 +22,14 @@ namespace VEPROMS.CSLA.Library get { return _Xp.ParentLookup; } set { _Xp.ParentLookup = value; } } - //PROPGRID: Needed to comment out [NonSerialized] in order to hide AncestorLookup from property grid - //[NonSerialized] - //private bool _AncestorLookup; - ////PROPGRID: Hide AncestorLookup - //[Browsable(false)] - //public bool AncestorLookup - //{ - // get { return _AncestorLookup; } - // set { _AncestorLookup = value; } - //} - private Procedure _Procedure; - private ProcedureInfo _ProcedureInfo; + private readonly Procedure _Procedure; + private readonly ProcedureInfo _ProcedureInfo; public ProcedureConfig(Procedure procedure) { _Procedure = procedure; string xml = procedure.MyContent.Config; - if (xml == string.Empty) - xml = ""; + if (xml == string.Empty) + xml = ""; _Xp = new XMLProperties(xml); // Correct Slaves nodes for Parent Child ValidateSlaves(_Xp.XmlContents, _Procedure.MyProcedureInfo.MyDocVersion.MultiUnitCount); @@ -74,7 +54,7 @@ namespace VEPROMS.CSLA.Library } for (int i = 1; i <= unitCount; i++) { - XmlNode xnc = xn.SelectSingleNode(string.Format("Slave[@index='{0}']", i)); + XmlNode xnc = xn.SelectSingleNode($"Slave[@index='{i}']"); if (xnc == null) // Missing Required Slave Node (index=i) - Add it. { XmlElement xec = xd.CreateElement("Slave"); @@ -98,9 +78,8 @@ namespace VEPROMS.CSLA.Library retval = proc.ProcedureConfig.GetValue(args.Group, args.Item); if (retval != string.Empty) return retval; } - DocVersionInfo docVersion = proc.ActiveParent as DocVersionInfo; - if (docVersion == null) return string.Empty; - retval = docVersion.DocVersionConfig.GetValue(args.Group, args.Item); + if (!(proc.ActiveParent is DocVersionInfo docVersion)) return string.Empty; + retval = docVersion.DocVersionConfig.GetValue(args.Group, args.Item); if (retval != string.Empty) return retval; for (FolderInfo folder = docVersion.MyFolder; folder != null; folder = folder.MyParent) { @@ -110,36 +89,19 @@ namespace VEPROMS.CSLA.Library } return string.Empty; } - //private string Xp_LookInAncestorFolderInfo(object sender, XMLPropertiesArgs args) - //{ - // if (args.AncestorLookup || ParentLookup) - // { - - // DocVersionInfo docVersion = (DocVersionInfo)_Procedure.ActiveParent; - // string retval = docVersion.DocVersionConfig.GetValue(args.Group, args.Item); - // if (retval != string.Empty) return retval; - // for (FolderInfo folder = docVersion.MyFolder; folder != null; folder = folder.MyParent) - // { - // retval = folder.FolderConfig.GetValue(args.Group, args.Item); - // if (retval != string.Empty) return retval; - // } - // } - // return string.Empty; - //} public ProcedureConfig(ProcedureInfo procedureInfo) { _ProcedureInfo = procedureInfo; string xml = procedureInfo.MyContent.Config; - if (xml == string.Empty) - xml = ""; - _Xp = new XMLProperties(xml); + if (xml == string.Empty) + xml = ""; + _Xp = new XMLProperties(xml); // Fix Slaves nodes for Parent Child ValidateSlaves(_Xp.XmlContents, _ProcedureInfo.MyDocVersion.MultiUnitCount); _Xp.AncestorLookup = true; if (procedureInfo.ActiveParent != null) _Xp.LookInAncestor += new XMLPropertiesEvent(Xp_LookInAncestorFolder); } private int _SelectedSlave = 0; - //[Browsable(false)] public int SelectedSlave { get { return _SelectedSlave; } @@ -150,19 +112,9 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - //public ProcedureConfig() - //{ - // _Xp = new XMLProperties(); - //} - public string GetValue(string group, string item) - { - return _Xp[group, item]; - } - public void SetValue(string group, string item, string newvalue) - { - _Xp[group, item] = newvalue; - } - public int GetItemId() + public string GetValue(string group, string item) => _Xp[group, item]; + public void SetValue(string group, string item, string newvalue) => _Xp[group, item] = newvalue; + public int GetItemId() { if (_Procedure != null) return _Procedure.ItemID; if (_ProcedureInfo != null) return _ProcedureInfo.ItemID; @@ -193,19 +145,16 @@ namespace VEPROMS.CSLA.Library [Description("Old Sequence")] public string OldSequence { - get { return (_Procedure != null ? _Procedure.MyContent.MyZContent.OldStepSequence : (_ProcedureInfo.MyContent.MyZContent == null ? null : _ProcedureInfo.MyContent.MyZContent.OldStepSequence)); } + get { return (_Procedure != null ? _Procedure.MyContent.MyZContent.OldStepSequence : (_ProcedureInfo.MyContent.MyZContent?.OldStepSequence)); } set { if (_Procedure != null) _Procedure.MyContent.MyZContent.OldStepSequence = value; } } - [Category("Identification")] - //PROPGRID: Hide Dirty - [Browsable(false)] - [DisplayName("Dirty")] - [Description("Dirty")] - public bool Dirty - { - get { return (_Procedure != null ? _Procedure.IsDirty : false); } - } - [Category("Format Settings")] + [Category("Identification")] + //PROPGRID: Hide Dirty + [Browsable(false)] + [DisplayName("Dirty")] + [Description("Dirty")] + public bool Dirty => _Procedure != null && _Procedure.IsDirty; + [Category("Format Settings")] [DisplayName("Format")] [Description("Format")] [TypeConverter(typeof(FormatList))] @@ -222,7 +171,6 @@ namespace VEPROMS.CSLA.Library if (_Procedure != null) { _Procedure.MyContent.MyFormat = FormatList.ToFormat(value); // Can only be set if _DocVersion is set - //_Procedure.ActiveFormat = null; } } } @@ -261,12 +209,11 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - #region DelProcReason - [Category("General")] + return s == "" || s == "" ? string.Empty : s; + } + #endregion + #region DelProcReason + [Category("General")] [DisplayName("DelProcReason")] [RefreshProperties(RefreshProperties.All)] [Description("Delete Procedure Reason")] @@ -283,19 +230,6 @@ namespace VEPROMS.CSLA.Library } #endregion #region FormatCategory - //[TypeConverter(typeof(EnumDescConverter))] - //public enum FormatColumns : int - //{ - // Default = 0, - // [Description("Single Column")] - // OneColumn, - // [Description("Dual Column")] - // TwoColumn, - // [Description("Triple Column")] - // ThreeColumn, - // [Description("Quad Column")] - // FourColumns - //} [Category("General")] [DisplayName("Default Column Mode")] [RefreshProperties(RefreshProperties.All)] @@ -375,13 +309,13 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Procedure", "Rev"]; if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Rev"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "Rev"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "Rev"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "Rev"] = value; // save selected value else _Xp["Procedure", "Rev"] = value; OnPropertyChanged("Print_Rev"); @@ -399,13 +333,13 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Procedure", "RevDate"]; if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "RevDate"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "RevDate"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "RevDate"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "RevDate"] = value; // save selected value else _Xp["Procedure", "RevDate"] = value; OnPropertyChanged("Print_RevDate"); @@ -443,7 +377,7 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Procedure", "ChangeBarDate"]; if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ChangeBarDate"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "ChangeBarDate"]; else { if (s != "") @@ -470,7 +404,7 @@ namespace VEPROMS.CSLA.Library set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ChangeBarDate"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "ChangeBarDate"] = value; // save selected value else _Xp["Procedure", "ChangeBarDate"] = value; OnPropertyChanged("Print_ChangeBarDate"); @@ -487,13 +421,13 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Procedure", "ReviewDate"]; if (SelectedSlave > 0) - s = _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ReviewDate"]; + s = _Xp[$"Slave[@index='{SelectedSlave}']", "ReviewDate"]; return s; } set { if (SelectedSlave > 0) - _Xp["Slave[@index='" + SelectedSlave.ToString() + "']", "ReviewDate"] = value; // save selected value + _Xp[$"Slave[@index='{SelectedSlave}']", "ReviewDate"] = value; // save selected value else _Xp["Procedure", "ReviewDate"] = value; OnPropertyChanged("Print_ReviewDate"); @@ -519,12 +453,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_NumCopies"); } } - //public enum PrintPagination : int - //{ - // Free = 0, Fixed, - // [Description("Automatic")] - // Auto - //} [Category("Print Settings")] [DisplayName("Pagination")] [RefreshProperties(RefreshProperties.All)] @@ -562,13 +490,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_Pagination"); } } - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintWatermark : int - //{ - // None = 0, Reference, Draft, Master, Sample, - // [Description("Information Only")] - // InformationOnly - //} [Category("Print Settings")] [DisplayName("Watermark")] [RefreshProperties(RefreshProperties.All)] @@ -623,29 +544,12 @@ namespace VEPROMS.CSLA.Library set { string s = _Xp["PrintSettings", "NotInMergeAll"]; // get the original value to see if a change - bool original = (s==string.Empty) ? false : bool.Parse(s); + bool original = s != string.Empty && bool.Parse(s); if (original == value) return; _Xp["PrintSettings", "NotInMergeAll"] = ((bool)value).ToString(); // save selected value OnPropertyChanged("Print_NotInMergeAll"); } } - // Change Bar Use from 16-bit code: - // No Default - // Without Change Bars - // With Default Change Bars - // With User Specified Change Bars - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBar : int - //{ - // [Description("Select Before Printing")] - // SelectBeforePrinting = 0, - // [Description("Without Change Bars")] - // Without, - // [Description("With Default Change Bars")] - // WithDefault, - // [Description("Use Custom Change Bars")] - // WithUserSpecified - //} [Category("Format Settings")] [DisplayName("Change Bar")] [RefreshProperties(RefreshProperties.All)] @@ -683,23 +587,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_ChangeBar"); } } - // User Specified Change Bar Location from16-bit code: - // With Text - // Outside Box - // AER on LEFT, RNO on Right - // To the Left of Text - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBarLoc : int - //{ - // [Description("With Text")] - // WithText = 0, - // [Description("Outside Box")] - // OutsideBox, - // [Description("AER on Left RNO on Right")] - // AERleftRNOright, - // [Description("To the Left of the Text")] - // LeftOfText - //} [Category("Format Settings")] [DisplayName("Change Bar Position")] [RefreshProperties(RefreshProperties.All)] @@ -737,27 +624,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Print_ChangeBarLoc"); } } - - // Change Bar Text from16-bit code: - // Date and Change ID - // Revision Number - // Change ID - // No Change Bar Message - // User Defined Message - //[TypeConverter(typeof(EnumDescConverter))] - //public enum PrintChangeBarText : int - //{ - // [Description("Date and Change ID")] - // DateChgID = 0, - // [Description("Revision Number")] - // RevNum, - // [Description("Change ID")] - // ChgID, - // [Description("No Change Bar Text")] - // None, - // [Description("Custom Change Bar Text")] - // UserDef - //} [Category("Format Settings")] [DisplayName("Change Bar Text Type")] [RefreshProperties(RefreshProperties.All)] diff --git a/PROMS/VEPROMS.CSLA.Library/Config/RODbConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/RODbConfig.cs index 1a57e980..7439ad9b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/RODbConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/RODbConfig.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using System.Drawing; using System.IO; -using DescriptiveEnum; namespace VEPROMS.CSLA.Library { @@ -12,21 +8,14 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class RODbConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _RODb == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _RODb == null; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors - private RODb _RODb; + private readonly RODb _RODb; public RODbConfig(RODb roDb) { _RODb = roDb; @@ -34,7 +23,7 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - private RODbInfo _RODbInfo; + private readonly RODbInfo _RODbInfo; public RODbConfig(RODbInfo roDbInfo) { _RODbInfo = roDbInfo; @@ -52,13 +41,10 @@ namespace VEPROMS.CSLA.Library string xml = ""; _Xp = new XMLProperties(xml); } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Local Properties - [Category("General")] + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Local Properties + [Category("General")] [DisplayName("ROName")] [Description("ROName")] public string ROName @@ -71,22 +57,20 @@ namespace VEPROMS.CSLA.Library [Description("FolderPath")] public string FolderPath { - get { return (_RODb != null ? _RODb.FolderPath : _RODbInfo != null?_RODbInfo.FolderPath:null); } + get { return (_RODb != null ? _RODb.FolderPath : _RODbInfo?.FolderPath); } set { if (_RODb != null) _RODb.FolderPath = value; } } - public RODb MyRODb - { get { return _RODb; } } - #endregion - #region ToString - public override string ToString() + public RODb MyRODb => _RODb; + #endregion + #region ToString + public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - #region RODefaults - [Category("Referenced Objects")] + return s == "" || s == "" ? string.Empty : s; + } + #endregion + #region RODefaults + [Category("Referenced Objects")] [DisplayName("Graphic File Extension")] [RefreshProperties(RefreshProperties.All)] [Description("Default File Extension")] @@ -98,38 +82,41 @@ namespace VEPROMS.CSLA.Library // look in roapp.ini in the FolderPath directory; // look in top folder's config // set to Volian default, i.e. "TIF". - string s = GetRoAppIniValue("ROAPP", "Extention"); + string s = GetRoAppIniValue("Extention"); if (s == null || s == string.Empty) - s = TopFolderConfigValue("Graphics", "defaultext"); + s = TopFolderConfigValue(); if (s == null || s == string.Empty) return s = "TIF"; return s; } } - private string GetRoAppIniValue(string p, string p_2) - { - if (FolderPath == null) return null; - string inipath = FolderPath + @"\roapp.ini"; - if (!File.Exists(inipath)) return null; - StreamReader myReader = new StreamReader(inipath); - string sLine; - int indx = -1; - while ((sLine = myReader.ReadLine()) != null) - { - if (sLine.Length > 0 && sLine.Substring(0, 1) != ";") - { - if ((indx = sLine.ToLower().IndexOf(p_2.ToLower())) >= 0) - { - indx = sLine.IndexOf("=", indx + 9); - return sLine.Substring(indx + 1, sLine.Length - indx - 1).Trim(); - } - } - } - myReader.Close(); - return null; - } - private string TopFolderConfigValue(string p, string p_2) + private string GetRoAppIniValue(string p_2) + { + if (FolderPath == null) return null; + string inipath = FolderPath + @"\roapp.ini"; + if (!File.Exists(inipath)) return null; + using (StreamReader myReader = new StreamReader(inipath)) + { + string sLine; + int indx = -1; + while ((sLine = myReader.ReadLine()) != null) + { + if (sLine.Length > 0 && sLine.Substring(0, 1) != ";") + { + if ((indx = sLine.ToLower().IndexOf(p_2.ToLower())) >= 0) + { + indx = sLine.IndexOf("=", indx + 9); + return sLine.Substring(indx + 1, sLine.Length - indx - 1).Trim(); + } + } + } + myReader.Close(); + } + + return null; + } + private string TopFolderConfigValue() { FolderInfo fi = FolderInfo.GetTop(); return fi.FolderConfig.Graphics_defaultext; @@ -145,9 +132,9 @@ namespace VEPROMS.CSLA.Library } public string GetDefaultGraphicExtensionLocation() { - string s = GetRoAppIniValue("ROAPP", "Extention"); + string s = GetRoAppIniValue("Extention"); if (s != null && s != string.Empty) return "Default Extension found in roapp.ini"; - s = TopFolderConfigValue("Graphics", "defaultext"); + s = TopFolderConfigValue(); if (s != null && s != string.Empty) return "Default Extension defined in veproms properties"; return "Used program default"; } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs b/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs index fe72f0f8..663c84f3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ROFSTLookup.cs @@ -159,16 +159,13 @@ namespace VEPROMS.CSLA.Library private int _totalRoCnt = 0; private double _pctComplete = 0; - #endregion + #endregion - #region Properties + #region Properties - public int RofstID - { - get { return _rofstID; } - } + public int RofstID => _rofstID; - public DocVersionInfo MyDocVersionInfo + public DocVersionInfo MyDocVersionInfo { get { return _myDocVersionInfo; } set @@ -178,14 +175,11 @@ namespace VEPROMS.CSLA.Library } } - // C2021-065 see if we need to get the RO information for the "Other" Child applicability value - public int SelectedSlave - { - get { return (!string.IsNullOrEmpty(_otherChild)) ? Convert.ToInt32(_otherChild) : _selectedSlave; } - } + // C2021-065 see if we need to get the RO information for the "Other" Child applicability value + public int SelectedSlave => (!string.IsNullOrEmpty(_otherChild)) ? Convert.ToInt32(_otherChild) : _selectedSlave; - //C2021-065 used by Barakah Alarms so that we get ROLookUp for the Other applicability - public string OtherChild + //C2021-065 used by Barakah Alarms so that we get ROLookUp for the Other applicability + public string OtherChild { get { return _otherChild; } set { _otherChild = value; } @@ -237,16 +231,13 @@ namespace VEPROMS.CSLA.Library set { _autoCombineSingleRetValues = value; } } - public bool ShowLoadingStatus - { - get { return _showLoadingStatus; } - } + public bool ShowLoadingStatus => _showLoadingStatus; - #endregion + #endregion - #region Constructors + #region Constructors - public ROFSTLookup(int rofstID, DocVersionInfo dvi, string otherChild, bool showLoadingStatus = true) + public ROFSTLookup(int rofstID, DocVersionInfo dvi, string otherChild, bool showLoadingStatus = true) { // Set Fields/Properties _rofstID = rofstID; @@ -321,31 +312,19 @@ namespace VEPROMS.CSLA.Library return RofstDataSearch(_rofstID, value, searchTypeID, onlyRoid16, maxNumRecords); } - public ROFSTLookup.rochild[] GetRoChildrenByID(int id, int dbiID, bool loadChildren = false, bool loadAllChildren = false) - { - return RofstDataGetChildrenByID(_rofstID, dbiID, id, loadChildren, loadAllChildren); - } + public ROFSTLookup.rochild[] GetRoChildrenByID(int id, int dbiID, bool loadChildren = false, bool loadAllChildren = false) => RofstDataGetChildrenByID(_rofstID, dbiID, id, loadChildren, loadAllChildren); - public ROFSTLookup.rochild[] GetRoChildrenByRoid(string roid, bool loadChildren = false, bool loadAllChildren = false) - { - return RofstDataGetChildrenByRoid(_rofstID, roid, loadChildren, loadAllChildren); - } + public ROFSTLookup.rochild[] GetRoChildrenByRoid(string roid, bool loadChildren = false, bool loadAllChildren = false) => RofstDataGetChildrenByRoid(_rofstID, roid, loadChildren, loadAllChildren); - public ROFSTLookup.rochild[] GetRoChildrenByType(E_ROValueType valueTypes, bool loadChildren = false, bool loadAllChildren = false) - { - return RofstDataGetRoChildrenByType(_rofstID, valueTypes, loadChildren, loadAllChildren); - } + public ROFSTLookup.rochild[] GetRoChildrenByType(E_ROValueType valueTypes, bool loadChildren = false, bool loadAllChildren = false) => RofstDataGetRoChildrenByType(_rofstID, valueTypes, loadChildren, loadAllChildren); - #endregion + #endregion - #region (RO Database Info) + #region (RO Database Info) - public int GetRODatabaseTitleIndex(string roid) - { - return Convert.ToInt32("0x" + roid.Substring(0, 4), 16); - } + public int GetRODatabaseTitleIndex(string roid) => Convert.ToInt32("0x" + roid.Substring(0, 4), 16); - public string GetRODatabaseTitle(int idx) + public string GetRODatabaseTitle(int idx) { ROFSTLookup.rodbi rd = RofstDataGetDatabaseByID(_rofstID, idx); return (!string.IsNullOrEmpty(rd.dbiTitle) ? rd.dbiTitle : "RO Database Title Not Found"); @@ -358,16 +337,13 @@ namespace VEPROMS.CSLA.Library return (rd.dbiID > 0) ? rd : RofstDataGetDatabaseByID(_rofstID, 1, loadChildren, loadAllChildren); } - public ROFSTLookup.rodbi[] GetRODatabaseList(bool loadChildren = false, bool loadAllChildren = false) - { - return RofstDataGetDatabases(_rofstID, loadChildren, loadAllChildren); - } + public ROFSTLookup.rodbi[] GetRODatabaseList(bool loadChildren = false, bool loadAllChildren = false) => RofstDataGetDatabases(_rofstID, loadChildren, loadAllChildren); - #endregion + #endregion - #region (RO Info By AccPageID) + #region (RO Info By AccPageID) - public string FormatAccPageKey(string accPageID) + public string FormatAccPageKey(string accPageID) { string accPageBase = string.Empty; string accPageExt = string.Empty; @@ -527,12 +503,9 @@ namespace VEPROMS.CSLA.Library return (!string.IsNullOrEmpty(retval)) ? retval.Replace("\r\n", @"\par ") : retval; } - public List GetValueDifferences(int originalRofstID, ref List delList) - { - return RofstDataGetValueDifferences(originalRofstID, _rofstID, ref delList); - } + public List GetValueDifferences(int originalRofstID, ref List delList) => RofstDataGetValueDifferences(originalRofstID, _rofstID, ref delList); - public List GetROTitleAndGroupPath(string roid, bool reportMissingROs, bool convertCaretToDelta) + public List GetROTitleAndGroupPath(string roid, bool reportMissingROs, bool convertCaretToDelta) { // Return the RO Title in a list of strings. The last item in the list is the actual RO title, // the items preceding it are the titles of the groups and sub-groups containing the RO @@ -616,26 +589,17 @@ namespace VEPROMS.CSLA.Library return sb.ToString(); } - #endregion + #endregion - #region (RO Info Helper Methods) + #region (RO Info Helper Methods) - public static byte[] GetRofstLookupBytes(int rofstID) - { - return RofstDataGetRofstLookupBytes(rofstID); - } + public static byte[] GetRofstLookupBytes(int rofstID) => RofstDataGetRofstLookupBytes(rofstID); - public static DateTime GetRoFSTdts(int rofstID) - { - return GetRofstDtsByID(rofstID); - } + public static DateTime GetRoFSTdts(int rofstID) => GetRofstDtsByID(rofstID); - public DateTime GetRoFSTdts() - { - return GetRoFSTdts(_rofstID); - } + public DateTime GetRoFSTdts() => GetRoFSTdts(_rofstID); - public bool HasChildren(ref ROFSTLookup.rochild child) + public bool HasChildren(ref ROFSTLookup.rochild child) { LoadChildren(ref child); return child.children.Any(); @@ -666,12 +630,9 @@ namespace VEPROMS.CSLA.Library db.children = GetRoChildrenByID(db.ID, db.dbiID, false); } - public static ROFSTLookup.rochild GetEmptyRoChild() - { - return new ROFSTLookup.rochild() { ID = -1, type = 0 }; - } + public static ROFSTLookup.rochild GetEmptyRoChild() => new ROFSTLookup.rochild() { ID = -1, type = 0 }; - public static string CalculateDuration(DateTime dtStart) + public static string CalculateDuration(DateTime dtStart) { string duration = string.Empty; @@ -1736,31 +1697,6 @@ namespace VEPROMS.CSLA.Library #region (Convert To Objects) - private ROFSTLookup.roHdr ConvertToRoHdrObject(SafeDataReader dr, bool loadChildren) - { - ROFSTLookup.roHdr rh = new ROFSTLookup.roHdr - { - hSize = (int)dr.GetValue("hSize"), - hYear = (int)dr.GetValue("hYear"), - hMonth = (byte)dr.GetValue("hMonth"), - hDay = (byte)dr.GetValue("hDay"), - hcYear = (int)dr.GetValue("hcYear"), - hcMonth = (byte)dr.GetValue("hcMonth"), - hcDay = (byte)dr.GetValue("hcDay"), - hcHour = (byte)dr.GetValue("hcHour"), - hcMin = (byte)dr.GetValue("hcMin"), - hcSec = (byte)dr.GetValue("hcSec"), - hcHund = (byte)dr.GetValue("hcHund") - }; - - if (loadChildren) - { - rh.myDbs = RofstDataGetDatabases(_rofstID); - } - - return rh; - } - private ROFSTLookup.rodbi ConvertToRodbiObject(SafeDataReader dr, bool loadChildren, bool loadAllChildren) { ROFSTLookup.rodbi rd = new ROFSTLookup.rodbi @@ -2202,12 +2138,9 @@ namespace VEPROMS.CSLA.Library return i; } - private int NextDelimiter(string delim, string str) - { - return (!string.IsNullOrEmpty(str)) ? str.IndexOfAny(delim.ToCharArray()) : -1; - } + private int NextDelimiter(string delim, string str) => (!string.IsNullOrEmpty(str)) ? str.IndexOfAny(delim.ToCharArray()) : -1; - private int MatchingBrace(string str) + private int MatchingBrace(string str) { int level = 1; int idx = 0; // the while will skip the first position (the first brace) @@ -2426,7 +2359,7 @@ namespace VEPROMS.CSLA.Library { if (match.Groups[2].Value != "1") // Other than "1", multiply it times 10 raised to a power { - sb.Append(match.Groups[2].Value + "x10"); + sb.Append($"{match.Groups[2].Value}x10"); } else // The number is simply 1 so it can be ignored and 10 can be raised to a power { @@ -2435,11 +2368,11 @@ namespace VEPROMS.CSLA.Library } else // A number with a decimal point { - sb.Append(match.Groups[2].Value + "." + match.Groups[3].Value + "x10"); + sb.Append($"{match.Groups[2].Value}.{match.Groups[3].Value}x10"); } // Add the exponent as superscript - return sb.ToString() + "\\up2 " + match.Groups[4].Value.Replace("-", @"\u8209?") + match.Groups[5].Value + "\\up0 "; + return $"{sb}\\up2 {match.Groups[4].Value.Replace("-", @"\u8209?")}{match.Groups[5].Value}\\up0 "; } #endregion diff --git a/PROMS/VEPROMS.CSLA.Library/Config/ROImageConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/ROImageConfig.cs index d55e0c8d..feef6ac3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/ROImageConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/ROImageConfig.cs @@ -7,21 +7,14 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class ROImageConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return _ROImageInfo == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => _ROImageInfo == null; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors - private ROImageInfo _ROImageInfo; + private readonly ROImageInfo _ROImageInfo; public ROImageConfig(ROImageInfo rOImageInfo) { _ROImageInfo = rOImageInfo; @@ -34,13 +27,10 @@ namespace VEPROMS.CSLA.Library string xml = ""; _Xp = new XMLProperties(xml); } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Local Properties - [Category("Image")] + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Local Properties + [Category("Image")] [Browsable(false)] [DisplayName("Size")] [RefreshProperties(RefreshProperties.All)] @@ -62,9 +52,8 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - } + return s == "" || s == "" ? string.Empty : s; + } + #endregion + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/RevisionConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/RevisionConfig.cs index 990a6ace..6b727a0b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/RevisionConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/RevisionConfig.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using System.Drawing; -using DescriptiveEnum; namespace VEPROMS.CSLA.Library { @@ -11,22 +7,15 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class RevisionConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return false; }//_Section == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => false; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors - private Revision _Revision; - private RevisionInfo _RevisionInfo; + private readonly Revision _Revision; + private readonly RevisionInfo _RevisionInfo; [Browsable(false)] public bool ParentLookup { @@ -52,18 +41,12 @@ namespace VEPROMS.CSLA.Library if (xml == string.Empty) xml = ""; _Xp = new XMLProperties(xml); } - public RevisionConfig() - { - _Xp = new XMLProperties(); - } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Properties and Methods - // This is needed for the Data Loader - [Category("History")] + public RevisionConfig() => _Xp = new XMLProperties(); + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Properties and Methods + // This is needed for the Data Loader + [Category("History")] [Browsable(false)] [DisplayName("Start Date")] [RefreshProperties(RefreshProperties.All)] @@ -115,9 +98,8 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - } + return s == "" || s == "" ? string.Empty : s; + } + #endregion + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Config/SectionConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/SectionConfig.cs index dc6fe4dc..d2b373af 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/SectionConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/SectionConfig.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.ComponentModel; using DescriptiveEnum; using System.Xml; @@ -11,18 +10,11 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class SectionConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged, IItemConfig { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return false; }//_Section == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => false; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors //PROPGRID: Hide ParentLookup @@ -32,26 +24,13 @@ namespace VEPROMS.CSLA.Library get { return _Xp.ParentLookup; } set { _Xp.ParentLookup = value; } } - //PROPGRID: Had to comment out NonSerialized to hide AncestorLookup from Property Grid - //[NonSerialized] - private bool _AncestorLookup; - //PROPGRID: Hide AncestorLookup - //[Browsable(false)] - //public bool AncestorLookup - //{ - // get { return _AncestorLookup; } - // set { _AncestorLookup = value; } - //} - private Section _Section; - private SectionInfo _SectionInfo; + private readonly Section _Section; + private readonly SectionInfo _SectionInfo; private static int _SectionConfigUnique = 0; - private static int SectionConfigUnique - { get { return ++_SectionConfigUnique; } } - private int _MySectionConfigUnique = SectionConfigUnique; - public int MySectionConfigUnique // Absolutely Unique ID - Info - { get { return _MySectionConfigUnique; } } + private static int SectionConfigUnique => ++_SectionConfigUnique; + private readonly int _MySectionConfigUnique = SectionConfigUnique; - public SectionConfig(Section section) + public SectionConfig(Section section) { _Section = section; string xml = section.MyContent.Config; @@ -82,9 +61,8 @@ namespace VEPROMS.CSLA.Library if (retval != string.Empty) return retval; proc = (ProcedureInfo)proc.ActiveParent; } - DocVersionInfo docVersion = proc.ActiveParent as DocVersionInfo; - if (docVersion == null) return string.Empty; - retval = docVersion.DocVersionConfig.GetValue(args.Group, args.Item); + if (!(proc.ActiveParent is DocVersionInfo docVersion)) return string.Empty; + retval = docVersion.DocVersionConfig.GetValue(args.Group, args.Item); if (retval != string.Empty) return retval; for (FolderInfo folder = docVersion.MyFolder; folder != null; folder = folder.MyParent) { @@ -102,23 +80,11 @@ namespace VEPROMS.CSLA.Library _Xp = new XMLProperties(xml); if (_SectionInfo.ActiveParent != null) _Xp.LookInAncestor += new XMLPropertiesEvent(Xp_LookInAncestorFolder); } - //public SectionConfig(string xml) - //{ - // if (xml == string.Empty) xml = ""; - // _Xp = new XMLProperties(xml); - //} - public SectionConfig() - { - _Xp = new XMLProperties(); - } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Local Properties - //[Category("Identification")] - [Category("General")] + public SectionConfig() => _Xp = new XMLProperties(); + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Local Properties + [Category("General")] [DisplayName("Number")] [Description("Number")] public string Number @@ -126,7 +92,6 @@ namespace VEPROMS.CSLA.Library get { return (_Section != null ? _Section.MyContent.Number : _SectionInfo.MyContent.Number); } set { if (_Section != null) _Section.MyContent.Number = value; } } - //[Category("Identification")] [Category("General")] [DisplayName("Title")] [Description("Title")] @@ -142,7 +107,7 @@ namespace VEPROMS.CSLA.Library [Description("Old Sequence")] public string OldSequence { - get { return (_Section != null ? _Section.MyContent.MyZContent.OldStepSequence : (_SectionInfo.MyContent.MyZContent == null ? null : _SectionInfo.MyContent.MyZContent.OldStepSequence)); } + get { return (_Section != null ? _Section.MyContent.MyZContent.OldStepSequence : (_SectionInfo.MyContent.MyZContent?.OldStepSequence)); } set { if (_Section != null) _Section.MyContent.MyZContent.OldStepSequence = value; } } [Category("Identification")] @@ -152,7 +117,7 @@ namespace VEPROMS.CSLA.Library [Description("Dirty")] public bool Dirty { - get { return (_Section != null ? _Section.IsDirty : false); } + get { return (_Section != null && _Section.IsDirty); } } [Category("Format")] [DisplayName("Format")] @@ -171,7 +136,6 @@ namespace VEPROMS.CSLA.Library if (_Section != null) { _Section.MyContent.MyFormat = FormatList.ToFormat(value); // Can only be set if _DocVersion is set - //_Section.ActiveFormat = null; DocStyleListConverter.MySection = _Section; } } @@ -192,7 +156,7 @@ namespace VEPROMS.CSLA.Library set { if (_Section != null) - _Section.MyContent.MyFormat = value == null ? null : value.GetJustFormat(); + _Section.MyContent.MyFormat = value?.GetJustFormat(); } } [Category("Format")] @@ -304,15 +268,13 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - #region SectionCategory // from sequence number in 16-bit database. - [TypeConverter(typeof(EnumDescConverter))] + return s == "" || s == "" ? string.Empty : s; + } + #endregion + #region SectionCategory // from sequence number in 16-bit database. + [TypeConverter(typeof(EnumDescConverter))] public enum SectionPagination : int { - //Default = 0, Continuous, Separate Continuous = 1, Separate = 2 } [Category("Format")] @@ -415,7 +377,7 @@ namespace VEPROMS.CSLA.Library get { string tmp = _Xp["Section", "TOC_Group_Title"]; - return (tmp == null)? "" : tmp; + return tmp ?? ""; } set { @@ -476,23 +438,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Section_DontIncludeDuplexFoldout"); } } - //[Category("Section")] - ////PROPGRID: Hide AutoGen - //[DisplayName("Section AutoGen")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Section AutoGen")] - //public string Section_AutoGen - //{ - // get - // { - // return _Xp["Section", "AutoGen"]; - // } - // set - // { - // _Xp["Section", "AutoGen"] = value; - // OnPropertyChanged("Section_AutoGen"); - // } - //} [Category("Section")] //PROPGRID: Hide Subsection PH [DisplayName("Section PrintHdr")] @@ -536,7 +481,6 @@ namespace VEPROMS.CSLA.Library { get { - //return _Xp["Section", "ShwRplWords"]; string tmp = _Xp["Section", "ShwRplWords"]; return tmp == null || tmp == "" ? "Y" : tmp; } @@ -568,8 +512,6 @@ namespace VEPROMS.CSLA.Library // C2020-046 change wording for the column modes to One, Two, Three, and Four public enum SectionColumnMode : int { - //[Description("Format Default")] - //Default = 0, [Description("One Column")] One = 1, [Description("Two Columns")] @@ -595,7 +537,7 @@ namespace VEPROMS.CSLA.Library // If there is no parent value, then use the volian default if (s == string.Empty) { - SectionInfo si = _SectionInfo != null ? _SectionInfo : SectionInfo.Get(_Section.ItemID); + SectionInfo si = _SectionInfo ?? SectionInfo.Get(_Section.ItemID); if (si != null) { E_PurchaseOptions po = (E_PurchaseOptions)(MyFormat ?? MyDefaultFormat).PlantFormat.FormatData.PurchaseOptions; @@ -607,34 +549,23 @@ namespace VEPROMS.CSLA.Library { case FormatColumns.OneColumn: return SectionColumnMode.One; - break; case FormatColumns.TwoColumn: return SectionColumnMode.Two; - break; case FormatColumns.ThreeColumn: return SectionColumnMode.Three; - break; case FormatColumns.FourColumns: return SectionColumnMode.Four; - break; - //default: - // return SectionColumnMode.One; - // break; } } } - int rval = 0; - if (MyFormat != null) + int rval; + if (MyFormat != null) { rval = (int)MyFormat.MyStepSectionLayoutData.PMode; - //int rval = (int)MyFormat.MyStepSectionLayoutData.PMode; - //return (SectionColumnMode)rval;//SectionColumnMode.Two; //SectionColumnMode.Default;// default to volian default } else { - //int rval = (int)MyDefaultFormat.MyStepSectionLayoutData.PMode; rval = (int)MyDefaultFormat.MyStepSectionLayoutData.PMode; - //return (SectionColumnMode)rval; } // if no pmode is defined, i.e. rval = 0, then go up to the procedure level & get // it's format column. @@ -646,11 +577,6 @@ namespace VEPROMS.CSLA.Library } else return (SectionColumnMode)int.Parse(s); - - //if (s == string.Empty) - // return SectionColumnMode.Default; - - //return (SectionColumnMode)int.Parse(s); } set { @@ -670,13 +596,12 @@ namespace VEPROMS.CSLA.Library } else rval =(int)MyFormat.MyStepSectionLayoutData.PMode; - //parval = ((rval > 0)?((SectionColumnMode)rval).ToString() : "2"); // if PMode is zero default to 2 column mode } // if still no value found in inheritance, check if the procedure has a default. if so and value matches, clear out any config item. if (rval == 0) { - SectionInfo si = _SectionInfo != null ? _SectionInfo : SectionInfo.Get(_Section.ItemID); + SectionInfo si = _SectionInfo ?? SectionInfo.Get(_Section.ItemID); if (si != null) { switch (si.MyProcedure.ProcedureConfig.Format_Columns) @@ -708,103 +633,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Section_ColumnMode"); } } -//char * far printtypes[] = { -// "Compressed, 8 lines per inch", -// "Elite, 6 lines per inch", -// "Pica, 6 lines per inch", -// "Default font, 4 Lines Per Inch", -// "Default font, 6 Lines Per Inch", -// "Compressed 6 LPI", -// "Default font, 7 Lines Per Inch", -// "Special Landscape, Elite, 6 lines per inch" -//}; - //[TypeConverter(typeof(EnumDescConverter))] - //public enum AttPrintSize : int - //{ - // [Description("Compressed, 8 lines per inch")] - // Cmp8lpi = 0, - // [Description("Elite, 6 lines per inch")] - // Elite6lpi = 1, - // [Description("Pica, 6 lines per inch")] - // Pica6lpi = 2, - // [Description("Default font, 4 Lines Per Inch")] - // Def4lpi = 3, - // [Description("Default font, 6 Lines Per Inch")] - // Def6lpi = 4, - // [Description("Compressed 6 LPI")] - // Cmp6lpi = 5, - // [Description("Default font, 7 Lines Per Inch")] - // Def7lpi = 6, - // [Description("Landscape, Elite, 6 lines per inch")] - // landElite6lpi = 7 - //} - - //[Category("Format")] - //[DisplayName("Attachment PrintSize")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Attachment Print Size")] - //public AttPrintSize Section_AttachmentPrintSize - //{ - // get - // { - // string lpiSettings = "*pP46f7L"; - // string s = _Xp["Section", "OldType"]; - // int idx = -1; - - // //If there is no value to get, then get the parent value (a.k.a. default value). - // if (s == string.Empty) - // s = _Xp.ParentValue("Section", "OldType"); // get the parent value - // // If there is no parent value, then use the volian default - // if (s == string.Empty) - // return AttPrintSize.Def6lpi;// default to volian default - - // idx = lpiSettings.IndexOf(s[1]); - // if (idx == -1) idx = 4; - // return (AttPrintSize)idx; - // //return (AttPrintSize)int.Parse(s); - // } - // set - // { - // // if value being saved is same as the parent value, then clear the value (save blank). This will - // // reset the data to use the parent value. - - // string lpiSettings = "*pP46f7L"; - // string parval = _Xp.ParentValue("Section", "OldType"); // get the parent value - // StringBuilder sb = new StringBuilder(); - // string curval = parval[1].ToString(); - - // sb.Append(parval[0]); // save first part of OldType - - // if (parval.Equals(string.Empty)) // if the parent value is empty, then use the volian default - // { - // //parval = ((int)(AttPrintSize.Def6lpi)).ToString(); - // //sb.Append(((int)(AttPrintSize.Def6lpi)).ToString()); - // sb.Append(lpiSettings[(int)(AttPrintSize.Def6lpi)]); - // } - - // if (curval.Equals(((int)value).ToString())) - // _Xp["Section", "OldType"] = string.Empty; // reset to parent value - // else - // { - // //sb.Append(((int)value).ToString()); - // sb.Append(lpiSettings[(int)value]); - // _Xp["Section", "OldType"] = sb.ToString(); // save selected value - // } - - // OnPropertyChanged("Section_AttachmentPrintSize"); - // } - //} - /* - int chkOffType = (rid[0] & 0x007F) - '0'; - if (chkOffType > 0) - ci.AddItem("Section", "CheckoffSelection", chkOffType.ToString()); - - if (stype.Length > 1) - { - int chkOffHeading = (stype[1] & 0x007F) - '0'; - if (chkOffHeading > 0) - ci.AddItem("Section", "CheckoffHeading", chkOffHeading.ToString()); - */ [Category("Format")] [DisplayName("Checkoff List Selection")] [Description("Checkoff List Selection")] @@ -874,13 +702,10 @@ namespace VEPROMS.CSLA.Library { get { - //if (_SectionInfo != null && _SectionInfo.Sections != null && _SectionInfo.Sections.Count > 0 && _SectionInfo.Steps != null && _SectionInfo.Steps.Count > 0) if (_SectionInfo != null && _SectionInfo.Sections != null && _SectionInfo.Sections.Count > 0) return "N"; if (_Section != null && HasSubsections) return "N"; - //if (_Section != null && _Section.MyContent.cont .Sections.Count > 0 && _Section.Steps.Count > 0) - // return "N"; return "Y"; } } @@ -1013,8 +838,6 @@ namespace VEPROMS.CSLA.Library { if (MyEnhancedDocuments == null || MyEnhancedDocuments.Count == 0) // clear out the xml node { - //XmlNode dd = _Xp.XmlContents.SelectSingleNode("//Slave[@index='" + index.ToString() + "']"); - //dd.ParentNode.RemoveChild(dd); List nodesToDel = new List(); foreach (XmlNode xnr in _Xp.XmlContents.SelectNodes("//Enhanced")) nodesToDel.Add(xnr); if (nodesToDel != null) diff --git a/PROMS/VEPROMS.CSLA.Library/Config/StepConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/StepConfig.cs index 692a8db3..42463e89 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/StepConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/StepConfig.cs @@ -1,19 +1,14 @@ using System; using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using DescriptiveEnum; using System.Xml; namespace VEPROMS.CSLA.Library { public partial class EnhancedDocuments : List { - public void Add(int type, int itemID) - { - Add(new EnhancedDocument(type, itemID)); - } - public static EnhancedDocuments Load(XMLProperties _Xp) + public void Add(int type, int itemID) => Add(new EnhancedDocument(type, itemID)); + public static EnhancedDocuments Load(XMLProperties _Xp) { EnhancedDocuments ed = new EnhancedDocuments(); foreach (XmlNode xn in _Xp.XmlContents.SelectNodes("//Enhanced")) @@ -31,45 +26,25 @@ namespace VEPROMS.CSLA.Library } public partial class EnhancedDocument { - private int _Type; - public int Type - { - get { return _Type; } - set { _Type = value; } - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - public EnhancedDocument() { ;} + public int Type { get; set; } + public int ItemID { get; set; } + public EnhancedDocument() { ;} public EnhancedDocument(int type, int itemID) { Type = type; ItemID = itemID; } - public override string ToString() - { - return string.Format("{0}.ItemID={1}", Type, ItemID); - } - } + public override string ToString() => $"{Type}.ItemID={ItemID}"; + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class StepConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged, IItemConfig { - #region DynamicTypeDescriptor - internal override bool IsReadOnly - { - get { return false; }//_Section == null; } - } - #endregion - #region XML - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + #region DynamicTypeDescriptor + internal override bool IsReadOnly => false; + #endregion + #region XML + private readonly XMLProperties _Xp; #endregion #region Constructors //PROPGRID: Hide ParentLookup @@ -79,18 +54,8 @@ namespace VEPROMS.CSLA.Library get { return _Xp.ParentLookup; } set { _Xp.ParentLookup = value; } } - //PROPGRID: Had to comment out NonSerialized to hide AncestorLookup from Property Grid - //[NonSerialized] - //private bool _AncestorLookup; - ////PROPGRID: Hide AncestorLookup - //[Browsable(false)] - //public bool AncestorLookup - //{ - // get { return _AncestorLookup; } - // set { _AncestorLookup = value; } - //} - private Step _Step; - private StepInfo _StepInfo; + private readonly Step _Step; + private readonly StepInfo _StepInfo; public StepConfig(Step step) { _Step = step; @@ -111,47 +76,36 @@ namespace VEPROMS.CSLA.Library _Xp = new XMLProperties(xml); } - public StepConfig() - { - _Xp = new XMLProperties(); - } - internal string GetValue(string group, string item) - { - return _Xp[group, item]; - } - #endregion - #region Local Properties - - #endregion - #region ToString - public override string ToString() + public StepConfig() => _Xp = new XMLProperties(); + internal string GetValue(string group, string item) => _Xp[group, item]; + #endregion + #region Local Properties + + #endregion + #region ToString + public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; - } - #endregion - #region StepAttr - //[Category("Step Attributes")] - //[DisplayName("Step Floating Foldout Association")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Step Floating Foldout Association")] - public int Step_FloatingFoldout + return s == "" || s == "" ? string.Empty : s; + } + #endregion + #region StepAttr + public int Step_FloatingFoldout { get { string s = _Xp["Step", "FloatingFoldout"]; if (s == string.Empty) return 0; - int tst = 0; - try + int tst; + try { tst = int.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0; } - return int.Parse(s); + return tst; } set { @@ -196,28 +150,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Step_TCAS"); } } - //// Alternate text to use on the Continuous Action Summary - //public string Step_AlternateContActSumText - //{ - // get - // { - // string s = _Xp["Step", "AlternateContActSumText"]; - // //If there is no value to get, then we use the actual step text - // if (s == string.Empty) return null; - // return s; - // } - // set - // { - // string s = _Xp["Step", "AlternateContActSumText"]; - // if (value == s) return; - // _Xp["Step", "AlternateContActSumText"] = value; - // OnPropertyChanged("Step_AlternateContActSumText"); - // } - //} - //[Category("Step Attributes")] - //[DisplayName("Step Placekeeper")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Step Placekeeper")] public string Step_Placekeeper { get @@ -236,10 +168,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Step_Placekeeper"); } } - //[Category("Step Attributes")] - //[DisplayName("Step Check Off Index")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Step Check Off Index")] public int Step_CheckOffIndex { get @@ -248,24 +176,14 @@ namespace VEPROMS.CSLA.Library if (s == string.Empty) return 0; - // there was an invalid character for Wolf Creek's index. just return - // a 0 if found. The dataloader was fixed (6/8/12) to not migrate the - // bad character, but this was added, in case there are some other conditions. - int tst = 0; - if(int.TryParse(s,out tst)) - return tst; - tst = (int) s[0]; + // there was an invalid character for Wolf Creek's index. just return + // a 0 if found. The dataloader was fixed (6/8/12) to not migrate the + // bad character, but this was added, in case there are some other conditions. + if (int.TryParse(s, out int tst)) + return tst; + tst = (int) s[0]; tst -= '0'; return tst; - //try - //{ - // tst = int.Parse(s); - //} - //catch (Exception ex) - //{ - // return 0; - //} - //return int.Parse(s); } set { @@ -275,10 +193,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Step_CheckOffIndex"); } } - //[Category("Step Attributes")] - //[DisplayName("Step Manual Pagebreak")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Step Manual Pagebreak")] public bool Step_ManualPagebreak { get @@ -352,10 +266,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Step_SubStepPagebreak"); } } - //[Category("Step Attributes")] - //[DisplayName("Step Change Bar Override")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Step Change Bar Override")] public string Step_CBOverride { get @@ -440,10 +350,6 @@ namespace VEPROMS.CSLA.Library OnPropertyChanged("Step_Responsibility"); } } - //[Category("Step Attributes")] - //[DisplayName("Step Change By Spell Checker")] - //[RefreshProperties(RefreshProperties.All)] - //[Description("Step Change By Spell Checker")] // When the spell checker changes text do not assign a change bar but keep existing change bar if it is there public string Step_SpellCheckerChangedText { @@ -557,16 +463,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Step", "ImageWidth"]; if (s == string.Empty) return 0; - int tst = 0; - try + int tst; + try { tst = int.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0; } - return int.Parse(s); + return tst; } set { @@ -582,16 +488,16 @@ namespace VEPROMS.CSLA.Library { string s = _Xp["Step", "ImageHeight"]; if (s == string.Empty) return 0; - int tst = 0; - try + int tst; + try { tst = int.Parse(s); } - catch (Exception ex) - { + catch (Exception) + { return 0; } - return int.Parse(s); + return tst; } set { @@ -617,7 +523,6 @@ namespace VEPROMS.CSLA.Library set { _MyEnhancedDocuments = value; - //OnPropertyChanged("EnhancedDocuments"); } } public void AddEnhancedDocument(int type, int itemid) @@ -637,7 +542,6 @@ namespace VEPROMS.CSLA.Library // so that what remains are those that need added to xml that will then be written to database foreach (XmlNode xn in _Xp.XmlContents.SelectNodes("//Enhanced")) { - //EnhancedDocument tmp = edsToAdd[int.Parse(xn.Attributes["Type"].Value)]; EnhancedDocument tmp = edsToAdd.GetByType(int.Parse(xn.Attributes["Type"].Value)); if (tmp != null) { @@ -659,74 +563,6 @@ namespace VEPROMS.CSLA.Library xa.Value = edadd.ItemID.ToString(); } } - //public string Step_SourceToBackground - //{ - // get - // { - // string s = _Xp["Step", "SourceToBackground"]; - // if (s == string.Empty) return null; - // return s; - // } - // set - // { - // string s = _Xp["Step", "SourceToBackground"]; - // if (value != null && value.ToString() == s) return; - // if (value == null && s != null) _Xp["Step", "SourceToBackground"] = null; - // else _Xp["Step", "SourceToBackground"] = value.ToString(); - // OnPropertyChanged("Step_SourceToBackground"); - // } - //} - //public string Step_BackgroundToSource - //{ - // get - // { - // string s = _Xp["Step", "BackgroundToSource"]; - // if (s == string.Empty) return null; - // return s; - // } - // set - // { - // string s = _Xp["Step", "BackgroundToSource"]; - // if (value != null && value.ToString() == s) return; - // if (value == null && s != null) _Xp["Step", "BackgroundToSource"] = null; - // else _Xp["Step", "BackgroundToSource"] = value.ToString(); - // OnPropertyChanged("Step_BackgroundToSource"); - // } - //} - //public string Step_SourceToDeviation - //{ - // get - // { - // string s = _Xp["Step", "SourceToDeviation"]; - // if (s == string.Empty) return null; - // return s; - // } - // set - // { - // string s = _Xp["Step", "SourceToDeviation"]; - // if (value != null && value.ToString() == s) return; - // if (value == null && s != null) _Xp["Step", "SourceToDeviation"] = null; - // else _Xp["Step", "SourceToDeviation"] = value.ToString(); - // OnPropertyChanged("Step_SourceToDeviation"); - // } - //} - //public string Step_DeviationToSource - //{ - // get - // { - // string s = _Xp["Step", "DeviationToSource"]; - // if (s == string.Empty) return null; - // return s; - // } - // set - // { - // string s = _Xp["Step", "DeviationToSource"]; - // if (value != null && value.ToString() == s) return; - // if (value == null && s != null) _Xp["Step", "DeviationToSource"] = null; - // else _Xp["Step", "DeviationToSource"] = value.ToString(); - // OnPropertyChanged("Step_DeviationToSource"); - // } - //} #endregion #region IItemConfig Members diff --git a/PROMS/VEPROMS.CSLA.Library/Config/TransitionConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/TransitionConfig.cs index 21ca181d..311e3aed 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/TransitionConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/TransitionConfig.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace VEPROMS.CSLA.Library @@ -9,11 +7,7 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class TransitionConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + private readonly XMLProperties _Xp; public TransitionConfig(string xml) { if (xml == string.Empty) xml = ""; @@ -38,8 +32,7 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; + return s == "" || s == "" ? string.Empty : s; } #region GeneralTransitionProperties [Category("Formatted")] // format transition, i.e. include page number diff --git a/PROMS/VEPROMS.CSLA.Library/Config/UserConfig.cs b/PROMS/VEPROMS.CSLA.Library/Config/UserConfig.cs index fe26018d..a5f3a198 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/UserConfig.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/UserConfig.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace VEPROMS.CSLA.Library @@ -9,11 +7,7 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class UserConfig : ConfigDynamicTypeDescriptor, INotifyPropertyChanged { - private XMLProperties _Xp; - private XMLProperties Xp - { - get { return _Xp; } - } + private readonly XMLProperties _Xp; public UserConfig(string xml) { if (xml == string.Empty) xml = ""; @@ -26,8 +20,7 @@ namespace VEPROMS.CSLA.Library public override string ToString() { string s = _Xp.ToString(); - if (s == "" || s == "") return string.Empty; - return s; + return s == "" || s == "" ? string.Empty : s; } #region UserCategory // from user.cfg [Category("User")] diff --git a/PROMS/VEPROMS.CSLA.Library/Config/XMLProperties.cs b/PROMS/VEPROMS.CSLA.Library/Config/XMLProperties.cs index 20107c58..5efa89d8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Config/XMLProperties.cs +++ b/PROMS/VEPROMS.CSLA.Library/Config/XMLProperties.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Runtime.Serialization; using System.Xml; @@ -47,12 +45,9 @@ namespace VEPROMS.CSLA.Library set { _ParentLookup = value; } } [NonSerialized] - XmlDocument _XmlContents; - public XmlDocument XmlContents - { - get { return _XmlContents; } - } - private XmlNode GetGroup(string group) + readonly XmlDocument _XmlContents; + public XmlDocument XmlContents => _XmlContents; + private XmlNode GetGroup(string group) { XmlNodeList xl = _XmlContents.DocumentElement.SelectNodes(string.Format("//{0}", group)); if(xl.Count == 0 && System.Text.RegularExpressions.Regex.IsMatch(group,"^[A-Za-z0-9]+$")) @@ -72,7 +67,6 @@ namespace VEPROMS.CSLA.Library } private XmlAttribute GetItem(XmlNode xx, string item) { - //XmlNodeList xl = xx.SelectNodes(string.Format("@{0}", item)); XmlNodeList xl = xx.SelectNodes( string.Format("@*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='{0}']", item.ToLower())); switch (xl.Count) @@ -87,11 +81,8 @@ namespace VEPROMS.CSLA.Library throw new XmlPropertiesException("Found more than one node @{0}", item); } } - public string ParentValue(string group, string item) - { - return OnLookInAncestor(this, new XMLPropertiesArgs(group, item, true)); - } - public string this[string group, string item] + public string ParentValue(string group, string item) => OnLookInAncestor(this, new XMLPropertiesArgs(group, item, true)); + public string this[string group, string item] { get { @@ -162,41 +153,26 @@ namespace VEPROMS.CSLA.Library } public partial class XMLPropertiesArgs { - #region Business Methods - private string _Group; - public string Group - { - get { return _Group; } - set { _Group = value; } - } - private string _Item; - public string Item - { - get { return _Item; } - set { _Item = value; } - } - private bool _AncestorLookup; + #region Business Methods + public string Group { get; set; } + public string Item { get; set; } - public bool AncestorLookup - { - get { return _AncestorLookup; } - set { _AncestorLookup = value; } - } + public bool AncestorLookup { get; set; } - #endregion - #region Factory Methods - private XMLPropertiesArgs() { ;} + #endregion + #region Factory Methods + private XMLPropertiesArgs() { ;} public XMLPropertiesArgs(string group, string item) { - _Group=group; - _Item=item; - _AncestorLookup = false; + Group=group; + Item=item; + AncestorLookup = false; } public XMLPropertiesArgs(string group, string item, bool ancestorLookup) { - _Group = group; - _Item = item; - _AncestorLookup = ancestorLookup; + Group = group; + Item = item; + AncestorLookup = ancestorLookup; } #endregion } diff --git a/PROMS/VEPROMS.CSLA.Library/EnumExtensions.cs b/PROMS/VEPROMS.CSLA.Library/EnumExtensions.cs index 3a1cb378..dfcbeaa7 100644 --- a/PROMS/VEPROMS.CSLA.Library/EnumExtensions.cs +++ b/PROMS/VEPROMS.CSLA.Library/EnumExtensions.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace VEPROMS.CSLA.Library { diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/AdminToolsExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/AdminToolsExt.cs index 4f67e8b7..39743d80 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/AdminToolsExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/AdminToolsExt.cs @@ -5,31 +5,22 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using Csla.Validation; namespace VEPROMS.CSLA.Library { public class ESP_FixHyphens : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int AffectedRows { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _AffectedRows; - public int AffectedRows - { - get { return _AffectedRows; } - set { _AffectedRows = value; } - } - public static int Execute(string storedProcedure) - { - ESP_DeletePDFs cmd = new ESP_DeletePDFs(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_DeletePDFs cmd = new ESP_DeletePDFs + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.AffectedRows; } #endregion @@ -59,24 +50,16 @@ namespace VEPROMS.CSLA.Library public class ESP_DeletePDFs : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int AffectedRows { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _AffectedRows; - public int AffectedRows - { - get { return _AffectedRows; } - set { _AffectedRows = value; } - } - public static int Execute(string storedProcedure) - { - ESP_DeletePDFs cmd = new ESP_DeletePDFs(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_DeletePDFs cmd = new ESP_DeletePDFs + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.AffectedRows; } #endregion @@ -106,24 +89,16 @@ namespace VEPROMS.CSLA.Library public class ESP_IdentifyDisconnectedItems : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_IdentifyDisconnectedItems cmd = new ESP_IdentifyDisconnectedItems(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_IdentifyDisconnectedItems cmd = new ESP_IdentifyDisconnectedItems + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -157,24 +132,16 @@ namespace VEPROMS.CSLA.Library public class ESP_PurgeDisconnectedItems : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_PurgeDisconnectedItems cmd = new ESP_PurgeDisconnectedItems(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_PurgeDisconnectedItems cmd = new ESP_PurgeDisconnectedItems + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -206,24 +173,16 @@ namespace VEPROMS.CSLA.Library public class ESP_GetROAssoc : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_GetROAssoc cmd = new ESP_GetROAssoc(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_GetROAssoc cmd = new ESP_GetROAssoc + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -257,24 +216,16 @@ namespace VEPROMS.CSLA.Library public class ESP_CleanupROAssoc : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_CleanupROAssoc cmd = new ESP_CleanupROAssoc(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_CleanupROAssoc cmd = new ESP_CleanupROAssoc + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -307,24 +258,16 @@ namespace VEPROMS.CSLA.Library public class ESP_GetUnusedRoFsts : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_GetUnusedRoFsts cmd = new ESP_GetUnusedRoFsts(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_GetUnusedRoFsts cmd = new ESP_GetUnusedRoFsts + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -358,24 +301,16 @@ namespace VEPROMS.CSLA.Library public class ESP_GetUnusedFigures : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_GetUnusedFigures cmd = new ESP_GetUnusedFigures(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_GetUnusedFigures cmd = new ESP_GetUnusedFigures + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -409,24 +344,16 @@ namespace VEPROMS.CSLA.Library public class ESP_PurgeUnusedRoFstsAndFigures : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public int RowCount { get; set; } + public static int Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private int _RowCount; - public int RowCount - { - get { return _RowCount; } - set { _RowCount = value; } - } - public static int Execute(string storedProcedure) - { - ESP_PurgeUnusedRoFstsAndFigures cmd = new ESP_PurgeUnusedRoFstsAndFigures(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_PurgeUnusedRoFstsAndFigures cmd = new ESP_PurgeUnusedRoFstsAndFigures + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.RowCount; } #endregion @@ -458,24 +385,16 @@ namespace VEPROMS.CSLA.Library public class ESP_IdentifyNonEditableItems : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public List ItemInfoList { get; set; } = new List(); + public static List Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private List _ItemInfoList = new List(); - public List ItemInfoList - { - get { return _ItemInfoList; } - set { _ItemInfoList = value; } - } - public static List Execute(string storedProcedure) - { - ESP_IdentifyNonEditableItems cmd = new ESP_IdentifyNonEditableItems(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_IdentifyNonEditableItems cmd = new ESP_IdentifyNonEditableItems + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.ItemInfoList; } #endregion @@ -508,24 +427,16 @@ namespace VEPROMS.CSLA.Library public class ESP_GetDatabaseSessions : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - private string _StoredProcedure; - public string StoredProcedure + #region Factory Methods + public string StoredProcedure { get; set; } + public string ResultsString { get; set; } + public static string Execute(string storedProcedure) { - get { return _StoredProcedure; } - set { _StoredProcedure = value; } - } - private string _ResultsString; - public string ResultsString - { - get { return _ResultsString; } - set { _ResultsString = value; } - } - public static string Execute(string storedProcedure) - { - ESP_GetDatabaseSessions cmd = new ESP_GetDatabaseSessions(); - cmd.StoredProcedure = storedProcedure; - DataPortal.Execute(cmd); + ESP_GetDatabaseSessions cmd = new ESP_GetDatabaseSessions + { + StoredProcedure = storedProcedure + }; + DataPortal.Execute(cmd); return cmd.ResultsString; } #endregion @@ -579,7 +490,7 @@ namespace VEPROMS.CSLA.Library } } } - _ResultsString = sbs.ToString(); + ResultsString = sbs.ToString(); } } } @@ -591,12 +502,4 @@ namespace VEPROMS.CSLA.Library } #endregion } - public class ESP_FindROProblems : CommandBase - { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #region Factory Methods - #endregion - #region Server-Side Code - #endregion - } } \ No newline at end of file diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/AnnotationExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/AnnotationExt.cs index 6b116fec..727c02d6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/AnnotationExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/AnnotationExt.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; -using System.Text.RegularExpressions; using Csla; using Csla.Data; @@ -11,12 +9,9 @@ namespace VEPROMS.CSLA.Library { public partial class AnnotationInfo { - public override string ToString() - { - return _SearchText; - } - #region JCB Annotation Status - private bool _IsAnnotationNew = false; + public override string ToString() => _SearchText; + #region JCB Annotation Status + private bool _IsAnnotationNew = false; public bool IsAnnotationNew { @@ -49,11 +44,8 @@ namespace VEPROMS.CSLA.Library } public partial class AnnotationType { - public override string ToString() - { - return _Name; - } - [NonSerialized] + public override string ToString() => _Name; + [NonSerialized] private AnnotationTypeConfig _AnnotationTypeConfig; public AnnotationTypeConfig AnnotationTypeConfig { @@ -83,79 +75,69 @@ namespace VEPROMS.CSLA.Library return _AnnotationTypeConfig; } } - public static List AllList() + public static List AllList() => AnnotationTypeInfo._CacheList; + public override string ToString() => _Name; + public static AnnotationTypeInfo GetByName(string name) { - //return _AllList; - return AnnotationTypeInfo._CacheList; + try + { + AnnotationTypeInfo tmp = DataPortal.Fetch(new GetByNameCriteria(name)); + if (tmp.ErrorMessage == "No Record Found") + { + tmp.Dispose(); // Clean-up AnnotationTypeInfo + tmp = null; + } + return tmp; + } + catch (Exception ex) + { + throw new DbCslaException("Error on AnnotationTypeInfo.GetByName", ex); + } } - public override string ToString() + [Serializable()] + protected class GetByNameCriteria { - return _Name; + private readonly string _Name; + public string Name => _Name; + public GetByNameCriteria(string name) => _Name = name; } - public static AnnotationTypeInfo GetByName(string name) - { - try - { - AnnotationTypeInfo tmp = DataPortal.Fetch(new GetByNameCriteria(name)); - if (tmp.ErrorMessage == "No Record Found") - { - tmp.Dispose(); // Clean-up AnnotationTypeInfo - tmp = null; - } - return tmp; - } - catch (Exception ex) - { - throw new DbCslaException("Error on AnnotationTypeInfo.GetByName", ex); - } - } - [Serializable()] - protected class GetByNameCriteria - { - private string _Name; - public string Name { get { return _Name; } } - public GetByNameCriteria(string name) - { - _Name = name; - } - } - private void DataPortal_Fetch(GetByNameCriteria criteria) - { - if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationTypeInfo.DataPortal_Fetch", GetHashCode()); - try - { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) - { - ApplicationContext.LocalContext["cn"] = cn; - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandText = "getAnnotationTypeByName"; - cm.CommandTimeout = Database.SQLTimeout; - cm.Parameters.AddWithValue("@Name", criteria.Name); - using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) - { - if (!dr.Read()) - { - _ErrorMessage = "No Record Found"; - return; - } - ReadData(dr); - } - } - // removing of item only needed for local data portal - if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) - ApplicationContext.LocalContext.Remove("cn"); - } - } - catch (Exception ex) - { - if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationTypeInfo.DataPortal_Fetch", ex); - _ErrorMessage = ex.Message; - throw new DbCslaException("AnnotationTypeInfo.DataPortal_Fetch", ex); - } - } - } + private void DataPortal_Fetch(GetByNameCriteria criteria) + { + if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationTypeInfo.DataPortal_Fetch", GetHashCode()); + try + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + ApplicationContext.LocalContext["cn"] = cn; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandText = "getAnnotationTypeByName"; + cm.CommandTimeout = Database.SQLTimeout; + cm.Parameters.AddWithValue("@Name", criteria.Name); + using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) + { + if (!dr.Read()) + { + _ErrorMessage = "No Record Found"; + return; + } + ReadData(dr); + } + } + // removing of item only needed for local data portal + if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) + ApplicationContext.LocalContext.Remove("cn"); + } + } + catch (Exception ex) + { + if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationTypeInfo.DataPortal_Fetch", ex); + _ErrorMessage = ex.Message; + throw new DbCslaException("AnnotationTypeInfo.DataPortal_Fetch", ex); + } + } + } public partial class AnnotationTypeInfoList { public static void Refresh() @@ -177,44 +159,20 @@ namespace VEPROMS.CSLA.Library _TypeID = anotypeid; MarkDirty(); // force the record update Save(); - //Update(); // commit record to database } } public void CommitChanges() { MarkDirty(); // force the record update Save(true); - //Update(); } public static void DeleteAnnotation(AnnotationInfo obj) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); try { - // ItemInfo nextItem = item.NextItem; - // ItemInfo prevItem = item.MyPrevious; - // item.OnBeforeDelete(); DataPortal.Delete(new DeleteCriteria(obj.AnnotationID, Volian.Base.Library.VlnSettings.UserID)); AnnotationInfo.StaticOnInfoChanged(); - // if (nextItem != null) // Adjust PreviousID for NextItem - // { - // ItemInfo.RefreshPrevious(nextItem.ItemID, item.PreviousID); - // // The order of the next two methods was required to fix a null reference - // // when getting myparent. This bug was found when deleting a node from the - // // tree when the RTBItem was not open (i.e. in the step editor window). - // nextItem.RefreshItemParts(); - // //nextItem.ResetOrdinal(); - UpdateTransitionText calls ResetOrdinal - // nextItem.UpdateTransitionText(); - // } - // else if (prevItem != null) - // { - // prevItem.RefreshNextItems(); - // if (prevItem.IsCaution || prevItem.IsNote) prevItem.ResetOrdinal(); - // prevItem.UpdateTransitionText(); - // } - // ItemInfo.DeleteItemInfoAndChildren(item.ItemID); // Dispose ItemInfo and Children } catch (Exception ex) { @@ -228,8 +186,6 @@ namespace VEPROMS.CSLA.Library public static void DeleteAnnotationProcByType(int typID, string procList) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); try { DataPortal.Delete(new DeleteAnnotationProcByTypeCriteria(typID, procList)); @@ -247,8 +203,6 @@ namespace VEPROMS.CSLA.Library public static void DeleteAnnotationDocvByType(int typID, string versionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); try { DataPortal.Delete(new DeleteAnnotationDocvByTypeCriteria(typID, versionID)); @@ -266,8 +220,6 @@ namespace VEPROMS.CSLA.Library public static int getAnnotationProcCnt(int typID, string procList) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); try { Annotation ProcCnt = DataPortal.Fetch(new getAnnotationCountProcCriteria(typID, procList)); @@ -287,8 +239,6 @@ namespace VEPROMS.CSLA.Library public static int getAnnotationCountDocv(int typID, string procList) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); try { Annotation DocvCnt = DataPortal.Fetch(new getAnnotationCountDocvCriteria(typID, procList)); @@ -319,10 +269,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DeleteCriteria { - private int _AnnotationID; - public int AnnotationID - { get { return _AnnotationID; } } - private string _UserID; + private readonly int _AnnotationID; + public int AnnotationID => _AnnotationID; + private string _UserID; public string UserID { get { return _UserID; } @@ -334,7 +283,7 @@ namespace VEPROMS.CSLA.Library _UserID = userID; } } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(DeleteCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); @@ -364,20 +313,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DeleteAnnotationProcByTypeCriteria { - private int _typeID; - public int TypeID - { get { return _typeID; } } + private readonly int _typeID; + public int TypeID => _typeID; - private string _procList; - public string ProcList - { get { return _procList; } } - public DeleteAnnotationProcByTypeCriteria(int typeID, string procList) + private readonly string _procList; + public string ProcList => _procList; + public DeleteAnnotationProcByTypeCriteria(int typeID, string procList) { _typeID = typeID; _procList = procList; } } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(DeleteAnnotationProcByTypeCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); @@ -407,20 +354,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DeleteAnnotationDocvByTypeCriteria { - private int _typeID; - public int TypeID - { get { return _typeID; } } + private readonly int _typeID; + public int TypeID => _typeID; - private string _versionID; - public string VersionID - { get { return _versionID; } } - public DeleteAnnotationDocvByTypeCriteria(int typeID, string versionID) + private readonly string _versionID; + public string VersionID => _versionID; + public DeleteAnnotationDocvByTypeCriteria(int typeID, string versionID) { _typeID = typeID; _versionID = versionID; } } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(DeleteAnnotationDocvByTypeCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Delete Annotations by Type Docv", GetHashCode()); @@ -459,16 +404,15 @@ namespace VEPROMS.CSLA.Library { private int _procCnt; public int ProcCnt - { get { return _procCnt; } - set { _procCnt = value; } + { + get { return _procCnt; } + set { _procCnt = value; } } - private int _typeID; - public int TypeID - { get { return _typeID; } } - private string _procList; - public string ProcList - { get { return _procList; } } - public getAnnotationCountProcCriteria(int typeID, string procList, int procCnt = 0) + private readonly int _typeID; + public int TypeID => _typeID; + private readonly string _procList; + public string ProcList => _procList; + public getAnnotationCountProcCriteria(int typeID, string procList, int procCnt = 0) { _typeID = typeID; _procList = procList; @@ -476,7 +420,7 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + private getAnnotationCountProcCriteria DataPortal_Fetch(getAnnotationCountProcCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Fetch", GetHashCode()); @@ -517,16 +461,15 @@ namespace VEPROMS.CSLA.Library { private int _docvCnt; public int DocvCnt - { get { return _docvCnt; } - set { _docvCnt = value; } + { + get { return _docvCnt; } + set { _docvCnt = value; } } - private int _TypeID; - public int TypeID - { get { return _TypeID; } } - private string _docvList; - public string DocvList - { get { return _docvList; } } - public getAnnotationCountDocvCriteria(int typeID, string docvList, int docvCnt = 0) + private readonly int _TypeID; + public int TypeID => _TypeID; + private readonly string _docvList; + public string DocvList => _docvList; + public getAnnotationCountDocvCriteria(int typeID, string docvList, int docvCnt = 0) { _TypeID = typeID; _docvList = docvList; @@ -534,7 +477,7 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + private getAnnotationCountDocvCriteria DataPortal_Fetch(getAnnotationCountDocvCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Fetch", GetHashCode()); diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/AuditExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/AuditExt.cs index c6f81cc3..e57c2374 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/AuditExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/AuditExt.cs @@ -1,13 +1,10 @@ using System; using System.Collections.Generic; -using System.Text; using Csla; using Csla.Data; -using Csla.Validation; using System.Data.SqlClient; using System.Data; using System.Text.RegularExpressions; -using System.Xml; namespace VEPROMS.CSLA.Library { @@ -31,26 +28,22 @@ namespace VEPROMS.CSLA.Library get { return _IContentID; } set { _IContentID = value; } } - public ItemInfo MyItemInfo - { - get {return ItemInfo.Get(this.ItemID);} - } - public string ListString() + public ItemInfo MyItemInfo => ItemInfo.Get(ItemID); + public string ListString() { string who = string.Empty; string when = string.Empty; - if (this.UserID != "Migration" || this.TypeID != 1) - who = string.Format(" by {0}", this.UserID); - if (this.DTS != DateTime.Parse("1/1/1980")) - when = string.Format(" on {0}", this.DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); - //return string.Format("{0}{1}{2}", this.ActionWhat, who, when); - return string.Format("{0}{1}{2}", this.DeleteStatus == 0 ? "Changed" : "Deleted", who, when); + if (UserID != "Migration" || TypeID != 1) + who = string.Format(" by {0}", UserID); + if (DTS != DateTime.Parse("1/1/1980")) + when = string.Format(" on {0}", DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); + return string.Format("{0}{1}{2}", DeleteStatus == 0 ? "Changed" : "Deleted", who, when); } public override string ToString() { - string itemTitle = Regex.Replace(this.MyItemInfo.SearchPath, "^..+?\\u0007", ""); + string itemTitle = Regex.Replace(MyItemInfo.SearchPath, "^..+?\\u0007", ""); itemTitle = itemTitle.Replace("\x11", itemTitle[0] == '\x11' ? "" : " - ").Replace("\\u8209?", "-").Replace(@"\u9586?", @"\"); - return string.Format("{0} Annotation {1}", itemTitle, this.ListString()); + return string.Format("{0} Annotation {1}", itemTitle, ListString()); } } @@ -88,56 +81,41 @@ namespace VEPROMS.CSLA.Library } public override string ToString() { - string itemTitle = Regex.Replace(this.Path, "^..+?\\u0007", ""); + string itemTitle = Regex.Replace(Path, "^..+?\\u0007", ""); itemTitle = itemTitle.Replace("\x11", itemTitle[0] == '\x11' ? "" : " - ").Replace("\\u8209?", "-").Replace(@"\u9586?",@"\"); - return string.Format("{4} item {0} by {1} on {2} @ {3}", this.ActionWhat, this.UserID, this.ActionWhen == DateTime.MinValue ? this.DTS.ToShortDateString() : this.ActionWhen.ToShortDateString(), this.ActionWhen == DateTime.MinValue ? this.DTS.ToString("HH:mm:ss") : this.ActionWhen.ToString("HH:mm:ss"), itemTitle); - //return string.Format("{0} by {1} on {2}", this.DeleteStatus == 0 ? "Changed" : "Deleted", this.UserID, this.DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); - //return string.Format("{0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted"); + return string.Format("{4} item {0} by {1} on {2} @ {3}", ActionWhat, UserID, ActionWhen == DateTime.MinValue ? DTS.ToShortDateString() : ActionWhen.ToShortDateString(), ActionWhen == DateTime.MinValue ? DTS.ToString("HH:mm:ss") : ActionWhen.ToString("HH:mm:ss"), itemTitle); } public string ListString() { string who = string.Empty; string when = string.Empty; - if (this.UserID != "Migration") - who = string.Format(" by {0}", this.UserID); - if (this.DTS != DateTime.Parse("1/1/1980")) - when = string.Format(" on {0}", this.DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); - return string.Format("{0}{1}{2}", this.ActionWhat, who, when); + if (UserID != "Migration") + who = string.Format(" by {0}", UserID); + if (DTS != DateTime.Parse("1/1/1980")) + when = string.Format(" on {0}", DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); + return string.Format("{0}{1}{2}", ActionWhat, who, when); } } public partial class DocumentAuditInfo { - public override string ToString() - { - return string.Format("{0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted"); - } + public override string ToString() => $"{UserID} - {DTS} {(DeleteStatus == 0 ? "" : "Deleted")}"; } public partial class EntryAuditInfo { - public override string ToString() - { - return string.Format("{0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted"); - } + public override string ToString() => $"{UserID} - {DTS} {(DeleteStatus == 0 ? "" : "Deleted")}"; } public partial class GridAuditInfo { - public override string ToString() - { - return string.Format("{0} by {1} on {2}", this.DeleteStatus == 0 ? "Changed" : "Deleted", this.UserID, this.DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); - //return string.Format("{0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted"); - } - } + public override string ToString() => $"{(DeleteStatus == 0 ? "Changed" : "Deleted")} by {UserID} on {DTS:MM/dd/yyyy @ HH:mm:ss}"; + } public partial class ImageAuditInfo { - public override string ToString() - { - return string.Format("{0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted"); - } - } + public override string ToString() => $"{UserID} - {DTS} {(DeleteStatus == 0 ? "" : "Deleted")}"; + } public partial class ItemAuditInfo { @@ -165,32 +143,17 @@ namespace VEPROMS.CSLA.Library return true; } internal int _Level; - public int Level - { - get { return _Level; } - } - internal string _ItemType; - public string ItemType - { - get { return _ItemType; } - } + public int Level => _Level; + internal string _ItemType; + public string ItemType => _ItemType; - public override string ToString() - { - return string.Format("{0}{1} deleted by {2} on {3}", this.Level == 0 ? "Previous " : this.Level == 1 ? "Next " : "", this.ItemType, this.UserID, this.DTS.ToString("MM/dd/yyyy @ HH:mm:ss")); -// return string.Format("Deleted by {0} on {1} @ {2}", this.UserID, this.DTS.ToShortDateString(), this.DTS.ToShortTimeString()); -// return string.Format("(ItemID: {4}, DeleteID: {5}, {0} by {1} on {2} Level: {3}", this.DeleteStatus == 0 ? "Changed" : "Deleted", this.UserID, this.DTS.ToString("MM/dd/yyyy @ HH:mm:ss"), Level.ToString(), this.ItemID.ToString(), this.DeleteStatus.ToString()); -// return string.Format("Level: {3}, {0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted", this.Level.ToString()); - } - } + public override string ToString() => $"{(Level == 0 ? "Previous " : Level == 1 ? "Next " : "")}{ItemType} deleted by {UserID} on {DTS:MM/dd/yyyy @ HH:mm:ss}"; + } public partial class PartAuditInfo { - public override string ToString() - { - return string.Format("{0} - {1} {2}", this.UserID, this.DTS, this.DeleteStatus == 0 ? "" : "Deleted"); - } - } + public override string ToString() => $"{UserID} - {DTS} {(DeleteStatus == 0 ? "" : "Deleted")}"; + } public partial class AnnotationAuditInfoList { @@ -206,7 +169,7 @@ namespace VEPROMS.CSLA.Library if (lst != null) { foreach (AnnotationAuditInfo itm in lst) - this.Add(itm); + Add(itm); } IsReadOnly = true; } @@ -220,12 +183,7 @@ namespace VEPROMS.CSLA.Library { try { - //if (_AnnotationAuditInfoList != null) - // return _AnnotationAuditInfoList; AnnotationAuditInfoList tmp = DataPortal.Fetch(new ItemIDCriteria(itemID)); - //AnnotationAuditInfo.AddList(tmp); - //tmp.AddEvents(); - //_AnnotationAuditInfoList = tmp; return tmp; } catch (Exception ex) @@ -236,17 +194,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemIDCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } - } + private readonly int _ItemID; + public int ItemID => _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; + } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -261,7 +215,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new AnnotationAuditInfo(dr)); + while (dr.Read()) Add(new AnnotationAuditInfo(dr)); IsReadOnly = true; } } @@ -272,19 +226,14 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("AnnotationAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } public static AnnotationAuditInfoList GetByAnnotationID(int annotationID) { try { - //if (_AnnotationAuditInfoList != null) - // return _AnnotationAuditInfoList; AnnotationAuditInfoList tmp = DataPortal.Fetch(new AnnotationIDCriteria(annotationID)); - //AnnotationAuditInfo.AddList(tmp); - //tmp.AddEvents(); - //_AnnotationAuditInfoList = tmp; return tmp; } catch (Exception ex) @@ -295,17 +244,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class AnnotationIDCriteria { - private int _AnnotationID; - public int AnnotationID - { get { return _AnnotationID; } } - public AnnotationIDCriteria(int annotationID) - { - _AnnotationID = annotationID; - } - } + private readonly int _AnnotationID; + public int AnnotationID => _AnnotationID; + public AnnotationIDCriteria(int annotationID) => _AnnotationID = annotationID; + } private void DataPortal_Fetch(AnnotationIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -320,7 +265,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new AnnotationAuditInfo(dr)); + while (dr.Read()) Add(new AnnotationAuditInfo(dr)); IsReadOnly = true; } } @@ -331,7 +276,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("AnnotationAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #region ChronologyReport @@ -351,22 +296,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ChronologyCriteria { - private int _procItemID; - public int ProcItemID - { - get { return _procItemID; } - } - private int _itemID; - public int ItemID - { - get { return _itemID; } - } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public ChronologyCriteria(int procItemID, int itemID, DateTime dts) + private readonly int _procItemID; + public int ProcItemID => _procItemID; + private readonly int _itemID; + public int ItemID => _itemID; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public ChronologyCriteria(int procItemID, int itemID, DateTime dts) { _procItemID = procItemID; _itemID = itemID; @@ -375,7 +311,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ChronologyCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -394,11 +330,13 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - AnnotationAuditInfo aai = new AnnotationAuditInfo(dr); - aai.ActionWhat = dr.GetString("ActionWhat"); - aai.ActionWhen = dr.GetDateTime("ActionWhen"); - aai.IContentID = dr.GetInt32("IContentID"); - this.Add(aai); + AnnotationAuditInfo aai = new AnnotationAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat"), + ActionWhen = dr.GetDateTime("ActionWhen"), + IContentID = dr.GetInt32("IContentID") + }; + Add(aai); } IsReadOnly = true; @@ -411,7 +349,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("AnnotationAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } //chronology report by unit public static AnnotationAuditInfoList GetChronologyByUnit(int @procItemID, int itemID, int unitID, DateTime dts) @@ -429,27 +367,15 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ChronologyCriteriaByUnit { - private int _procItemID; - public int ProcItemID - { - get { return _procItemID; } - } - private int _itemID; - public int ItemID - { - get { return _itemID; } - } - private int _UnitID; - public int UnitID - { - get { return _UnitID; } - } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public ChronologyCriteriaByUnit(int procItemID, int itemID, int unitID, DateTime dts) + private readonly int _procItemID; + public int ProcItemID => _procItemID; + private readonly int _itemID; + public int ItemID => _itemID; + private readonly int _UnitID; + public int UnitID => _UnitID; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public ChronologyCriteriaByUnit(int procItemID, int itemID, int unitID, DateTime dts) { _procItemID = procItemID; _itemID = itemID; @@ -459,7 +385,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ChronologyCriteriaByUnit criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -479,11 +405,13 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - AnnotationAuditInfo aai = new AnnotationAuditInfo(dr); - aai.ActionWhat = dr.GetString("ActionWhat"); - aai.ActionWhen = dr.GetDateTime("ActionWhen"); - aai.IContentID = dr.GetInt32("IContentID"); - this.Add(aai); + AnnotationAuditInfo aai = new AnnotationAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat"), + ActionWhen = dr.GetDateTime("ActionWhen"), + IContentID = dr.GetInt32("IContentID") + }; + Add(aai); } IsReadOnly = true; @@ -496,7 +424,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("AnnotationAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #endregion @@ -516,7 +444,7 @@ namespace VEPROMS.CSLA.Library if (lst != null) { foreach (ContentAuditInfo itm in lst) - this.Add(itm); + Add(itm); } IsReadOnly = true; } @@ -530,12 +458,7 @@ namespace VEPROMS.CSLA.Library { try { - //if (_ContentAuditInfoList != null) - // return _ContentAuditInfoList; ContentAuditInfoList tmp = DataPortal.Fetch(new ContentIDCriteria(contentID)); - //ContentAuditInfo.AddList(tmp); - //tmp.AddEvents(); - //_ContentAuditInfoList = tmp; return tmp; } catch (Exception ex) @@ -546,17 +469,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ContentIDCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -573,9 +492,11 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ContentAuditInfo cai = new ContentAuditInfo(dr); - cai.ActionWhat = dr.GetString("ActionWhat"); - this.Add(cai); + ContentAuditInfo cai = new ContentAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat") + }; + Add(cai); // this.Add(new ContentAuditInfo(dr)); } IsReadOnly = true; @@ -588,19 +509,14 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } //byDTS public static ContentAuditInfoList Get(int contentID, DateTime dts) { try { - //if (_ContentAuditInfoList != null) - // return _ContentAuditInfoList; ContentAuditInfoList tmp = DataPortal.Fetch(new ContentIDandDTSCriteria(contentID, dts)); - //ContentAuditInfo.AddList(tmp); - //tmp.AddEvents(); - //_ContentAuditInfoList = tmp; return tmp; } catch (Exception ex) @@ -611,15 +527,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ContentIDandDTSCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public ContentIDandDTSCriteria(int contentID, DateTime dts) + private readonly int _ContentID; + public int ContentID => _ContentID; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public ContentIDandDTSCriteria(int contentID, DateTime dts) { _ContentID = contentID; _DTS = dts; @@ -627,7 +539,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDandDTSCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -645,9 +557,11 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ContentAuditInfo cai = new ContentAuditInfo(dr); - cai.ActionWhat = dr.GetString("ActionWhat"); - this.Add(cai); + ContentAuditInfo cai = new ContentAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat") + }; + Add(cai); // this.Add(new ContentAuditInfo(dr)); } IsReadOnly = true; @@ -660,19 +574,14 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } //by delete status public static ContentAuditInfoList GetByDeleteStatus(int deleteStatus) { try { - //if (_ContentAuditInfoList != null) - // return _ContentAuditInfoList; ContentAuditInfoList tmp = DataPortal.Fetch(new DeleteStatusCriteria(deleteStatus)); - //ContentAuditInfo.AddList(tmp); - //tmp.AddEvents(); - //_ContentAuditInfoList = tmp; return tmp; } catch (Exception ex) @@ -683,17 +592,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DeleteStatusCriteria { - private int _DeleteStatus; - public int DeleteStatus - { get { return _DeleteStatus; } } - public DeleteStatusCriteria(int deleteStatus) - { - _DeleteStatus = deleteStatus; - } - } + private readonly int _DeleteStatus; + public int DeleteStatus => _DeleteStatus; + public DeleteStatusCriteria(int deleteStatus) => _DeleteStatus = deleteStatus; + } private void DataPortal_Fetch(DeleteStatusCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -708,7 +613,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ContentAuditInfo(dr)); + while (dr.Read()) Add(new ContentAuditInfo(dr)); IsReadOnly = true; } } @@ -719,7 +624,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #region ChronologyReport @@ -739,27 +644,15 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ChronologyCriteria { - private int _ProcedureItemID; - public int ProcedureItemID - { - get { return _ProcedureItemID; } - } - private int _CurrentItemID; - public int CurrentItemID - { - get { return _CurrentItemID; } - } - private bool _IncludeDeletedChildren; - public bool IncludeDeletedChildren - { - get { return _IncludeDeletedChildren; } - } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public ChronologyCriteria(int procedureItemID, int currentItemID, bool includeDeletedChildren, DateTime dts) + private readonly int _ProcedureItemID; + public int ProcedureItemID => _ProcedureItemID; + private readonly int _CurrentItemID; + public int CurrentItemID => _CurrentItemID; + private readonly bool _IncludeDeletedChildren; + public bool IncludeDeletedChildren => _IncludeDeletedChildren; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public ChronologyCriteria(int procedureItemID, int currentItemID, bool includeDeletedChildren, DateTime dts) { _ProcedureItemID = procedureItemID; _CurrentItemID = currentItemID; @@ -769,7 +662,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ChronologyCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -789,13 +682,15 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ContentAuditInfo cai = new ContentAuditInfo(dr); - cai.ActionWhat = dr.GetString("ActionWhat"); - cai.ActionWhen = dr.GetDateTime("ActionWhen"); - cai.Path = dr.GetString("Path"); - cai.ItemID = dr.GetInt32("ItemID"); - cai.TypeName = dr.GetString("TypeName"); - this.Add(cai); + ContentAuditInfo cai = new ContentAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat"), + ActionWhen = dr.GetDateTime("ActionWhen"), + Path = dr.GetString("Path"), + ItemID = dr.GetInt32("ItemID"), + TypeName = dr.GetString("TypeName") + }; + Add(cai); } IsReadOnly = true; @@ -808,7 +703,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } //chronology report by unit public static ContentAuditInfoList GetChronologyByUnit(int procedureItemID, int currentItemID, bool includeDeletedChildren, int unitID, DateTime dts) @@ -826,32 +721,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ChronologyCriteriaByUnit { - private int _ProcedureItemID; - public int ProcedureItemID - { - get { return _ProcedureItemID; } - } - private int _CurrentItemID; - public int CurrentItemID - { - get { return _CurrentItemID; } - } - private bool _IncludeDeletedChildren; - public bool IncludeDeletedChildren - { - get { return _IncludeDeletedChildren; } - } - private int _UnitID; - public int UnitID - { - get { return _UnitID; } - } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public ChronologyCriteriaByUnit(int procedureItemID, int currentItemID, bool includeDeletedChildren, int unitID, DateTime dts) + private readonly int _ProcedureItemID; + public int ProcedureItemID => _ProcedureItemID; + private readonly int _CurrentItemID; + public int CurrentItemID => _CurrentItemID; + private readonly bool _IncludeDeletedChildren; + public bool IncludeDeletedChildren => _IncludeDeletedChildren; + private readonly int _UnitID; + public int UnitID => _UnitID; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public ChronologyCriteriaByUnit(int procedureItemID, int currentItemID, bool includeDeletedChildren, int unitID, DateTime dts) { _ProcedureItemID = procedureItemID; _CurrentItemID = currentItemID; @@ -862,7 +742,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ChronologyCriteriaByUnit criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -883,13 +763,15 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ContentAuditInfo cai = new ContentAuditInfo(dr); - cai.ActionWhat = dr.GetString("ActionWhat"); - cai.ActionWhen = dr.GetDateTime("ActionWhen"); - cai.Path = dr.GetString("Path"); - cai.ItemID = dr.GetInt32("ItemID"); - cai.TypeName = dr.GetString("TypeName"); - this.Add(cai); + ContentAuditInfo cai = new ContentAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat"), + ActionWhen = dr.GetDateTime("ActionWhen"), + Path = dr.GetString("Path"), + ItemID = dr.GetInt32("ItemID"), + TypeName = dr.GetString("TypeName") + }; + Add(cai); } IsReadOnly = true; @@ -902,7 +784,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #endregion @@ -923,27 +805,15 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class SummaryCriteria { - private int _ProcedureItemID; - public int ProcedureItemID - { - get { return _ProcedureItemID; } - } - private int _CurrentItemID; - public int CurrentItemID - { - get { return _CurrentItemID; } - } - private bool _IncludeDeletedChildren; - public bool IncludeDeletedChildren - { - get { return _IncludeDeletedChildren; } - } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public SummaryCriteria(int procedureItemID, int currentItemID, bool includeDeletedChildren, DateTime dts) + private readonly int _ProcedureItemID; + public int ProcedureItemID => _ProcedureItemID; + private readonly int _CurrentItemID; + public int CurrentItemID => _CurrentItemID; + private readonly bool _IncludeDeletedChildren; + public bool IncludeDeletedChildren => _IncludeDeletedChildren; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public SummaryCriteria(int procedureItemID, int currentItemID, bool includeDeletedChildren, DateTime dts) { _ProcedureItemID = procedureItemID; _CurrentItemID = currentItemID; @@ -953,7 +823,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(SummaryCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -973,13 +843,15 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ContentAuditInfo cai = new ContentAuditInfo(dr); - cai.ActionWhat = dr.GetString("ActionWhat"); - cai.ActionWhen = dr.GetDateTime("ActionWhen"); - cai.Path = dr.GetString("Path"); - cai.ItemID = dr.GetInt32("ItemID"); - cai.TypeName = dr.GetString("TypeName"); - this.Add(cai); + ContentAuditInfo cai = new ContentAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat"), + ActionWhen = dr.GetDateTime("ActionWhen"), + Path = dr.GetString("Path"), + ItemID = dr.GetInt32("ItemID"), + TypeName = dr.GetString("TypeName") + }; + Add(cai); } IsReadOnly = true; @@ -992,7 +864,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } //summary report by unit public static ContentAuditInfoList GetSummaryByUnit(int procedureItemID, int currentItemID, bool includeDeletedChildren, int unitID, DateTime dts) @@ -1010,32 +882,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class SummaryCriteriaByUnit { - private int _ProcedureItemID; - public int ProcedureItemID - { - get { return _ProcedureItemID; } - } - private int _CurrentItemID; - public int CurrentItemID - { - get { return _CurrentItemID; } - } - private bool _IncludeDeletedChildren; - public bool IncludeDeletedChildren - { - get { return _IncludeDeletedChildren; } - } - private int _UnitID; - public int UnitID - { - get { return _UnitID; } - } - private DateTime _DTS; - public DateTime DTS - { - get { return _DTS; } - } - public SummaryCriteriaByUnit(int procedureItemID, int currentItemID, bool includeDeletedChildren, int unitID, DateTime dts) + private readonly int _ProcedureItemID; + public int ProcedureItemID => _ProcedureItemID; + private readonly int _CurrentItemID; + public int CurrentItemID => _CurrentItemID; + private readonly bool _IncludeDeletedChildren; + public bool IncludeDeletedChildren => _IncludeDeletedChildren; + private readonly int _UnitID; + public int UnitID => _UnitID; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; + public SummaryCriteriaByUnit(int procedureItemID, int currentItemID, bool includeDeletedChildren, int unitID, DateTime dts) { _ProcedureItemID = procedureItemID; _CurrentItemID = currentItemID; @@ -1046,7 +903,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(SummaryCriteriaByUnit criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1067,13 +924,15 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ContentAuditInfo cai = new ContentAuditInfo(dr); - cai.ActionWhat = dr.GetString("ActionWhat"); - cai.ActionWhen = dr.GetDateTime("ActionWhen"); - cai.Path = dr.GetString("Path"); - cai.ItemID = dr.GetInt32("ItemID"); - cai.TypeName = dr.GetString("TypeName"); - this.Add(cai); + ContentAuditInfo cai = new ContentAuditInfo(dr) + { + ActionWhat = dr.GetString("ActionWhat"), + ActionWhen = dr.GetDateTime("ActionWhen"), + Path = dr.GetString("Path"), + ItemID = dr.GetInt32("ItemID"), + TypeName = dr.GetString("TypeName") + }; + Add(cai); } IsReadOnly = true; @@ -1086,7 +945,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #endregion @@ -1114,17 +973,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DocumentIDCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - public DocumentIDCriteria(int docID) - { - _DocID = docID; - } + private readonly int _DocID; + public int DocID => _DocID; + public DocumentIDCriteria(int docID) => _DocID = docID; } private void DataPortal_Fetch(DocumentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1139,7 +994,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DocumentAuditInfo(dr)); + while (dr.Read()) Add(new DocumentAuditInfo(dr)); IsReadOnly = true; } } @@ -1150,7 +1005,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocumentAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } @@ -1176,17 +1031,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ContentIDCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1201,7 +1052,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new EntryAuditInfo(dr)); + while (dr.Read()) Add(new EntryAuditInfo(dr)); IsReadOnly = true; } } @@ -1212,7 +1063,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("EntryAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("EntryAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } @@ -1237,18 +1088,14 @@ namespace VEPROMS.CSLA.Library } [Serializable()] protected class ContentIDCriteria - { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } + { + private readonly int _ContentID; + public int ContentID => _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1263,7 +1110,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new GridAuditInfo(dr)); + while (dr.Read()) Add(new GridAuditInfo(dr)); IsReadOnly = true; } } @@ -1274,7 +1121,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("GridAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("GridAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } @@ -1300,17 +1147,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ContentIDCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1325,7 +1168,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ImageAuditInfo(dr)); + while (dr.Read()) Add(new ImageAuditInfo(dr)); IsReadOnly = true; } } @@ -1336,7 +1179,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ImageAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ImageAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } @@ -1362,17 +1205,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemIDCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } + private readonly int _ItemID; + public int ItemID => _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1389,10 +1228,12 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - ItemAuditInfo iai = new ItemAuditInfo(dr); - iai._Level = dr.GetInt32("Level"); - iai._ItemType = dr.GetString("ItemType"); - this.Add(iai); + ItemAuditInfo iai = new ItemAuditInfo(dr) + { + _Level = dr.GetInt32("Level"), + _ItemType = dr.GetString("ItemType") + }; + Add(iai); } IsReadOnly = true; } @@ -1404,7 +1245,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ItemAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } @@ -1431,17 +1272,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ContentIDCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1456,7 +1293,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartAuditInfo(dr)); + while (dr.Read()) Add(new PartAuditInfo(dr)); IsReadOnly = true; } } @@ -1467,7 +1304,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PartAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } public static PartAuditInfoList GetByDeleteStatus(int deleteStatus) @@ -1485,17 +1322,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DeleteStatusCriteria { - private int _DeleteStatus; - public int DeleteStatus - { get { return _DeleteStatus; } } - public DeleteStatusCriteria(int deleteStatus) - { - _DeleteStatus = deleteStatus; - } + private readonly int _DeleteStatus; + public int DeleteStatus => _DeleteStatus; + public DeleteStatusCriteria(int deleteStatus) => _DeleteStatus = deleteStatus; } private void DataPortal_Fetch(DeleteStatusCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1510,7 +1343,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartAuditInfo(dr)); + while (dr.Read()) Add(new PartAuditInfo(dr)); IsReadOnly = true; } } @@ -1521,7 +1354,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PartAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } public static PartAuditInfoList GetByItemID(int itemID) @@ -1539,17 +1372,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemIDCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } + private readonly int _ItemID; + public int ItemID => _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -1564,7 +1393,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartAuditInfo(dr)); + while (dr.Read()) Add(new PartAuditInfo(dr)); IsReadOnly = true; } } @@ -1575,7 +1404,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PartAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } @@ -1583,12 +1412,8 @@ namespace VEPROMS.CSLA.Library public partial class ItemInfo { public static event ItemInfoEvent InfoRestored; - private void OnInfoRestored(ItemInfo itemInfo) - { - if (InfoRestored != null) - InfoRestored(this); - } - public ItemInfo RestoreSibling(ItemAuditInfo iai,ROFstInfo myRoFst) + private void OnInfoRestored(ItemInfo itemInfo) => InfoRestored?.Invoke(this); + public ItemInfo RestoreSibling(ItemAuditInfo iai,ROFstInfo myRoFst) { if (iai.DeleteStatus == 0) return null; @@ -1607,12 +1432,11 @@ namespace VEPROMS.CSLA.Library } public ItemInfo RestoreItem(ItemAuditInfo iai, ROFstInfo myRoFst) { - ItemInfo tmp2 = null; - try - { + try + { ItemInfo tmp = DataPortal.Fetch(new RestoreCriteria(iai, this)); - tmp2 = tmp; - AddToCache(tmp); + ItemInfo tmp2 = tmp; + AddToCache(tmp); if (tmp.ErrorMessage == "No Record Found") tmp = null; if(iai.Level == 2) OnNewChild(new ItemInfoInsertEventArgs(tmp, EAddpingPart.Child)); @@ -1628,8 +1452,7 @@ namespace VEPROMS.CSLA.Library { foreach (TransitionInfo tran in tmp.MyContent.ContentTransitions) { - if(tran.MyItemToID != null) - tran.MyItemToID.UpdateTransitionText(); + tran.MyItemToID?.UpdateTransitionText(); } } tmp.UpdateROText(); @@ -1645,7 +1468,6 @@ namespace VEPROMS.CSLA.Library } if (cont.ContentRoUsageCount > 0) { - //ROFstInfo myrofst = tmp.MyDocVersion.DocVersionAssociations[0].MyROFst; ROFSTLookup mylookup = myRoFst.GetROFSTLookup(tmp.MyContent.ContentItems[0].MyProcedure.MyDocVersion); foreach (ContentRoUsage ro in cont.ContentRoUsages) { @@ -1722,10 +1544,9 @@ namespace VEPROMS.CSLA.Library } } } - catch (Exception ex) - { - //if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAuditInfoList.DataPortal_Fetch", ex); - //throw new DbCslaException("ItemAuditInfoList.DataPortal_Fetch", ex); + catch (Exception) + { + //Do Nothing if errors } DataPortal_Fetch(new PKCriteria(iai.ItemID)); } @@ -1785,10 +1606,9 @@ namespace VEPROMS.CSLA.Library } } } - catch (Exception ex) + catch (Exception) { - //if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAuditInfoList.DataPortal_Fetch", ex); - //throw new DbCslaException("ItemAuditInfoList.DataPortal_Fetch", ex); + //Do Nothing if errors } } else @@ -1808,12 +1628,11 @@ namespace VEPROMS.CSLA.Library } } } - catch (Exception ex) + catch (Exception) { - //if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAuditInfoList.DataPortal_Fetch", ex); - //throw new DbCslaException("ItemAuditInfoList.DataPortal_Fetch", ex); - } - } + //Do Nothing if errors + } + } DataPortal_Fetch(new PKCriteria(aai.AnnotationID)); } } @@ -1858,8 +1677,7 @@ namespace VEPROMS.CSLA.Library { foreach (TransitionInfo tran in tmp.ContentTransitions) { - if (tran.MyItemToID != null) - tran.MyItemToID.UpdateTransitionText(); + tran.MyItemToID?.UpdateTransitionText(); } } using (Content ctmp = tmp.Get()) @@ -1872,7 +1690,6 @@ namespace VEPROMS.CSLA.Library } ctmp.Save(); } - //ROFstInfo myrofst = tmp.ContentItems[0].MyProcedure.MyDocVersion.DocVersionAssociations[0].MyROFst; if (tmp.ContentRoUsages.Count != 0) // B2017-118 If no ROUsages ignore ROFST { ROFSTLookup mylookup = myRoFst.GetROFSTLookup(tmp.ContentItems[0].MyProcedure.MyDocVersion); @@ -1892,7 +1709,6 @@ namespace VEPROMS.CSLA.Library } ContentInfo.Refresh(cctmp); } - //FixContentText(RoUsageInfo rousg, string value, int rotype, ROFstInfo origROFstInfo return tmp; } @@ -1934,12 +1750,11 @@ namespace VEPROMS.CSLA.Library } } } - catch (Exception ex) + catch (Exception) { - //if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAuditInfoList.DataPortal_Fetch", ex); - //throw new DbCslaException("ItemAuditInfoList.DataPortal_Fetch", ex); - } - DataPortal_Fetch(new PKCriteria(cai.ContentID)); + //Do Nothing if errors + } + DataPortal_Fetch(new PKCriteria(cai.ContentID)); } } public partial class StageInfoList diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/CacheUsage.cs b/PROMS/VEPROMS.CSLA.Library/Extension/CacheUsage.cs index a8fc9de6..c32aee4c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/CacheUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/CacheUsage.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text; using Volian.Base.Library; @@ -438,29 +437,29 @@ namespace VEPROMS.CSLA.Library count += lst.Count; if (count == 0) return ""; string output = typeof(T).Name; - output += "\t" + cache.Count; - output += "\t" + count + "\r\n"; + output += $"\t{cache.Count}"; + output += $"\t{count}\r\n"; return output; } private static string Counts(int count) { if (count == 0) return ""; string output = typeof(T).Name; - output += "\t" + count + "\r\n"; + output += $"\t{count}\r\n"; return output; } private static string Counts(int countNotDisposed, int countNotFinalized) { if (countNotDisposed == 0 && countNotFinalized == 0) return ""; string output = typeof(T).Name; - output += "\t" + countNotDisposed + "\t" + countNotFinalized + "\r\n"; + output += $"\t{countNotDisposed}\t{countNotFinalized}\r\n"; return output; } private static string Counts(int countCreated, int countNotDisposed, int countNotFinalized) { if (countCreated == 0) return ""; string output = typeof(T).Name; - output += "\t" + countCreated + "\t" + countNotDisposed + "\t" + countNotFinalized + "\r\n"; + output += $"\t{countCreated}\t{countNotDisposed}\t{countNotFinalized}\r\n"; return output; } } @@ -475,7 +474,8 @@ namespace VEPROMS.CSLA.Library #region Stack public partial class Content { - private static List _MyStack = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _MyStack = new List(); public static string MyStack { get @@ -519,15 +519,13 @@ namespace VEPROMS.CSLA.Library return _MyStack.IndexOf(stk); } } - private int _StackIndex = StaticStackIndex; - public int StackIndex - { - get { return _StackIndex; } - } - } + private readonly int _StackIndex = StaticStackIndex; + public int StackIndex => _StackIndex; + } public partial class ContentInfo { - private static List _MyStack = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _MyStack = new List(); public static string MyStack { get @@ -571,15 +569,13 @@ namespace VEPROMS.CSLA.Library return _MyStack.IndexOf(stk); } } - private int _StackIndex = StaticStackIndex; - public int StackIndex - { - get { return _StackIndex; } - } - } + private readonly int _StackIndex = StaticStackIndex; + public int StackIndex => _StackIndex; + } public partial class DocVersionInfo { - private static List _MyStack = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _MyStack = new List(); public static string MyStack { get @@ -623,12 +619,9 @@ namespace VEPROMS.CSLA.Library return _MyStack.IndexOf(stk); } } - private int _StackIndex = StaticStackIndex; - public int StackIndex - { - get { return _StackIndex; } - } - } + private readonly int _StackIndex = StaticStackIndex; + public int StackIndex => _StackIndex; + } public partial class PartInfo { public static HashSet CacheList diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ColorTab.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ColorTab.cs index 8c5bb647..13121f59 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ColorTab.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ColorTab.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Text; namespace VEPROMS.CSLA.Library { @@ -21,26 +19,28 @@ namespace VEPROMS.CSLA.Library // if the dictionary hasn't been set yet, if (ColorIndx==null) { - ColorIndx = new Dictionary(); - ColorIndx["black"] = 1; - ColorIndx["blue"] = 2; - ColorIndx["green"] = 3; - ColorIndx["cyan"] = 4; - ColorIndx["red"] = 5; - ColorIndx["magenta"] = 6; - ColorIndx["brown"] = 7; - ColorIndx["lightgray"] = 8; - ColorIndx["darkgray"] = 9; - ColorIndx["lightblue"] = 10; - ColorIndx["lightgreen"] = 11; - ColorIndx["lightcyan"] = 12; - ColorIndx["lightred"] = 13; - ColorIndx["lightmagenta"] = 14; - ColorIndx["yellow"] = 15; - ColorIndx["white"] = 16; - ColorIndx["ro"] = 17; - ColorIndx["trans"] = 18; - ColorIndx["editbackground"] = 19; + ColorIndx = new Dictionary + { + ["black"] = 1, + ["blue"] = 2, + ["green"] = 3, + ["cyan"] = 4, + ["red"] = 5, + ["magenta"] = 6, + ["brown"] = 7, + ["lightgray"] = 8, + ["darkgray"] = 9, + ["lightblue"] = 10, + ["lightgreen"] = 11, + ["lightcyan"] = 12, + ["lightred"] = 13, + ["lightmagenta"] = 14, + ["yellow"] = 15, + ["white"] = 16, + ["ro"] = 17, + ["trans"] = 18, + ["editbackground"] = 19 + }; } return ColorIndx[color]; } @@ -49,49 +49,49 @@ namespace VEPROMS.CSLA.Library // This gets the rtf color table string for the input color. public static string GetTableString(string color) { - Dictionary ColorIndx = new Dictionary(); if (ColorRtf == null) { - ColorRtf = new Dictionary(); - - // color table, from 16-bit code, is defined as (in order): - // black=0,0,0 - // blue=0,0,255 - // green=0,155,12 - // cyan=0,136,159 - // red=255,0,0 - // magenta=202,28,175 - // brown=128,64,0 - // lightgray=0,0,0 - // darkgray=0,0,0 - // lightblue=0,0,255 - // lightgreen=0,255,0 - // lightcyan=0,0,255 - // lightred=209,29,183 - // lightmagenta=255,0,255 - // yellow=255,0,0 - // white=128,128,128 - // ro=255,128,0 - // editbackground=192,192,192 - ColorRtf["black"] = "\\red0\\green0\\blue0;"; - ColorRtf["blue"] = "\\red0\\green0\\blue255;"; - ColorRtf["green"] = "\\red0\\green155\\blue12;"; - ColorRtf["cyan"] = "\\red0\\green136\\blue159;"; - ColorRtf["red"] = "\\red255\\green0\\blue0;"; - ColorRtf["magenta"] = "\\red202\\green28\\blue175;"; - ColorRtf["brown"] = "\\red128\\green64\\blue0;"; - ColorRtf["lightgray"] = "\\red100\\green100\\blue100;"; - ColorRtf["darkgray"] = "\\red10\\green10\\blue10;"; - ColorRtf["lightblue"] = "\\red0\\green0\\blue255;"; - ColorRtf["lightgreen"] = "\\red0\\green255\\blue0;"; - ColorRtf["lightcyan"] = "\\red0\\green0\\blue255;"; - ColorRtf["lightred"] = "\\red209\\green29\\blue183;"; - ColorRtf["lightmagenta"] = "\\red255\\green0\\blue255;"; - ColorRtf["yellow"] = "\\red255\\green0\\blue0;"; - ColorRtf["white"] = "\\red128\\green128\\blue128;"; - ColorRtf["ro"] = "\\red255\\green128\\blue0;"; - ColorRtf["trans"] = "\\red255\\green128\\blue0;"; - ColorRtf["editbackground"] = "\\red192\\green192\\blue192;"; + ColorRtf = new Dictionary + { + // color table, from 16-bit code, is defined as (in order): + // black=0,0,0 + // blue=0,0,255 + // green=0,155,12 + // cyan=0,136,159 + // red=255,0,0 + // magenta=202,28,175 + // brown=128,64,0 + // lightgray=0,0,0 + // darkgray=0,0,0 + // lightblue=0,0,255 + // lightgreen=0,255,0 + // lightcyan=0,0,255 + // lightred=209,29,183 + // lightmagenta=255,0,255 + // yellow=255,0,0 + // white=128,128,128 + // ro=255,128,0 + // editbackground=192,192,192 + ["black"] = "\\red0\\green0\\blue0;", + ["blue"] = "\\red0\\green0\\blue255;", + ["green"] = "\\red0\\green155\\blue12;", + ["cyan"] = "\\red0\\green136\\blue159;", + ["red"] = "\\red255\\green0\\blue0;", + ["magenta"] = "\\red202\\green28\\blue175;", + ["brown"] = "\\red128\\green64\\blue0;", + ["lightgray"] = "\\red100\\green100\\blue100;", + ["darkgray"] = "\\red10\\green10\\blue10;", + ["lightblue"] = "\\red0\\green0\\blue255;", + ["lightgreen"] = "\\red0\\green255\\blue0;", + ["lightcyan"] = "\\red0\\green0\\blue255;", + ["lightred"] = "\\red209\\green29\\blue183;", + ["lightmagenta"] = "\\red255\\green0\\blue255;", + ["yellow"] = "\\red255\\green0\\blue0;", + ["white"] = "\\red128\\green128\\blue128;", + ["ro"] = "\\red255\\green128\\blue0;", + ["trans"] = "\\red255\\green128\\blue0;", + ["editbackground"] = "\\red192\\green192\\blue192;" + }; } return ColorRtf[color]; } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs index fff93e8c..57256636 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ContentExt.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Text; using Csla; using Csla.Data; -using System.Xml; using System.Data.SqlClient; using System.Data; using System.Text.RegularExpressions; @@ -80,7 +79,7 @@ namespace VEPROMS.CSLA.Library { string rv = ConvertTransitionToText(tran, newvalue); //Text = Text.Substring(0, myIndex - 14) + gg + Text.Substring(myIndex + myLength); - using (Item myitem = this.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 + using (Item myitem = ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 { myitem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 // B2016-225 (follow through) added more descriptive Annotation Type when transition is converted to text] @@ -161,13 +160,11 @@ namespace VEPROMS.CSLA.Library else { // look for rtf font command and insert it around the special char (i.e. symbol char) int ii = orgText.IndexOf(specChar); - int fnt1 = -1; - int fnt2 = -1; - if (ii > -1) + if (ii > -1) { - fnt1 = orgText.LastIndexOf(@"\f", ii); - fnt2 = orgText.IndexOf(@"\f", ii); - if (fnt1 != -1 && fnt2 != -1) + int fnt1 = orgText.LastIndexOf(@"\f", ii); + int fnt2 = orgText.IndexOf(@"\f", ii); + if (fnt1 != -1 && fnt2 != -1) newValue = newValue.Replace(specChar, orgText.Substring(fnt1, 3) + specChar + orgText.Substring(fnt2, 3) + " "); } } @@ -199,11 +196,8 @@ namespace VEPROMS.CSLA.Library } else lookFor = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}~\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}}~ \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); - int lastIndex = 0; - string newText = MyGrid.Data; foreach (Match mm in ms) { - int offset = mm.Index; Match m = Regex.Match(mm.Value, lookFor, RegexOptions.Singleline); if (m != null && m.Groups.Count > 1) { @@ -228,8 +222,7 @@ namespace VEPROMS.CSLA.Library } break; // Text has been processed } - lastIndex = mm.Index + mm.Length; - } + } return; } public string ConvertTransitionToText(TransitionInfo tran, string value) @@ -554,13 +547,13 @@ namespace VEPROMS.CSLA.Library } if (value == "?" || gg != newvalue) { - MyGrid.Data = Content.ConvertGridROsToText(MyGrid.Data, mmg, mg, newvalue); // B2017-060 convert the RO in the grid (table) to text + MyGrid.Data = ConvertGridROsToText(MyGrid.Data, mmg, mg, newvalue); // B2017-060 convert the RO in the grid (table) to text } } } } } - return retval == null ? "" : retval; + return retval ?? ""; } // B2017-060 logic pulled from dlgExportImport to covert a RO in a table (grid) to text public static string ConvertGridROsToText(string data, Match mmg, Match mg, string ss) @@ -601,8 +594,8 @@ namespace VEPROMS.CSLA.Library string retval = null; if (value == "?") { - retval = this.ConvertROToText(rousg, value, rotype, origROFstInfo, roidFrmImportStep); - using (Item myitem = this.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 + retval = ConvertROToText(rousg, value, rotype, origROFstInfo, roidFrmImportStep); + using (Item myitem = ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 { myitem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 // B2016-225 (follow through) added more descriptive Annotation Type when RO is converted to text @@ -638,7 +631,7 @@ namespace VEPROMS.CSLA.Library Text = Text.Substring(0, myIndex) + newvalue + Text.Substring(myIndex + myLength); if (!saveAnnotation) { - using (Item myitem = this.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 + using (Item myitem = ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 { myitem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 // B2016-225 (follow through) added more descriptive Annotation Type when RO is converted to text @@ -836,21 +829,17 @@ namespace VEPROMS.CSLA.Library { return str.Replace(@"\u8209?", "-").Replace(@"\u160?", " "); //dash and hard space } - - //C2022-028 (only used from Amin Tools) check the RO link text - compare with RO Usage information, annotate RO links that are bad - public bool CheckROLinkTextandUsage(ref int BadROLinksCount, ref int CheckROLinksCount, ref int FixedROLinksCount) + + //C2022-028 (only used from Admin Tools) check the RO link text - compare with RO Usage information, annotate RO links that are bad + public bool CheckROLinkTextandUsage(ref int BadROLinksCount, ref int CheckROLinksCount) { - /*** needed if we fix RO link text - bool bFixedROLinks = false; - bool bFixedTableDataText = false; - ***/ - if (this.Text.Contains("#Link:ReferencedObject:")) + if (Text.Contains("#Link:ReferencedObject:")) { - if (this.ContentRoUsageCount == 0) // Procedure text has one or more links but no RO Usage records + if (ContentRoUsageCount == 0) // Procedure text has one or more links but no RO Usage records { CheckROLinksCount++; - _MyLog.ErrorFormat(string.Format("No RO usage records for RO link(s) - ContentID = {0}", this.ContentID)); - using (Item myItem = this.ContentItems[0].MyItem) // so that myitem does not stay in cache + _MyLog.ErrorFormat(string.Format("No RO usage records for RO link(s) - ContentID = {0}", ContentID)); + using (Item myItem = ContentItems[0].MyItem) // so that myitem does not stay in cache { myItem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed Annotation.MakeAnnotation(myItem, AnnotationType.GetByNameOrCreate("Bad RO link"), "", "Incomplete RO Link Information for all RO References in this text - Relink RO References", null); @@ -862,7 +851,6 @@ namespace VEPROMS.CSLA.Library string findLink = @""; MatchCollection ms = Regex.Matches(Text, findLink); // finds all the links (both RO and Transitions) string lookFor = "#Link:ReferencedObject:"; - string fixedContentText = Text; if (ms.Count > 0) { int roCnt = 0; @@ -892,18 +880,17 @@ namespace VEPROMS.CSLA.Library bool GoodROUsageID = false; bool GoodROID = false; // Check each ContentRoUsages and look for a matching ROUsageID and ROID - if (iRousage > 0 && this.ContentRoUsageCount > 0) + if (iRousage > 0 && ContentRoUsageCount > 0) { int lastROUsageID = -1; string lastROID = ""; RoUsageInfo badRoUsageInfo = null; - foreach (RoUsageInfo rui in this.ContentItems[0].MyItem.MyItemInfo.MyContent.ContentRoUsages) + foreach (RoUsageInfo rui in ContentItems[0].MyItem.MyItemInfo.MyContent.ContentRoUsages) { GoodROID = rui.ROID.Equals(sROid); //does this usage record have a matching ROID with the link text? GoodROUsageID = rui.ROUsageID.Equals(iRousage); //does the usage record have a matching ROUsageID with the link text? if (GoodROID && GoodROUsageID) { - //myROUsages.RemoveAt(myROUsageCnt - 1); break; // jump out loop - valid RO Usage record found } if (GoodROID && !GoodROUsageID) @@ -918,46 +905,24 @@ namespace VEPROMS.CSLA.Library { BadROLinksCount++; // Add detail information to the error log - _MyLog.ErrorFormat(string.Format("Invalid ROID - ContentID = {0} Link - {1}", this.ContentID, mm.Value)); + _MyLog.ErrorFormat(string.Format("Invalid ROID - ContentID = {0} Link - {1}", ContentID, mm.Value)); sAnnotationText += string.Format("Bad RO Instance {0} - RO Needs Relinked - RO Text different than RO Data\n", roCnt); } else if (!GoodROUsageID) // Link does not have a valid ROUsage record for that RO link - add annotation { BadROLinksCount++; - /********* - //** below is logic to replace the ROUsageID in the linked text with one (for this contentID) that has the same ROID - //** Commented out for now as this was test code for now - don't want to give to customers until we are comfortable - //if (lastROUsageID != -1) - //{ - // // set the ROUsageID in the link text to last good ROUsageID found in ROUsage table - // linkText = linkText.Replace(string.Format("#Link:ReferencedObject:{0} ", sROusageID), string.Format("#Link:ReferencedObject:{0} ", lastROUsageID)); - // fixedContentText = fixedContentText.Replace(string.Format("#Link:ReferencedObject:{0} ", sROusageID), string.Format("#Link:ReferencedObject:{0} ", lastROUsageID)); - // bFixedROLinks = true; // set to true so we know to update content text - // _MyLog.InfoFormat(string.Format("Fixed Invalid RO Link - ContentID = {0} badLink - {1} goodLink - {2}",this.ContentID, mm.Value, linkText)); - // FixedROLinksCount++; - // using (Item myItem = this.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 - // { - // myItem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 - // //Annotation.MakeAnnotation(myItem, AnnotationType.GetByNameOrCreate("Bad RO link"), "", string.Format("Invalid RO Usage ID for RO Instance {0}",roCnt), null); - // Annotation.MakeAnnotation(myItem, AnnotationType.GetByNameOrCreate("Fixed Bad RO link"), "", string.Format("Fixed RO Instance {0} - Verify RO Value", roCnt), null); - // } - //} - *********/ - //else - //{ - // Add detail information to the error log - _MyLog.ErrorFormat(string.Format("Invalid ROUsageID - ContentID = {0} Link - {1}", this.ContentID, mm.Value)); - sAnnotationText += string.Format("RO Instance {0} Needs Relinked - Value Not Able To Update\n", roCnt); - //} + // Add detail information to the error log + _MyLog.ErrorFormat(string.Format("Invalid ROUsageID - ContentID = {0} Link - {1}", ContentID, mm.Value)); + sAnnotationText += string.Format("RO Instance {0} Needs Relinked - Value Not Able To Update\n", roCnt); } } } } - if (roCnt < this.ContentRoUsageCount) + if (roCnt < ContentRoUsageCount) { BadROLinksCount++; // there are more RO Usage records then there links in the step - _MyLog.WarnFormat(string.Format("Possible missing RO links, more RO Usage records than Links - ContentID = {0}", this.ContentID)); + _MyLog.WarnFormat(string.Format("Possible missing RO links, more RO Usage records than Links - ContentID = {0}", ContentID)); sAnnotationText += "Possible missing RO links.\n"; } // if any bad RO links were found, put the information in an Annotation @@ -965,113 +930,15 @@ namespace VEPROMS.CSLA.Library { char[] newLine = { '\n' }; sAnnotationText = sAnnotationText.TrimEnd(newLine); - using (Item myItem = this.ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 + using (Item myItem = ContentItems[0].MyItem) // so that myitem does not stay in cache B2016-153 { myItem.DisposeOfContent = false; // don't dispose of the contents may be needed if more than one RO needs processed - part of B2017-060 - //Annotation.MakeAnnotation(myItem, AnnotationType.GetByNameOrCreate("Bad RO link"), "", string.Format("Invalid RO Usage ID for RO Instance {0}",roCnt), null); Annotation.MakeAnnotation(myItem, AnnotationType.GetByNameOrCreate("Bad RO link"), "", sAnnotationText, null); } } - /*** COMMENTED OUT BECAUSE WE NOT MAKING CHANGES TO THE DATA - FOR NOW - //if (bFixedROLinks) - //{ - // // save content text - // Text = fixedContentText; - //} - *****/ - - /******* - // if we fix RO links in the RTF then see if there is a grid to update too. - // WE DON'T NEED TO ADD ANNOTATIONS AS THAT IS DONE ABOVE (FOR THE RTF OF THE TABLE - BELOW IS THE XML OF THE TABLE - // *** bFixedROLinks WILL REMAIN FALSE FOR NOW AS WE ARE NOT CHANGING LINK TEXT - THIS WILL PREVENT THE CHECKING OF THE XML TABLE - if (bFixedROLinks && MyGrid != null && MyGrid.Data.Length > 0) - { - string fixedTableDataText = MyGrid.Data; - // **** NEED LOGIC TO CHECK RO TABLES **** - - //if (rotype == (int)E_ROValueType.Table) // if change in rotable data... - //{ - // if (origROFstInfo != null) - // { - // List retlist = origROFstInfo.OnROTableUpdate(this, new ROFstInfoROTableUpdateEventArgs(newvalue, MyGrid.Data)); - // if (MyGrid.Data != retlist[1]) - // { - // MyGrid.Data = retlist[1]; - // retval = Text; - // if (Text != retlist[0]) - // Text = retlist[0]; - // } - // } - //} - //else - { - // if it's an ro within a table, need to process into an flex grid to save the grid data: - string findLinkXml = @"<START\].*?\[END>"; - //string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>$", rousg.ROUsageID); - string lookForXml = "#Link:ReferencedObject:"; - MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); - foreach (Match mmg in msg) - { - Match mg = Regex.Match(mmg.Value, lookForXml);// look for Referenced Object link in linked text - if (mg != null && mg.Groups.Count > 1) - { - string tblLinkText = mmg.Value; // the link text in the table XML - int rousgidx = mg.Index + mg.Length; - int rousagid_len = mmg.Value.IndexOf(" ", rousgidx) - rousgidx; - string sROusageID = mmg.Value.Substring(rousgidx, rousagid_len); // ROUsageID from link text - int roidIdx = rousgidx + rousagid_len + 1; - int roid_Len = mmg.Value.IndexOf(" ", roidIdx) - roidIdx; - string sROid = mmg.Value.Substring(roidIdx, roid_Len); - // initialize to zero for cases where the ROUsage is to force a no match below - // -when a link has either of these, then the process of inserting that RO link did not complete for some reason - int iRousage = 0; - if (!sROusageID.StartsWith("<")) // don't try to convert if link has for the ROUsageID value - iRousage = Convert.ToInt32(sROusageID); //ROUsageID as interger - // see if there is a ContentID and ROUsage record match - // Both GoodROUsageID and GoodROUID must match in ROUsage record for link to be good - bool GoodROUsageID = false; - bool GoodROID = false; - // Check each ContentRoUsages and look for a matching ROUsageID and ROID - if (iRousage > 0 && this.ContentRoUsageCount > 0) - { - int lastROUsageID = -1; - string lastROID = ""; - RoUsageInfo badRoUsageInfo = null; - foreach (RoUsageInfo rui in this.ContentItems[0].MyItem.MyItemInfo.MyContent.ContentRoUsages) - { - GoodROID = rui.ROID.Equals(sROid); //does this usage record have a matching ROID with the link text? - GoodROUsageID = rui.ROUsageID.Equals(iRousage); //does the usage record have a matching ROUsageID with the link text? - if (GoodROID && GoodROUsageID) break; // jump out loop - valid RO Usage record found - if (GoodROID && !GoodROUsageID) - { - lastROUsageID = rui.ROUsageID; - lastROID = rui.ROID; - } - else if (!GoodROID && GoodROUsageID) - badRoUsageInfo = rui; - } - if (!GoodROUsageID && GoodROID && lastROUsageID != -1) // Link does not have a valid ROUsage record for that RO link - add annotation - { - // set the ROUsageID in the link text to last good ROUsageID found in ROUsage table - tblLinkText = tblLinkText.Replace(string.Format("#Link:ReferencedObject:{0} ", sROusageID), string.Format("#Link:ReferencedObject:{0} ", lastROUsageID)); - fixedTableDataText = fixedTableDataText.Replace(string.Format("#Link:ReferencedObject:{0} ", sROusageID), string.Format("#Link:ReferencedObject:{0} ", lastROUsageID)); - bFixedTableDataText = true; // set to true so we know to update content text - } - if (bFixedTableDataText) // if we changed the table XML, then save it - { - this.MyGrid.Data = fixedTableDataText; - } - } - } - } - } - ******* End modify table ****/ } } } - /*** needed if we fix RO links - return (bFixedROLinks || bFixedTableDataText); - ***/ return false; } } @@ -1079,29 +946,14 @@ namespace VEPROMS.CSLA.Library public delegate void StaticContentInfoEvent(object sender, StaticContentInfoEventArgs args); public class StaticContentInfoEventArgs { - string _OldValue; - public string OldValue + public string OldValue { get; set; } + public string NewValue { get; set; } + public string Type { get; set; } + public StaticContentInfoEventArgs(string oldValue, string newValue, string type) { - get { return _OldValue; } - set { _OldValue = value; } - } - string _NewValue; - public string NewValue - { - get { return _NewValue; } - set { _NewValue = value; } - } - string _Type; - public string Type - { - get { return _Type; } - set { _Type = value; } - } - public StaticContentInfoEventArgs(string oldValue, string newValue, string type) - { - _OldValue = oldValue; - _NewValue = newValue; - _Type = type; + OldValue = oldValue; + NewValue = newValue; + Type = type; } } @@ -1119,27 +971,14 @@ namespace VEPROMS.CSLA.Library return sb.ToString(); } - public string LastChangedString - { - get { return ContentInfo.FormatByteArray(_LastChanged); } - } + public string LastChangedString => FormatByteArray(_LastChanged); - public Int64 LastChangedInt64 - { - get { return Convert.ToInt64(LastChangedString, 16); } - } - public static bool IsInCache(int contentID) - { - return _CacheByPrimaryKey.ContainsKey(contentID.ToString()); - } - public static event StaticContentInfoEvent StaticContentInfoChange; - // B2018-002 - Invalid Transitions - Changed to Public - public static void OnStaticContentInfoChange(object sender, StaticContentInfoEventArgs args) - { - if (StaticContentInfoChange != null) - StaticContentInfoChange(sender, args); - } - public string MyContentMessage = string.Empty; + public long LastChangedInt64 => Convert.ToInt64(LastChangedString, 16); + public static bool IsInCache(int contentID) => _CacheByPrimaryKey.ContainsKey(contentID.ToString()); + public static event StaticContentInfoEvent StaticContentInfoChange; + // B2018-002 - Invalid Transitions - Changed to Public + public static void OnStaticContentInfoChange(object sender, StaticContentInfoEventArgs args) => StaticContentInfoChange?.Invoke(sender, args); + public string MyContentMessage = string.Empty; public string MyGridMessage = string.Empty; public bool InList(params int[] IDs) { @@ -1150,22 +989,13 @@ namespace VEPROMS.CSLA.Library return false; } - public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii) - { - FixTransitionText(tran, tranLookup, ii, ""); - } + public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii) => FixTransitionText(tran, tranLookup, ii, ""); - public void FixTransitionText(TransitionInfo tran, ItemInfo ii) - { - FixTransitionText(tran, ii, ""); - } + public void FixTransitionText(TransitionInfo tran, ItemInfo ii) => FixTransitionText(tran, ii, ""); - public void FixTransitionText(TransitionInfo tran, ItemInfo ii, string forceConvertToText) - { - FixTransitionText(tran, null, ii, forceConvertToText); - } + public void FixTransitionText(TransitionInfo tran, ItemInfo ii, string forceConvertToText) => FixTransitionText(tran, null, ii, forceConvertToText); - public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii, string forceConvertToText) + public void FixTransitionText(TransitionInfo tran, TransitionLookup tranLookup, ItemInfo ii, string forceConvertToText) { string newvalue; MyContentMessage = string.Empty; @@ -1199,7 +1029,7 @@ namespace VEPROMS.CSLA.Library myLength += m.Groups[3].Length; } string gg = Text.Substring(myIndex, myLength); - MyContentMessage = string.Format("ContentExt.ContentInfo:Content:{0}, {1}, {2}", this.ContentID, tran.TransitionID, gg); + MyContentMessage = string.Format("ContentExt.ContentInfo:Content:{0}, {1}, {2}", ContentID, tran.TransitionID, gg); newvalue = newvalue.Replace("{", @"\{").Replace("}", @"\}"); if ((gg.Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\\")) != (newvalue.Replace("\\u8209?", "-").Replace(@"\u9586?", @"\\")) || newvalue == "?") // B2017-165 added check of newvalue { @@ -1230,66 +1060,57 @@ namespace VEPROMS.CSLA.Library // see if there is a grid to update too. if (tran.MyContent.MyGrid != null) { - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* ([^#]*?)(\\[^v'? \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); - //Match mg = Regex.Match(MyGrid.Data, lookForXml); - //if (mg != null && mg.Groups.Count > 1) - //{ - // System.Text.RegularExpressions.Group g = mg.Groups[3]; - // //if (g.ToString() != transText) - // // MyGrid.Data = MyGrid.Data.Substring(0, g.Index) + transText + MyGrid.Data.Substring(g.Index + g.Length); - //} - MyGridMessage = string.Empty; - string findLinkXml = @"<START\].*?\[END>"; - //string lookForXml = string.Format(@"<START\](\\[^v \\]+)*\\v0(\\[^v \\]+)* (.*?)(\\[^v '?\\]+)*\\v(\\[^v \\]+)* #Link:ReferencedObject:{0} .*?\[END>", rousg.ROUsageID); - string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); - MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); - foreach (Match mmg in msg) - { - Match mg = Regex.Match(mmg.Value, lookForXml);// Regex.Match(MyGrid.Data, lookForXml); - if (mg != null && mg.Groups.Count > 1) - { - int myIndex = mg.Groups[4].Index + mmg.Index; - int myLength = mg.Groups[4].Length; - if (mg.Groups[3].Value != " ") - { - myIndex = mg.Groups[3].Index + mmg.Index; - myLength += mg.Groups[3].Length; - } - string gg = MyGrid.Data.Substring(myIndex, myLength); - if (newvalue.Contains(@"\u8209?")) - { - // B2022-058: Printing of '-' in transition in table prints as '?' instead of '-'. Wasn't using correct string to - // look for font character (was using newvalue, not gg) - Match m = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u8209?", "-"); - else - newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u9586?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u9586?", @"\\"); - else - newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); - } - if (newvalue.Contains(@"\u9586?")) - { - Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); - if (m == null) - newvalue = newvalue.Replace(@"\u9586?", @"\\"); - else - newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); - } - MyGridMessage = string.Format("ContentExt.ContentInfo:Grid:{0}, {1}, {2}", this.ContentID, tran.TransitionID, gg); - if (gg != newvalue) - { - MyGrid.SetData(MyGrid.Data.Substring(0, myIndex) + newvalue + MyGrid.Data.Substring(myIndex + myLength)); - } - } - } - } + MyGridMessage = string.Empty; + string findLinkXml = @"<START\].*?\[END>"; + string lookForXml = string.Format(@"^<START\](\\[^v \\]+)*\\v0(\\[^v '?{{}}\\]+)*( |\\u[0-9]{{1,4}}?|\\'[0-9a-fA-F]{{2}}|\\[{{}}~])(.*?)(\\[^v'?{{}} \\]+)*\\v(\\[^v \\]+)* #Link:Transition[^:]*?:{0} {1}( [0-9]*){{1,2}}\[END>", tran.TranType, tran.TransitionID); + MatchCollection msg = Regex.Matches(MyGrid.Data, findLinkXml); + foreach (Match mmg in msg) + { + Match mg = Regex.Match(mmg.Value, lookForXml); + if (mg != null && mg.Groups.Count > 1) + { + int myIndex = mg.Groups[4].Index + mmg.Index; + int myLength = mg.Groups[4].Length; + if (mg.Groups[3].Value != " ") + { + myIndex = mg.Groups[3].Index + mmg.Index; + myLength += mg.Groups[3].Length; + } + string gg = MyGrid.Data.Substring(myIndex, myLength); + if (newvalue.Contains(@"\u8209?")) + { + // B2022-058: Printing of '-' in transition in table prints as '?' instead of '-'. Wasn't using correct string to + // look for font character (was using newvalue, not gg) + Match m = Regex.Match(gg, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u8209?", "-"); + else + newvalue = newvalue.Replace(@"\u8209?", $@"{m.Groups[1].Value}\u8209?{m.Groups[3].Value}"); + } + if (newvalue.Contains(@"\u9586?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u9586?", @"\\"); + else + newvalue = newvalue.Replace(@"\u9586?", $@"{m.Groups[1].Value}\u9586?{m.Groups[3].Value}"); + } + if (newvalue.Contains(@"\u9586?")) + { + Match m = Regex.Match(newvalue, @"(\\f[0-9]+)(\\u[0-9]{1,4}\?)(\\f[0-9]+ ?)"); + if (m == null) + newvalue = newvalue.Replace(@"\u9586?", @"\\"); + else + newvalue = newvalue.Replace(@"\u9586?", $@"{m.Groups[1].Value}\u9586?{m.Groups[3].Value}"); + } + MyGridMessage = string.Format("ContentExt.ContentInfo:Grid:{0}, {1}, {2}", ContentID, tran.TransitionID, gg); + if (gg != newvalue) + { + MyGrid.SetData(MyGrid.Data.Substring(0, myIndex) + newvalue + MyGrid.Data.Substring(myIndex + myLength)); + } + } + } + } } public void FixContentText(RoUsageInfo rousg, string value, int rotype, ROFstInfo origROFstInfo, ItemInfo ii) @@ -1362,10 +1183,6 @@ namespace VEPROMS.CSLA.Library newvalue = newvalue.Replace($"{(char)916}", @"\u916?"); } - // Debug - jsj 5-19-2017 - left in for initial check-in - //string xx_gg = gg_org.Replace(@"\'b0", @"\'B0").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace("\xA0", " "); - //string xx_nv = newval_org.Replace(@"\'b0", @"\'B0").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace("\xA0", " "); - //Console.WriteLine(xx_gg.CompareTo(xx_nv)); OnStaticContentInfoChange(ii, new StaticContentInfoEventArgs(gg, newvalue, "RO")); break; // Text has been processed } @@ -1378,7 +1195,7 @@ namespace VEPROMS.CSLA.Library { if (rotype == (int)E_ROValueType.Table) // if change in rotable data... { - List retlist = origROFstInfo.OnROTableUpdate(this.Get(), new ROFstInfoROTableUpdateEventArgs(newvalue, MyGrid.Data)); + List retlist = origROFstInfo.OnROTableUpdate(Get(), new ROFstInfoROTableUpdateEventArgs(newvalue, MyGrid.Data)); if (retlist != null && Text != retlist[0]) _Text = retlist[0]; //B2022-075 added null reference check } else @@ -1412,7 +1229,7 @@ namespace VEPROMS.CSLA.Library if (m.Groups.Count < 3) newvalue = newvalue.Replace(@"\u8209?", "-"); else - newvalue = newvalue.Replace(@"\u8209?", m.Groups[1].Value + @"\u8209?" + m.Groups[3].Value); + newvalue = newvalue.Replace(@"\u8209?", $@"{m.Groups[1].Value}\u8209?{m.Groups[3].Value}"); } //B2024-003, B2023-113, B2024-093 - Updating RO Values inside a text Grid, // This will handle if there is a delta and the column/row of the grid is removed @@ -1425,7 +1242,7 @@ namespace VEPROMS.CSLA.Library else if (m.Groups.Count < 3) newvalue = newvalue.Replace(@"\u916?", $"{(char)916}"); else - newvalue = newvalue.Replace(@"\u916?", m.Groups[1].Value + @"\u916?" + m.Groups[3].Value); + newvalue = newvalue.Replace(@"\u916?", $@"{m.Groups[1].Value}\u916?{m.Groups[3].Value}"); } if (newvalue.Contains(@"\u8593?")) { @@ -1433,7 +1250,7 @@ namespace VEPROMS.CSLA.Library if (m.Groups.Count < 3) newvalue = newvalue.Replace(@"\u8593?", "^"); else - newvalue = newvalue.Replace(@"\u8593?", m.Groups[1].Value + @"\u8593?" + m.Groups[3].Value); + newvalue = newvalue.Replace(@"\u8593?", $@"{m.Groups[1].Value}\u8593?{m.Groups[3].Value}"); } if (newvalue.Contains(@"\u9586?")) @@ -1442,7 +1259,7 @@ namespace VEPROMS.CSLA.Library if (m.Groups.Count < 3) newvalue = newvalue.Replace(@"\u9586?", @"\\"); else - newvalue = newvalue.Replace(@"\u9586?", m.Groups[1].Value + @"\u9586?" + m.Groups[3].Value); + newvalue = newvalue.Replace(@"\u9586?", $@"{m.Groups[1].Value}\u9586?{m.Groups[3].Value}"); } // B2022-064: Translate '<' to '<', '<' is xml token, so xml grid string was incorrect for print. // Note that the '>' symbol was also translated. This method does NOT save the string to database, @@ -1469,24 +1286,18 @@ namespace VEPROMS.CSLA.Library _Text = "?"; } - // C2021-018 used to update the content record when displaying Alarm Pont Table information in the step Editor (BNPP alarms) - public void UpdateAlarmTableInfoView(string updateText) - { - _Text = updateText; - } + // C2021-018 used to update the content record when displaying Alarm Pont Table information in the step Editor (BNPP alarms) + public void UpdateAlarmTableInfoView(string updateText) => _Text = updateText; - public void LoadNonCachedGrid() + public void LoadNonCachedGrid() { _MyGrid = GridInfo.GetNonCached(ContentID); //Console.WriteLine("LoadNonCachedGrid {0},{1},{2}",ContentID,_MyGrid==null,_MyContentInfoUnique); } - public PartInfoList LocalContentParts - { - get { return _ContentParts; } - } + public PartInfoList LocalContentParts => _ContentParts; - public void AddPart(SafeDataReader dr, ItemInfo itemInfo) + public void AddPart(SafeDataReader dr, ItemInfo itemInfo) { if (_ContentParts == null) _ContentParts = new PartInfoList(dr, itemInfo); @@ -1494,17 +1305,11 @@ namespace VEPROMS.CSLA.Library _ContentParts.AddPartInfo(dr, itemInfo); } - public override string ToString() - { - return string.Format("{0} {1}", Number, Text); - } + public override string ToString() => $"{Number} {Text}"; - public void ShowChange() - { - OnChange(); - } + public void ShowChange() => OnChange(); - internal ContentInfo(SafeDataReader dr, bool ForItem) + internal ContentInfo(SafeDataReader dr, bool ForItem) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentInfo.Constructor", GetHashCode()); @@ -1587,7 +1392,7 @@ namespace VEPROMS.CSLA.Library private void DataPortal_Fetch(ContentListCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) @@ -1604,7 +1409,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -1616,7 +1421,7 @@ namespace VEPROMS.CSLA.Library Database.LogException("ContentInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } public static ContentInfoList GetChangedList(byte[] lastChanged) @@ -1624,7 +1429,6 @@ namespace VEPROMS.CSLA.Library try { ContentInfoList tmp = DataPortal.Fetch(new ChangeListCriteria(lastChanged)); - // ContentInfo.AddList(tmp); tmp.AddEvents(); return tmp; } @@ -1651,7 +1455,7 @@ namespace VEPROMS.CSLA.Library private void DataPortal_Fetch(ChangeListCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) @@ -1668,7 +1472,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -1680,7 +1484,7 @@ namespace VEPROMS.CSLA.Library Database.LogException("ContentInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ContentInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #region ClearCBOverride @@ -1725,7 +1529,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -1760,29 +1564,15 @@ namespace VEPROMS.CSLA.Library { public ClearOverrideFormatsByDocVersionCriteria(string dvlist, int? formatID, int? newformatID) { - _FormatID = formatID; - _DVList = dvlist; - _NewFormatID = newformatID; + FormatID = formatID; + DVList = dvlist; + NewFormatID = newformatID; } - private int? _FormatID; - public int? FormatID - { - get { return _FormatID; } - set { _FormatID = value; } - } - private int? _NewFormatID; - public int? NewFormatID - { - get { return _NewFormatID; } - set { _NewFormatID = value; } - } - private string _DVList; - public string DVList - { - get { return _DVList; } - set { _DVList = value; } - } - } + + public int? FormatID { get; set; } + public int? NewFormatID { get; set; } + public string DVList { get; set; } + } private void DataPortal_Fetch(ClearOverrideFormatsByDocVersionCriteria criteria) { @@ -1810,7 +1600,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -1841,29 +1631,15 @@ namespace VEPROMS.CSLA.Library { public ClearOverrideFormatsByItemCriteria(int itemID, int? formatID, int? newformatID) { - _FormatID = formatID; - _NewFormatID = newformatID; - _ItemID = itemID; + FormatID = formatID; + NewFormatID = newformatID; + ItemID = itemID; } - private int? _FormatID; - public int? FormatID - { - get { return _FormatID; } - set { _FormatID = value; } - } - private int? _NewFormatID; - public int? NewFormatID - { - get { return _NewFormatID; } - set { _NewFormatID = value; } - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - } + + public int? FormatID { get; set; } + public int? NewFormatID { get; set; } + public int ItemID { get; set; } + } private void DataPortal_Fetch(ClearOverrideFormatsByItemCriteria criteria) { @@ -1891,7 +1667,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -1975,7 +1751,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -2005,7 +1781,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -2069,7 +1845,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -2146,7 +1922,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } @@ -2222,7 +1998,7 @@ namespace VEPROMS.CSLA.Library while (dr.Read()) { ContentInfo contentInfo = new ContentInfo(dr); - this.Add(contentInfo); + Add(contentInfo); } IsReadOnly = true; } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DROUsagesExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DROUsagesExt.cs index f6c37d66..52d9e703 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DROUsagesExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DROUsagesExt.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; using Csla; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DisplayText.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DisplayText.cs index 36e70e49..4c6fe929 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DisplayText.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DisplayText.cs @@ -3,12 +3,10 @@ using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; -using System.Drawing; using Volian.Base.Library; using JR.Utils.GUI.Forms; -//using VEPROMS.colorReplaceWords; +using System.Linq; -// This was moved from volian.controls.library namespace VEPROMS.CSLA.Library { public enum E_FieldToEdit { StepText, Text, Number, PSI }; @@ -23,19 +21,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region Properties public static int RemoveTrailingBlankID = -1; - private bool _setDTS = true; // Added for when data is cleaned so that DTS/UserID are not reset (for B2016-037 fix) - public bool SetDTS - { - get { return _setDTS; } - set { _setDTS = value; } - } - private E_FieldToEdit _FieldToEdit; - public E_FieldToEdit FieldToEdit - { - get { return _FieldToEdit; } - set { _FieldToEdit = value; } - } - private ItemInfo _MyItemInfo; + + public bool SetDTS { get; set; } = true; + public E_FieldToEdit FieldToEdit { get; set; } + private readonly ItemInfo _MyItemInfo; private string InfoText { get @@ -45,24 +34,15 @@ namespace VEPROMS.CSLA.Library case E_FieldToEdit.StepText: case E_FieldToEdit.Text: return _MyItemInfo.MyContent.Text; - break; case E_FieldToEdit.Number: return _MyItemInfo.MyContent.Number; - break; } return string.Empty; } } - private string ShwRplWords(ItemInfo _MyItemInfo) - { - //if (_Initalizing) return "N"; - //_MyItemInfo. - SectionConfig sc = _MyItemInfo.MyConfig as SectionConfig; - if (sc == null) return "N"; - return sc.Section_ShwRplWords; - } - // C2019-025 c2025-010 Ability-to-Toggle-Replace-Words - private bool ShwRplWdsIndex(ItemInfo _MyItemInfo) + private string ShwRplWords(ItemInfo _MyItemInfo) => !(_MyItemInfo.MyConfig is SectionConfig sc) ? "N" : sc.Section_ShwRplWords; + // C2019-025 c2025-010 Ability-to-Toggle-Replace-Words + private bool ShwRplWdsIndex(ItemInfo _MyItemInfo) { StepConfig sc = _MyItemInfo.MyConfig as StepConfig; int setting = sc.Step_ShwRplWdsIndex; @@ -70,25 +50,12 @@ namespace VEPROMS.CSLA.Library { case (int)ReplaceWords.DoNotShow: return false; - break; case (int)ReplaceWords.Show: return true; - break; case (int)ReplaceWords.Inherit: - //SectionConfig sc2 = _MyItemInfo.ActiveParent.MyConfig as SectionConfig; - SectionConfig sc2 = _MyItemInfo.ActiveSection.MyConfig as SectionConfig; - if (sc2 == null || sc2.Section_ShwRplWords == "Y") - { - return true; - } - else - { - return false; - } - break; - default: + return !(_MyItemInfo.ActiveSection.MyConfig is SectionConfig sc2) || sc2.Section_ShwRplWords == "Y"; + default: return false; - break; } } @@ -102,10 +69,8 @@ namespace VEPROMS.CSLA.Library case E_FieldToEdit.StepText: case E_FieldToEdit.Text: return _MyItem.MyContent.Text; - break; case E_FieldToEdit.Number: return _MyItem.MyContent.Number; - break; } return string.Empty; } @@ -132,33 +97,14 @@ namespace VEPROMS.CSLA.Library } } } - // list of 'pieces of text' for this item. Pieces include symbols, ros, - // transitions & plain text. - private List _DisplayTextElementList; - public List DisplayTextElementList - { - get { return _DisplayTextElementList; } - set { _DisplayTextElementList = value; } - } - // dictionary for the font table for this item. Note that this may - // go away (it is not really used). - private Dictionary _dicRtfFontTable; - public Dictionary dicRtfFontTable - { - get { return _dicRtfFontTable; } - set { _dicRtfFontTable = value; } - } - private VE_Font _textFont; // Font from format for this item - public VE_Font TextFont - { - get { return _textFont; } - set { _textFont = value; } - } - private bool PrintingSmartTemplate = false; - public string StartText; + + public List DisplayTextElementList { get; set; } + public Dictionary dicRtfFontTable { get; set; } + public VE_Font TextFont { get; set; } + public string StartText; public string OriginalText; // compare for save to see if change for links. public bool AddedDefaultTextFromFmt = false; - private FormatInfo _MyFormat; + private readonly FormatInfo _MyFormat; #endregion #region Constructors /// @@ -176,7 +122,7 @@ namespace VEPROMS.CSLA.Library public DisplayText(ItemInfo itemInfo, E_EditPrintMode epMode, E_ViewMode vwMode, bool noEdit,E_FieldToEdit fieldToEdit, bool colorLinks, string prefix, string suffix, bool RemoveTrailingHardReturnAndManualPageBreaks) { int profileDepth = ProfileTimer.Push(">>>> DisplayText"); - _FieldToEdit = fieldToEdit; + FieldToEdit = fieldToEdit; _MyItemInfo = itemInfo; OriginalText = epMode == E_EditPrintMode.Print && RemoveTrailingHardReturnAndManualPageBreaks ? Regex.Replace(InfoText, "(\\\\line|\r|\n|\\\\u160\\?| )+$", "") : InfoText; @@ -196,7 +142,6 @@ namespace VEPROMS.CSLA.Library else OriginalText = InfoText; } - //OriginalText = InfoText; //if (OriginalText != InfoText) Console.WriteLine("ItemId = {0}, {1}", itemInfo.ItemID, OriginalText.Length-InfoText.Length); if (OriginalText.Contains("Prerequisite") && epMode == E_EditPrintMode.Print) OriginalText = Regex.Replace(OriginalText, @"\\{Prerequisite Step: .*?\\}", ""); @@ -218,17 +163,15 @@ namespace VEPROMS.CSLA.Library string text = prefix + OriginalText + suffix; _MyFormat = itemInfo.ActiveFormat; - bool tableShouldBeOutlined = false; //(epMode == E_EditPrintMode.Print || vwMode == E_ViewMode.View || noEdit) && - //(_FieldToEdit == E_FieldToEdit.StepText || _FieldToEdit == E_FieldToEdit.Text) && - //(!itemInfo.IsSection && !itemInfo.IsProcedure) && (itemInfo.IsTable || itemInfo.IsFigure); + bool tableShouldBeOutlined = false; bool wordsShouldBeReplaced = epMode == E_EditPrintMode.Print || vwMode == E_ViewMode.View || noEdit; if (_MyFormat == null) Console.WriteLine(this._MyItemInfo.MyItemInfoUnique); bool numbersShouldBeFormated = (!_MyFormat.PlantFormat.FormatData.SectData.StepSectionData.FortranFormatNumbers && (epMode == E_EditPrintMode.Print || vwMode == E_ViewMode.View || noEdit)); int typ = ((int)itemInfo.MyContent.Type) % 10000; - bool tableHasBorder = tableShouldBeOutlined ? itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[typ].Type.IndexOf(@"Borderless") < 0 : false; + bool tableHasBorder = tableShouldBeOutlined && itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[typ].Type.IndexOf(@"Borderless") < 0; bool ROsShouldBeAdjusted = wordsShouldBeReplaced; // same logical value - bool underlineAfterDashSpace = (itemInfo.FormatStepData == null) ? false : itemInfo.FormatStepData.UnderlineAfterDashSpace; + bool underlineAfterDashSpace = itemInfo.FormatStepData != null && itemInfo.FormatStepData.UnderlineAfterDashSpace; if (epMode == E_EditPrintMode.Print && _MyItemInfo.IsStep) { if (_MyItemInfo.FormatStepData.UseSmartTemplate) @@ -240,7 +183,7 @@ namespace VEPROMS.CSLA.Library text = !_MyItemInfo.FormatStepData.Font.FontIsProportional() ? ReplaceLinesWithUnicode(_MyItemInfo.FormatStepData.Prefix) + @"\par " + text + @"\par " : @"\par " + text + @"\par "; if (_MyItemInfo.FormatStepData.Suffix != null && _MyItemInfo.FormatStepData.Suffix != "") - text = text + (!_MyItemInfo.FormatStepData.Font.FontIsProportional() ? ReplaceLinesWithUnicode(_MyItemInfo.FormatStepData.Suffix) : + text += (!_MyItemInfo.FormatStepData.Font.FontIsProportional() ? ReplaceLinesWithUnicode(_MyItemInfo.FormatStepData.Suffix) : @"\par\par\par "); } } @@ -307,11 +250,11 @@ namespace VEPROMS.CSLA.Library // F2021-053: BNPP Alarm - need ability to have super/sub scripts in the text of Alarm Tables (ROs). Added a // constructor that allows for passing in a flag to set whether replace words should be done on page list. If doing // on page list, the object has a section not a step associated with it. - private bool _DoReplWordInPageList = false; + private readonly bool _DoReplWordInPageList = false; public DisplayText(ItemInfo itemInfo, string text, bool colorLinks, bool dorepl) { _DoReplWordInPageList = dorepl; - _FieldToEdit = E_FieldToEdit.Text; + FieldToEdit = E_FieldToEdit.Text; _MyItemInfo = itemInfo; OriginalText = text; TextFont = itemInfo.GetItemFont(); @@ -319,16 +262,15 @@ namespace VEPROMS.CSLA.Library bool wordsShouldBeReplaced = true; bool numbersShouldBeFormated = !_MyFormat.PlantFormat.FormatData.SectData.StepSectionData.FortranFormatNumbers; - int typ = ((int)itemInfo.MyContent.Type) % 10000; bool ROsShouldBeAdjusted = wordsShouldBeReplaced; // same logical value - bool underlineAfterDashSpace = (itemInfo.FormatStepData == null) ? false : itemInfo.FormatStepData.UnderlineAfterDashSpace; + bool underlineAfterDashSpace = itemInfo.FormatStepData != null && itemInfo.FormatStepData.UnderlineAfterDashSpace; text = CreateRtf(colorLinks, text, false, wordsShouldBeReplaced, numbersShouldBeFormated, false, ROsShouldBeAdjusted, underlineAfterDashSpace, E_EditPrintMode.Edit); StartText = text; } public DisplayText(ItemInfo itemInfo, string text, bool colorLinks) { - _FieldToEdit = E_FieldToEdit.Text; + FieldToEdit = E_FieldToEdit.Text; _MyItemInfo = itemInfo; OriginalText = text; TextFont = itemInfo.GetItemFont(); @@ -336,9 +278,8 @@ namespace VEPROMS.CSLA.Library bool wordsShouldBeReplaced = true; bool numbersShouldBeFormated = !_MyFormat.PlantFormat.FormatData.SectData.StepSectionData.FortranFormatNumbers; - int typ = ((int)itemInfo.MyContent.Type) % 10000; bool ROsShouldBeAdjusted = wordsShouldBeReplaced; // same logical value - bool underlineAfterDashSpace = (itemInfo.FormatStepData == null) ? false : itemInfo.FormatStepData.UnderlineAfterDashSpace; + bool underlineAfterDashSpace = itemInfo.FormatStepData != null && itemInfo.FormatStepData.UnderlineAfterDashSpace; text = CreateRtf(colorLinks, text, false, wordsShouldBeReplaced, numbersShouldBeFormated, false, ROsShouldBeAdjusted, underlineAfterDashSpace, E_EditPrintMode.Edit); StartText = text; @@ -473,15 +414,8 @@ namespace VEPROMS.CSLA.Library //text = text.Replace(@"\~", @"\u160?"); // convert \'99 to \u8482? this is for the trade mark symbol. For some reason RTF is automatically // converting the unicode \u8482? to \'99, but once this is done, PROMS StepRTB (edit windows) do not show it - //text = text.Replace(@"\'99", @"\u8482?"); text = RtfTools.RTFConvertedSymbolsToUnicode(text); text = text.Replace("\r\n", @"\line "); // replace a \r\n with a \line instead of a \par - // B2015-134 Hanging Indent with Hard Returns was not being saved - //text = text.Replace(@"\line", @"\pard\line"); - //text = text.Replace(@"\pard\pard\line", @"\pard\line"); - //if (text.IndexOf(@"\line") > -1) - // MessageBox.Show("Found rtf line"); - //text = text.Replace(@"\line", @"\par"); // we don't want to replace the \line part of bug fix B2015-140 // Now put symbol (for fixed fonts) or unicode font (proportional) around symbols // These fonts are VESymbFix & Arial Unicode MS respectively, and the font table @@ -593,7 +527,6 @@ namespace VEPROMS.CSLA.Library // ReplaceStrData xml node is empty, it does the inheritance and gets the 'base' format's list. if (rsl.Count == 1 && (rsl[0].ReplaceWord == null || rsl[0].ReplaceWord == "")) return text; // Loop through text looking for words to be replaced - List partialReplaceList = new List(); foreach (ReplaceStr rs in rsl) { if (rs.ReplaceWord.Contains("{RO}")) @@ -612,8 +545,8 @@ namespace VEPROMS.CSLA.Library } } } - return text; - } + return text; + } private string ReplaceOppositeUnitRO(string text, string replaceWord2, string replaceWith) { @@ -626,25 +559,12 @@ namespace VEPROMS.CSLA.Library { text = text.Substring(0, offset + m.Index) + replaceWith + text.Substring(offset + m.Index + m.Length); len = replaceWith.Length; - //text = text.Replace(replaceWord2, rs.ReplaceWith.Replace(@"\xA0",@"\'A0") + @"\v"); } offset += m.Index + len; m = Regex.Match(text.Substring(offset), replaceWord2, RegexOptions.IgnoreCase); } return text; } - private Match FirstMatch(string text, string replaceWord2) - { - //if(text.Contains(replaceWord2.Replace("(","").Replace(")","").Replace(@"\\",@"\"))) - // Console.WriteLine("here"); - MatchCollection matches = Regex.Matches(text, replaceWord2, RegexOptions.IgnoreCase); - if (matches.Count > 0) - { - Match mm = Regex.Match(text, replaceWord2, RegexOptions.IgnoreCase); - return matches[0]; - } - return null; - } private int FindUnderlineTerminator(string text) { int idx = -1; @@ -661,24 +581,18 @@ namespace VEPROMS.CSLA.Library } return idx; } - private string DoSearchAndReplace(string text, string find, string replace) - { - return text.Replace(find, replace); - } private static string DoColorLinks(string text) { string origtext = text; text = Regex.Replace(text, @"( -1) + int indxend = text.IndexOf(@"\v", indxcf); + if (indxend > -1) { text = text.Insert(indxend, @"\cf0"); indxcf = text.IndexOf(@"\v0\cf1", indxend); @@ -690,8 +604,8 @@ namespace VEPROMS.CSLA.Library } } } - catch (Exception ex) - { + catch (Exception) + { _MyLog.WarnFormat("DisplayText.DoColorLinks Failed\r\norgitext:'{0}'\r\ntext'{1}'", origtext, text); } return text; @@ -713,15 +627,17 @@ namespace VEPROMS.CSLA.Library { // B2018-088 - Added code to look for CROUSGID Regex regRefObj = new Regex(@"\#Link\:ReferencedObject:([0-9]*||) ([0-9a-zA-Z]*) ([0-9]*)", RegexOptions.Singleline); - string strippedText = StaticStripRtfCommands(text, _MyItemInfo!=null?_MyItemInfo.IsTable:false); - // (\\[^v \\]+)* --> look for any rtf commands (first part of lookFor) - // \\v0 --> end of comment - // (\\[^v \\]+)* --> more rtf commands ended by a space - // (.*?) --> smallest anything to that matches this based on what's next - // (\\[^v' \\]+)* --> look for rtf commands but exclude \' before the \v - // \\v(\\[^v \\]+)* --> look for rtf commands after the \v - // if it turns out that if ro's have any embedded unicode characters this needs expanded, such as /u8209? (hard hyphen) - string lookFor = string.Format(@""); +#pragma warning disable IDE0059 // Unnecessary assignment of a value + string strippedText = StaticStripRtfCommands(text, _MyItemInfo != null && _MyItemInfo.IsTable); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + // (\\[^v \\]+)* --> look for any rtf commands (first part of lookFor) + // \\v0 --> end of comment + // (\\[^v \\]+)* --> more rtf commands ended by a space + // (.*?) --> smallest anything to that matches this based on what's next + // (\\[^v' \\]+)* --> look for rtf commands but exclude \' before the \v + // \\v(\\[^v \\]+)* --> look for rtf commands after the \v + // if it turns out that if ro's have any embedded unicode characters this needs expanded, such as /u8209? (hard hyphen) + string lookFor = string.Format(@""); MatchCollection matches = Regex.Matches(text, lookFor); string prevValue = null; for (int i = matches.Count - 1; i >= 0; i--) @@ -729,24 +645,16 @@ namespace VEPROMS.CSLA.Library Match m = matches[i]; if (m != null && m.Groups.Count > 7 && m.Groups[7].ToString() == "ReferencedObject") { - // if previous processed (next ro) was found, then see if it has an 'and' between it and the previous - //if (prevValue != null) - //{ - // int endIndx = m.Index + m.Length; - // string tr = text.Substring(endIndx).Replace(@"\v0","").TrimStart(); - // if (!tr.ToUpper().StartsWith("AND")) prevValue = null; - //} - int myIndex = m.Groups[4].Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index; - myLength += m.Groups[3].Length; - } - string gg = text.Substring(myIndex, myLength).TrimEnd(" ".ToCharArray());// RHM 20180608 - Found an issue where the value contained a trailing space - //System.Text.RegularExpressions.Group g = m.Groups[3]; - string beforeRO = StaticStripRtfCommands(text.Substring(0, myIndex), _MyItemInfo != null ? _MyItemInfo.IsTable : false); - string afterRO = StaticStripRtfCommands(text.Substring(myIndex + myLength), _MyItemInfo != null ? _MyItemInfo.IsTable : false); + int myIndex = m.Groups[4].Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index; + myLength += m.Groups[3].Length; + } + string gg = text.Substring(myIndex, myLength).TrimEnd(" ".ToCharArray());// RHM 20180608 - Found an issue where the value contained a trailing space + string beforeRO = StaticStripRtfCommands(text.Substring(0, myIndex), _MyItemInfo != null && _MyItemInfo.IsTable); + string afterRO = StaticStripRtfCommands(text.Substring(myIndex + myLength), _MyItemInfo != null && _MyItemInfo.IsTable); Match myMatch = regRefObj.Match(m.ToString()); // B-2018-088 Made Error Log output more useful if (m.ToString().ToUpper().Contains("") || m.ToString().ToUpper().Contains("= 0) @@ -823,7 +729,7 @@ namespace VEPROMS.CSLA.Library } } lstindx = spindx; - spindx = (spindx + 1 >= newvalue.Length)?spindx = -1: newvalue.IndexOf(" ", spindx+1); + spindx = (spindx + 1 >= newvalue.Length)? -1 : newvalue.IndexOf(" ", spindx+1); } return newvalue; } @@ -862,8 +768,10 @@ namespace VEPROMS.CSLA.Library { int profileDepth = ProfileTimer.Push(">>>> DoTransitionAdjustments"); bool undtran = _MyItemInfo.ActiveFormat.PlantFormat.FormatData.TransData.Underline; - string strippedText = StaticStripRtfCommands(text, _MyItemInfo != null ? _MyItemInfo.IsTable : false); - string lookFor = string.Format(@""); +#pragma warning disable IDE0059 // Unnecessary assignment of a value + string strippedText = StaticStripRtfCommands(text, _MyItemInfo != null && _MyItemInfo.IsTable); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + string lookFor = string.Format(@""); MatchCollection matches = Regex.Matches(text, lookFor); if (matches.Count == 0) { @@ -877,21 +785,19 @@ namespace VEPROMS.CSLA.Library // if this transition text already has a hard space, don't add another. if (m.Groups[4].Value.Contains("\xA0")) continue; // if the transition text does not start with a digit, don't add the hardspace. - //if (!Char.IsDigit(m.Groups[3].Value[0])) continue; if (m != null && m.Groups.Count > 8 && m.Groups[7].ToString().StartsWith("Transition")) { if (m.Groups[8].Value != "") // && StepTransition(int.Parse(m.Groups[7].Value))) { - int myIndex = m.Groups[4].Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index; - myLength += m.Groups[3].Length; - } - string newvalue = text.Substring(myIndex, myLength); + int myIndex = m.Groups[4].Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index; + myLength += m.Groups[3].Length; + } + string newvalue = text.Substring(myIndex, myLength); if (boldTran) newvalue = newvalue.Replace(@"\b0", "").Replace(@"\B0", ""); - //System.Text.RegularExpressions.Group g = m.Groups[3]; string beforeTran = retstr.Substring(0, myIndex); string afterTran = retstr.Substring(myIndex + myLength); @@ -899,7 +805,6 @@ namespace VEPROMS.CSLA.Library // i.e. there is a format flag 'BeforeTrans' that bolds text before the transition // (in wst formats). beforeTran = DoBeforeTransFlagSupport(beforeTran, _MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.ReplaceStrList); - //string newvalue = g.ToString(); // if this is a 'step transition' type, i.e. includes a step number, in addition to other replacements, // we want to change a space to a hardspace. if (StepTransition(int.Parse(m.Groups[8].Value))) @@ -918,7 +823,7 @@ namespace VEPROMS.CSLA.Library } else if (boldTran) { - retstr = beforeTran + @"\b " + newvalue + @"\b0" + afterTran; + retstr = $@"{beforeTran}\b {newvalue}\b0{afterTran}"; } } } @@ -941,7 +846,6 @@ namespace VEPROMS.CSLA.Library string findit = beforeTran.Substring(0, beforeTran.LastIndexOf(@"\v /// B2017-121 Regular Express for all RTF tokens for Hyphens /// - private static Regex regHyphen = new Regex(@"(?", "\\\\"); // if there are links, we'll need to do extra processing to see if // there were additions, deletions or modifications. @@ -1097,7 +999,7 @@ namespace VEPROMS.CSLA.Library if (!dvsLinked) { string destProcNumber = tran.MyItemToID.MyProcedure.DisplayNumber; - foreach (ProcedureInfo prci in tran.MyContent.ContentItems[0].MyDocVersion.Procedures) + foreach (ProcedureInfo prci in tran.MyContent.ContentItems[0].MyDocVersion.Procedures.OfType()) { if (prci.DisplayNumber == destProcNumber) { @@ -1129,9 +1031,6 @@ namespace VEPROMS.CSLA.Library { Console.WriteLine("{0} - {1}", br.Property, br.Description); } - // Don't update the DTS or User for Text Changes - //_MyItem.DTS = DateTime.Now; - //_MyItem.UserID = Volian.Base.Library.VlnSettings.UserID; _MyItem.Save(); } _MyItem = null; @@ -1148,7 +1047,6 @@ namespace VEPROMS.CSLA.Library Console.WriteLine("DisplayText Save Failed with error: {0} - {1}\r\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace); return false; } - //rtb.SelectionStart = savSelStart; return true; } private string DteToString() @@ -1320,26 +1218,26 @@ namespace VEPROMS.CSLA.Library if(tparts.Length > 3) tr2 = System.Convert.ToInt32(tparts[3]); // tparts[3] is token for rangeid bool dispose1 = false; - Item itm1 = null; - bool dispose2 = false; - Item itm2 = null; - if (itm.ItemID == tr1) - itm1 = itm; // a transition that points to itself should not dispose - else - { - dispose1 = true; - itm1 = Item.Get(tr1); - } - if (itm.ItemID == tr2) - itm2 = itm; // a transition that points to itself should not dispose - else if (tr1 == tr2) - itm2 = itm1; // if both destinations are the same only dispose the first one - else - { - dispose2 = true; - itm2 = Item.Get(tr2); - } - ContentTransition ct = itm.MyContent.ContentTransitions.Add(itm1, itm2); + bool dispose2 = false; + Item itm1; + if (itm.ItemID == tr1) + itm1 = itm; // a transition that points to itself should not dispose + else + { + dispose1 = true; + itm1 = Item.Get(tr1); + } + Item itm2; + if (itm.ItemID == tr2) + itm2 = itm; // a transition that points to itself should not dispose + else if (tr1 == tr2) + itm2 = itm1; // if both destinations are the same only dispose the first one + else + { + dispose2 = true; + itm2 = Item.Get(tr2); + } + ContentTransition ct = itm.MyContent.ContentTransitions.Add(itm1, itm2); //Console.WriteLine("CT {0},{1},{2},{3}", ct.TransitionID, itm.ItemID, itm.MyContent.MyContentUnique, itm.MyContent.ContentTransitions.Count); ct.TranType = type; if (dte.Type == E_TextElementType.Transition) @@ -1368,11 +1266,13 @@ namespace VEPROMS.CSLA.Library if (vte.Type == E_TextElementType.ReferencedObject || vte.Type == E_TextElementType.TransitionRange || vte.Type == E_TextElementType.Transition) { displayLinkElement tmp = (displayLinkElement)vte; - displayLinkElement copy_vte = new displayLinkElement(); - copy_vte.Type = tmp.Type; - copy_vte.Link = tmp.Link; - copy_vte.Text = tmp.Text; - retList.Add(copy_vte); + displayLinkElement copy_vte = new displayLinkElement + { + Type = tmp.Type, + Link = tmp.Link, + Text = tmp.Text + }; + retList.Add(copy_vte); } } return retList; @@ -1390,22 +1290,22 @@ namespace VEPROMS.CSLA.Library string noExtraRtfStr = text; int startIndex = 0; - int index = -1; - noExtraRtfStr = noExtraRtfStr.Replace(@"><", @">\v0 \v <"); - while ((index = FindTokenChar(noExtraRtfStr, startIndex)) > -1) - { - // Do any 'plain' text that preceeds the token. - if (index > startIndex) DoTextElement(noExtraRtfStr, startIndex, index); + noExtraRtfStr = noExtraRtfStr.Replace(@"><", @">\v0 \v <"); + int index; + while ((index = FindTokenChar(noExtraRtfStr, startIndex)) > -1) + { + // Do any 'plain' text that preceeds the token. + if (index > startIndex) DoTextElement(noExtraRtfStr, startIndex, index); - if (noExtraRtfStr[index + 1] == 'v') - index = DoLink(noExtraRtfStr, index); - else - index = DoSymbol(noExtraRtfStr, startIndex, index); - startIndex = index; // +1; - if (startIndex >= noExtraRtfStr.Length) break; - } - // Add any remaining text. - if (startIndex < noExtraRtfStr.Length) DoTextElement(noExtraRtfStr, startIndex, index); + if (noExtraRtfStr[index + 1] == 'v') + index = DoLink(noExtraRtfStr, index); + else + index = DoSymbol(noExtraRtfStr, index); + startIndex = index; // +1; + if (startIndex >= noExtraRtfStr.Length) break; + } + // Add any remaining text. + if (startIndex < noExtraRtfStr.Length) DoTextElement(noExtraRtfStr, startIndex, index); } private string RtfToDbText(string text) { @@ -1415,21 +1315,13 @@ namespace VEPROMS.CSLA.Library // Note that if the \~ is sent to the rtb, it is treated as a regular space, // i.e. no longer a hardspace, and actually is converted to a regular space. // SO, on the way out, convert any \~ to \u160? - //string noExtraRtfStr = text.Replace(@"\~", @"\u160?"); - //noExtraRtfStr = noExtraRtfStr.Replace(@"\'a0", @"\u160?"); // convert \'99 to \u8482? this is for the trade mark symbol. For some reason RTF is automatically // converting the unicode \u8482? to \'99, but once this is done, PROMS StepRTB (edit windows) do not show it - //noExtraRtfStr = noExtraRtfStr.Replace(@"\'99", @"\u8482?"); - + string noExtraRtfStr = RtfTools.RTFConvertedSymbolsToUnicode(text); // Check for two links in a row & if found, add separating rtf comment // commands (these get removed in the richtextbox: // RHM 20100303 Not sure why this is here. The RichTextBox will always remove it. - //noExtraRtfStr = noExtraRtfStr.Replace(@"[END>\v0 \v = 6 && token.Substring(0, 6) == "\\par\r\n") return token.Replace("\r\n", " "); break; - //case 'f': // handle fonts separately because they may or may not have a space after them - // if (token[2] >= '0' && token[2] <= '9') return token; - // break; } } catch (Exception ex) @@ -1512,15 +1396,15 @@ namespace VEPROMS.CSLA.Library } return "";//Strip All } - private static Regex reg1 = new Regex(@"\\par\r\n(?!\\)"); - private static Regex reg2 = new Regex(@"[\r\n]", RegexOptions.Singleline); // Strip Carriage Returns and Newlines - private static Regex reg3 = new Regex(@"^\{(.*)\}$", RegexOptions.Singleline); // Strip Opening and Closing Braces - private static Regex reg4 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - private static Regex reg5 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - private static Regex reg6 = new Regex(@"(\\[^' \\?\r\n\t]+)(?=\\)"); // add space after token if followed by token - private static Regex reg7 = new Regex(@"(\\[^' \\?\r\n\t]+ )"); // take backslash xyz and evaluates them - private static Regex reg8 = new Regex(@"(\\[^' \\?\r\n\t]+) (?=\\)"); // remove space between tokens - private static Regex reg9 = new Regex(@"(\\[^' \\?\r\n\t]+) (?=\r\n)"); // remove space before /r/n + private static readonly Regex reg1 = new Regex(@"\\par\r\n(?!\\)"); + private static readonly Regex reg2 = new Regex(@"[\r\n]", RegexOptions.Singleline); // Strip Carriage Returns and Newlines + private static readonly Regex reg3 = new Regex(@"^\{(.*)\}$", RegexOptions.Singleline); // Strip Opening and Closing Braces + private static readonly Regex reg4 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces + private static readonly Regex reg5 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces + private static readonly Regex reg6 = new Regex(@"(\\[^' \\?\r\n\t]+)(?=\\)"); // add space after token if followed by token + private static readonly Regex reg7 = new Regex(@"(\\[^' \\?\r\n\t]+ )"); // take backslash xyz and evaluates them + private static readonly Regex reg8 = new Regex(@"(\\[^' \\?\r\n\t]+) (?=\\)"); // remove space between tokens + private static readonly Regex reg9 = new Regex(@"(\\[^' \\?\r\n\t]+) (?=\r\n)"); // remove space before /r/n public string StripRtfCommands(string rtf) { @@ -1543,17 +1427,6 @@ namespace VEPROMS.CSLA.Library retval = reg8.Replace(retval, "$1"); // remove space between tokens retval = reg9.Replace(retval, "$1"); // remove space before /r/n - //retval = Regex.Replace(retval, @"\\par\r\n(?!\\)", "\\par "); - //retval = retval.Replace("\\v0\r\n", "\\v0 "); // Replace Carriage Return and Newline after comment - //retval = Regex.Replace(retval, @"[\r\n]", "", RegexOptions.Singleline); // Strip Carriage Returns and Newlines - //retval = Regex.Replace(retval, @"^\{(.*)\}$", "$1", RegexOptions.Singleline); // Strip Opening and Closing Braces - //retval = Regex.Replace(retval, @"\{[^{]*?\}", "", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - //retval = Regex.Replace(retval, @"\{[^{]*?\}", "", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - //retval = Regex.Replace(retval, @"(\\[^' \\?\r\n\t]+)(?=\\)", "$1 "); // add space after token if followed by token - //retval = Regex.Replace(retval, @"(\\[^' \\?\r\n\t]+ )", new MatchEvaluator(StaticReplaceRTFClause)); // take backslash xyz and evaluates them - //retval = Regex.Replace(retval, @"(\\[^' \\?\r\n\t]+) (?=\\)", "$1"); // remove space between tokens - //retval = Regex.Replace(retval, @"(\\[^' \\?\r\n\t]+) (?=\r\n)", "$1"); // remove space before /r/n - // remove \r\n at end of string if the string has 2 or more characters if (retval.EndsWith("\r\n")) retval = retval.Remove(retval.Length - 2, 2); if (retval.Length == 0) return ""; @@ -1563,15 +1436,15 @@ namespace VEPROMS.CSLA.Library return retval; } - private static Regex sreg1 = new Regex(@"\\par\r\n(?!\\)"); - private static Regex sreg2 = new Regex(@"[\r\n]", RegexOptions.Singleline); // Strip Carriage Returns and Newlines - private static Regex sreg3 = new Regex(@"^\{(.*)\}$", RegexOptions.Singleline); // Strip Opening and Closing Braces - private static Regex sreg4 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - private static Regex sreg5 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - private static Regex sreg6 = new Regex(@"(\\[^' \\?\r\n\t]+)(?=\\)"); // add space after token if followed by token - private static Regex sreg7 = new Regex(@"(\\[^ \\?\r\n\t]+ )"); // take backslash xyz and evaluates them - private static Regex sreg8 = new Regex(@"(\\[^ \\?\r\n\t]+) (?=\\)"); // remove space between tokens - private static Regex sreg9 = new Regex(@"(\\[^ \\?\r\n\t]+) (?=\r\n)"); // remove space before /r/n + private static readonly Regex sreg1 = new Regex(@"\\par\r\n(?!\\)"); + private static readonly Regex sreg2 = new Regex(@"[\r\n]", RegexOptions.Singleline); // Strip Carriage Returns and Newlines + private static readonly Regex sreg3 = new Regex(@"^\{(.*)\}$", RegexOptions.Singleline); // Strip Opening and Closing Braces + private static readonly Regex sreg4 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces + private static readonly Regex sreg5 = new Regex(@"\{[^{]*?\}", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces + private static readonly Regex sreg6 = new Regex(@"(\\[^' \\?\r\n\t]+)(?=\\)"); // add space after token if followed by token + private static readonly Regex sreg7 = new Regex(@"(\\[^ \\?\r\n\t]+ )"); // take backslash xyz and evaluates them + private static readonly Regex sreg8 = new Regex(@"(\\[^ \\?\r\n\t]+) (?=\\)"); // remove space between tokens + private static readonly Regex sreg9 = new Regex(@"(\\[^ \\?\r\n\t]+) (?=\r\n)"); // remove space before /r/n // This is used in the DataLoader private static bool _fromTable = false; // C2020-001: Change Font Size in Tables - keep rtf '\fs##' for tables only @@ -1589,10 +1462,8 @@ namespace VEPROMS.CSLA.Library // Note that if the \~ is sent to the rtb, it is treated as a regular space, // i.e. no longer a hardspace, and actually is converted to a regular space. // SO, on the way out, convert any \~ to \u160? - //retval = retval.Replace(@"\~", @"\u160?"); // convert \'99 to \u8482? this is for the trade mark symbol. For some reason RTF is automatically // converting the unicode \u8482? to \'99, but once this is done, PROMS StepRTB (edit windows) do not show it - //retval = retval.Replace(@"\'99", @"\u8482?"); retval = RtfTools.RTFConvertedSymbolsToUnicode(retval); @@ -1611,44 +1482,11 @@ namespace VEPROMS.CSLA.Library retval = sreg8.Replace(retval, "$1"); // remove space between tokens retval = sreg9.Replace(retval, "$1"); // remove space before /r/n - //retval = Regex.Replace(retval, @"\\par\r\n(?!\\)", "\\par "); - ////retval = Regex.Replace(retval, @"\\par\r\n(?=\\)", "\\par"); - - //retval = retval.Replace("\\v0\r\n", "\\v0 "); // Replace Carriage Return and Newline after comment - //retval = Regex.Replace(retval, @"[\r\n]", "", RegexOptions.Singleline); // Strip Carriage Returns and Newlines - //retval = Regex.Replace(retval, @"^\{(.*)\}$", "$1", RegexOptions.Singleline); // Strip Opening and Closing Braces - //retval = Regex.Replace(retval, @"\{[^{]*?\}", "", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - //retval = Regex.Replace(retval, @"\{[^{]*?\}", "", RegexOptions.Singleline); // Strip Clauses - remove anything from curly braces - ////retval = Regex.Replace(retval, @"(\\[^ \\?\r\n\t]+)\\f[0-9] ", "$1 "); // remove font command - if next to another command, keep other command and space - //// OLD: The following two lines are replaced by the more generic replace above. - ////retval = Regex.Replace(retval, @"\\v\\f[0-9] ", "\\v "); // remove font command - if next to Comment keep space - ////retval = Regex.Replace(retval, @"\\line\\f[0-9] ", "\\line "); // remove font command - if next to Line keep space - ////retval = Regex.Replace(retval, @"\\f[0-9] ", ""); // remove font command with ending space - ////retval = Regex.Replace(retval, @"\\f[0-9]", ""); // remove font command without ending space - ////retval = Regex.Replace(retval, @"\\par ", "\r\n"); - //retval = Regex.Replace(retval, @"(\\[^' \\?\r\n\t]+)(?=\\)", "$1 "); // add space after token if followed by token - ////retval = Regex.Replace(retval, @"(\\[^ \\?\r\n\t]+)(\\)", "$1 $2"); // take backslash xyz and evaluates them - //retval = Regex.Replace(retval, @"(\\[^ \\?\r\n\t]+ )", new MatchEvaluator(StaticReplaceRTFClause)); // take backslash xyz and evaluates them - //retval = Regex.Replace(retval, @"(\\[^ \\?\r\n\t]+) (?=\\)", "$1"); // remove space between tokens - //retval = Regex.Replace(retval, @"(\\[^ \\?\r\n\t]+) (?=\r\n)", "$1"); // remove space before /r/n - - // remove a space if there is one as the first character or the last character - //if (retval[0] == ' ') retval = retval.Remove(0, 1); - //retval = retval.TrimEnd(' '); // remove \r\n at end of string if the string has 2 or more characters if (retval.Length > 1 && retval.Substring(retval.Length - 2, 2) == "\r\n") retval = retval.Remove(retval.Length - 2, 2); - // remove \par at end of string if the string has 4 or more characters - //if (retval.Length > 3 && retval.Substring(retval.Length - 4, 4) == @"\par") retval = retval.Remove(retval.Length - 4, 4); - // remove a space following \r\n - //retval = Regex.Replace(retval, "\r\n ", "\r\n"); - ////if there are still spaces following \r\n, then probable in a table - we need to put the space back - //retval = Regex.Replace(retval, "\r\n ", "\r\n "); if (retval.Length == 0) return ""; if (retval.Length > 1 && retval.Substring(retval.Length - 2, 2) == @"\v") retval = retval.Remove(retval.Length - 2, 2); - //retval = RemoveRtfStyles(retval); - //if (itmInfo != null) - // retval = StaticRemoveRtfStyles(retval, itmInfo); retval = retval.Replace(@" (![", @"\{"); retval = retval.Replace(@" (!]", @"\}"); @@ -1660,29 +1498,6 @@ namespace VEPROMS.CSLA.Library return retval; } #endregion - #region StyleData - //private VE_Font GetItemFont() - //{ - // VE_Font font = null; - // FormatInfo format = _MyItemInfo.ActiveFormat; - // int type = (int)_MyItemInfo.MyContent.Type; - // switch (type/10000) - // { - // case 0: // procedure - // font = format.PlantFormat.FormatData.Font; - // break; - // case 1: // section - // font = format.PlantFormat.FormatData.SectData.SectionHeader.Font; - // break; - // case 2: // step types - // int typindx = type - 20000; // what to do for other types rather than steps - // font = format.PlantFormat.FormatData.StepDataList[typindx].Font; - // break; - // } - // TextFont = font; - // return font; - //} - #endregion #region DoListElements private int FindTokenChar(string txt, int startIndex) { @@ -1705,37 +1520,40 @@ namespace VEPROMS.CSLA.Library } private int DoTextElement(string text, int startIndex, int index) { - displayTextElement vte = new displayTextElement(); - vte.Type = E_TextElementType.Text; - int len = (index == -1) ? text.Length - startIndex : index - startIndex; + displayTextElement vte = new displayTextElement + { + Type = E_TextElementType.Text + }; + int len = (index == -1) ? text.Length - startIndex : index - startIndex; vte.Text = text.Substring(startIndex, len); DisplayTextElementList.Add(vte); return index+1; } private int DoLink(string text, int startIndex) { - int retval = -1; - int fnd = text.IndexOf("#Link:", startIndex); - if (text.Substring(fnd + 6, 3) == "Ref") - retval = DoRO(text, startIndex); - else - retval = DoTran(text, startIndex); - return retval; + int fnd = text.IndexOf("#Link:", startIndex); + int retval; + if (text.Substring(fnd + 6, 3) == "Ref") + retval = DoRO(text, startIndex); + else + retval = DoTran(text, startIndex); + return retval; } private int DoRO(string text, int index) { - displayLinkElement vte = new displayLinkElement(); - vte.Type = E_TextElementType.ReferencedObject; - return DoLinkElements(text, index, vte); + displayLinkElement vte = new displayLinkElement + { + Type = E_TextElementType.ReferencedObject + }; + return DoLinkElements(text, index, vte); } private string FixTransition(string link, string text) { if (link.IndexOf("") != -1) return text; - //CSM B2024-078 - when a bad transition link / does not contain a number, simply return the text as-is - int transitionID; - string[] splt_link = link.Split(' '); - if (splt_link.Length < 2 || !int.TryParse(splt_link[1], out transitionID)) + //CSM B2024-078 - when a bad transition link / does not contain a number, simply return the text as-is + string[] splt_link = link.Split(' '); + if (splt_link.Length < 2 || !int.TryParse(splt_link[1], out int transitionID)) { return text; } @@ -1768,22 +1586,6 @@ namespace VEPROMS.CSLA.Library return DoLinkElements(text, index, vte); } - //private int GetLastLower(string stepText) - //{ - // // TO DO: need to check AlwaysUpperCase format setting - this was not yet converted as of 17Jun2010 - // // if (AlwaysUpperCase[steptype]) return (stepText.Length-1); - - // int idx = stepText.Length - 1; - // while (idx >= 0 && !(char.IsLower(stepText[idx]) && stepText[idx] != 's')) idx--; - // if (idx < 0) idx = stepText.Length - 1; // entire string is uppercased set return value to end of string - // return idx; - //} - - //private bool IsSpaceOrHardSpace(char ch) - //{ - // string spaces = @" \u160?"; - // return (spaces.IndexOf(ch) >= 0); - //} private string DoROFormatFlags(string roText, string beforeRO, string afterRO, bool isSetpoint) { string rtnstr = roText; @@ -1791,8 +1593,7 @@ namespace VEPROMS.CSLA.Library // should ignore other RO text. beforeRO = Regex.Replace(beforeRO, @"\", ""); // Remove any RO Values. beforeRO = Regex.Replace(beforeRO, @"(\\[^v \\]+)*\\v(\\[^v \\]+)* .*?\\v0(\\[^v \\]+)*( |$)", ""); // Remove Comments - string allUnitAfterRo = afterRO; - afterRO = Regex.Replace(afterRO, @"(\\[^v \\]+)*\\v(\\[^v \\]+)* .*?\\v0(\\[^v \\]+)*( |$)", ""); // Remove Comments + afterRO = Regex.Replace(afterRO, @"(\\[^v \\]+)*\\v(\\[^v \\]+)* .*?\\v0(\\[^v \\]+)*( |$)", ""); // Remove Comments // Underline all ROs, values and Units if (isSetpoint && _MyItemInfo.ActiveFormat.PlantFormat.FormatData.ROData.UnderlineRo) @@ -1821,23 +1622,12 @@ namespace VEPROMS.CSLA.Library if (_MyItemInfo.ActiveFormat.PlantFormat.FormatData.ROData.CapRoIfLastLower && !Regex.IsMatch(afterRO,@".*(? 0 && !IsSpaceOrHardSpace(stepText[indx])) indx--; // find character before RO - //while (indx2 <= stepText.Length && !IsSpaceOrHardSpace(stepText[indx2])) indx2++; // find character after RO - - //if (indx >= 0 && char.IsUpper(stepText[indx]) && indx2 > GetLastLower(stepText)) - // doUpCase = true; return UpperCaseUnits(rtnstr); } // If a RO follows a "- " then it will be uppercased if (_MyItemInfo.ActiveFormat.PlantFormat.FormatData.ROData.UpRoAftrDash && Regex.IsMatch(beforeRO, @".*\\u8209\?( |\\u160\?)")) { - //int indx = startLinkText - 1; - //while (indx > 0 && !IsSpaceOrHardSpace(stepText[indx])) indx--; // find character before RO - //string prefix = indx >= 7?stepText.Substring(indx-7,8):""; - //doUpCase = (prefix == @"\u8209? "); // Dash character before RO return UpperCaseUnits(rtnstr); } // For Wolf Creek, the "- " should be right before the link. This ro format flag was introduced @@ -1882,17 +1672,15 @@ namespace VEPROMS.CSLA.Library //(e.g., "25 gpm and 30 gpm" vs. "25 and 30 gpm") if (!_MyItemInfo.ActiveFormat.PlantFormat.FormatData.ROData.AllUnits && prevValue != null) { - string units = null; - //Match m = Regex.Match(prevValue, "[^0-9]"); - int ind = prevValue.LastIndexOfAny("0123456789".ToCharArray()); + int ind = prevValue.LastIndexOfAny("0123456789".ToCharArray()); if (ind>=0) { string mynum = prevValue.Substring(0, ind+1); // Handle Hex characters which are part of the Units such as the degree character if (Regex.IsMatch(mynum, @".*\\'[A-Fa-f0-9]{2,2}$")) ind -= 4; - units = prevValue.Substring(ind+1); - if (rtnstr.EndsWith(units) && units != "")// Don't do this if there are no units + string units = prevValue.Substring(ind + 1); + if (rtnstr.EndsWith(units) && units != "")// Don't do this if there are no units { rtnstr = rtnstr.Replace(units, ""); } @@ -1911,7 +1699,7 @@ namespace VEPROMS.CSLA.Library return match.Value; return match.Value.ToUpper(); } - Regex _RegExUppercaseROUnits = new Regex("(^|[^a-zA-Z])[a-zA-Z]+"); + readonly Regex _RegExUppercaseROUnits = new Regex("(^|[^a-zA-Z])[a-zA-Z]+"); private string UpperCaseUnits(string rtnstr) { // Uppercase Units @@ -1969,25 +1757,18 @@ namespace VEPROMS.CSLA.Library tmptxt = FixTransition(vte.Link, vte.Text); vte.Text = tmptxt; } - //else - //{ - // tmptxt = DoROFormatFlags(vte.Text, text, index, endLinkIndx); - // vte.Text = tmptxt; - //} // Now get the entire text & link. Account for various ending possibilities: // ends with '\v0\'; ends with '\v0 '; ends with '\v0' (end of string); // ends with '[END>' if two in a row - will have ", endLinkIndx + 3); // get past end of link int endComment = text.IndexOf(@"\v0", endToken); - - int rettoken = 0; - int retlen = 4; + int retlen = 4; if (endComment + 3 == text.Length) retlen = 3; else if (text[endComment + 3] == '\\') retlen = 3; vte.TextAndLink = text.Substring(index, endComment - index + retlen); - rettoken = endComment + retlen; - if (vte.Type != E_TextElementType.ReferencedObject) + int rettoken = endComment + retlen; + if (vte.Type != E_TextElementType.ReferencedObject) { if (vte.TextAndLink.Contains("(Resolved Transition Text)")) vte.TextAndLink = vte.TextAndLink.Replace("(Resolved Transition Text)", tmptxt); @@ -1998,162 +1779,27 @@ namespace VEPROMS.CSLA.Library DisplayTextElementList.Add(vte); return rettoken; } - private int DoSymbol(string text, int startIndex, int index) + private int DoSymbol(string text, int index) { - displayTextElement vte = new displayTextElement(); - vte.Type = E_TextElementType.Symbol; - // symbols are the unicode/rtf command. A symbol can be represented by \'xy or - // in the text from the database \uxyz?. If the \'xy is used the length of the - // symbol number will always be two, otherwise find the index of the '?' to - // find the end. - int endindx = -1; - if (text[index + 1] == '\'') endindx = index + 3; + displayTextElement vte = new displayTextElement + { + Type = E_TextElementType.Symbol + }; + // symbols are the unicode/rtf command. A symbol can be represented by \'xy or + // in the text from the database \uxyz?. If the \'xy is used the length of the + // symbol number will always be two, otherwise find the index of the '?' to + // find the end. + int endindx; + if (text[index + 1] == '\'') endindx = index + 3; else endindx = text.IndexOf("?", index); vte.Text = text.Substring(index, endindx - index + 1); DisplayTextElementList.Add(vte); return endindx+1; } - #endregion - #region ReplaceWords - #region commented out - //private string DoReplaceWords(string Text) - //{ - // ReplaceStrList rsl = _MyFormat.PlantFormat.FormatData.SectData.ReplaceStrList; - // foreach (ReplaceStr rs in rsl) - // { - // if (_MyItemInfo.MyContent.Type < 20000) return Text; // for now only replace in steps. - // bool replaceit = false; - - // if (_MyItemInfo.ItemID == 2557) Console.WriteLine("here"); - // // note that the order of this check is important. Check in this order... - // // background here - // if (_MyItemInfo.IsHigh && (rs.Flag & E_ReplaceFlags.High)>0) replaceit = true; - // else if ((_MyItemInfo.IsTable || _MyItemInfo.IsFigure) && (rs.Flag & E_ReplaceFlags.Table) > 0) replaceit = true; - // else if (_MyItemInfo.IsInRNO && (rs.Flag & E_ReplaceFlags.RNO) > 0) replaceit = true; - // else if (_MyItemInfo.IsCaution && (rs.Flag & E_ReplaceFlags.Caution) > 0) replaceit = true; - // else if (_MyItemInfo.IsNote && (rs.Flag & E_ReplaceFlags.Note) > 0) replaceit = true; - // else if (_MyItemInfo.IsStepPart && (rs.Flag & E_ReplaceFlags.Substep) > 0) replaceit = true; - // //else if (_MyItemInfo.IsInFirstLevelSubStep && (rs.Flag & E_ReplaceFlags.Substep) > 0) replaceit = true; - // else if (_MyItemInfo.IsAccPages & (rs.Flag & E_ReplaceFlags.Attach) > 0) replaceit = true; - - // if (replaceit) - // { - // // CASEINSENS: Do ReplaceWords for all words that match, regardless of case, and replace - // // with the ReplaceWith string as is - // if ((rs.Flag & E_ReplaceFlags.CaseInsens) > 0) - // { - // //string res = ""; - // //string fortest = Text.ToUpper(); - // ////string pat = @"(?<=\W|^)" + rs.ReplaceWord.ToUpper() + @"(?=\W|$)"; - // //// jsj 07Jun2010 HardSpaces defeat replaceword logic - // //string pat = @"(?<=\W|^)(? 0) - // { - // // only in Maine Yankee - we don't need to do this one. - // } - // // CASEINSENSFIRST: Do ReplaceWords for all words that exactly match the ReplaceWord, - // // except the case where the first character may be different - // else if ((rs.Flag & E_ReplaceFlags.CaseInsensFirst) > 0) - // { - // // only used in V.C. Summer - we don't need to do this either. - // } - // else - // { - // // If there are Regex Control Characters '\[]()' prefix them with backslash - // string replaceWord = Regex.Replace(rs.ReplaceWord, @"[[\]\\()]", @"\$0"); - // //string pat = @"(?<=\W|^)" + replaceWord + @"(?=\W|$)"; - // // jsj 07Jun2010 HardSpaces defeat replaceword logic - // //string pat = @"(?<=\W|^)(? 0) replaceit = true; - // else if ((_MyItemInfo.IsTable || _MyItemInfo.IsFigure) && (rs.Flag & E_ReplaceFlags.Table) > 0) replaceit = true; - // else if (_MyItemInfo.IsInRNO && (rs.Flag & E_ReplaceFlags.RNO) > 0) replaceit = true; - // else if (_MyItemInfo.IsCaution && (rs.Flag & E_ReplaceFlags.Caution) > 0) replaceit = true; - // else if (_MyItemInfo.IsNote && (rs.Flag & E_ReplaceFlags.Note) > 0) replaceit = true; - // else if (_MyItemInfo.IsStepPart && (rs.Flag & E_ReplaceFlags.Substep) > 0) replaceit = true; - // //else if (_MyItemInfo.IsInFirstLevelSubStep && (rs.Flag & E_ReplaceFlags.Substep) > 0) replaceit = true; - // else if (_MyItemInfo.IsAccPages & (rs.Flag & E_ReplaceFlags.Attach) > 0) replaceit = true; - - // if (replaceit) - // { - // // CASEINSENS: Do ReplaceWords for all words that match, regardless of case, and replace with the ReplaceWith string as is - // RegexOptions myOptions = (rs.Flag & E_ReplaceFlags.CaseInsens) == E_ReplaceFlags.CaseInsens ? RegexOptions.IgnoreCase : RegexOptions.None; - // string replaceWord = Regex.Replace(rs.ReplaceWord, @"[[\]\\()]", @"\$0"); - // string pat = @"(?<=\W|^)(? dicReplaceRegex = new Dictionary(); + #endregion + #region ReplaceWords + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary dicReplaceRegex = new Dictionary(); private static bool? _ProcessReplaceWords; public static bool ProcessReplaceWords { @@ -2229,11 +1875,6 @@ namespace VEPROMS.CSLA.Library if (!dicReplaceRegex.ContainsKey(rs)) { RegexOptions myOptions = (E_ReplaceFlags)(rs.Flag & E_ReplaceFlags.CaseInsens) == E_ReplaceFlags.CaseInsens ? RegexOptions.IgnoreCase : RegexOptions.None; - //RegexOptions myOptions = (E_ReplaceFlags)(rs.Flag) == E_ReplaceFlags.CaseInsens ? RegexOptions.IgnoreCase : RegexOptions.None; - //RegexOptions myOptions = (rs.Flag & E_ReplaceFlags.CaseInsens) == E_ReplaceFlags.CaseInsens ? RegexOptions.IgnoreCase : RegexOptions.None; - //int profileDepth3 = ProfileTimer.Push(">>>> DoReplaceWords2.BuildMatch"); - // CASEINSENS: Do ReplaceWords for all words that match, regardless of case, and replace with the ReplaceWith string as is - //RegexOptions myOptions = (rs.Flag & E_ReplaceFlags.CaseInsens) == E_ReplaceFlags.CaseInsens ? RegexOptions.IgnoreCase & RegexOptions.Singleline : RegexOptions.None & RegexOptions.Singleline; string replaceWord = Regex.Replace(rs.ReplaceWord, @"[[\]\\()]", @"\$0"); // if first or last character in replaceword is a non-word character, for example, ',', ')', or '.', @@ -2375,29 +2016,8 @@ namespace VEPROMS.CSLA.Library } return replaceit; } - #region notused - static Regex regFindLink = new Regex(@"\", RegexOptions.Singleline); - private string ReplaceWord(string text, string replace, string with, RegexOptions regexOptions) - { - MatchCollection myMatches = Regex.Matches(text, replace, regexOptions); - MatchCollection myLinks = regFindLink.Matches(text); - for (int i = myMatches.Count - 1; i >= 0; i--) - { - Match myMatch = myMatches[i]; - if (!PartOfLinkText(myMatch, myLinks)) - text = text.Substring(0, myMatch.Index) + with + text.Substring(myMatch.Index + myMatch.Length); - } - return text; - } - - private bool PartOfLinkText(Match myMatch, MatchCollection myLinks) - { - foreach (Match myLink in myLinks) - if (myMatch.Index > myLink.Index && myMatch.Index < (myLink.Index + myLink.Length)) - return true; - return false; - } - #endregion + + static readonly Regex regFindLink = new Regex(@"\", RegexOptions.Singleline); #endregion } #region displayTextElementClass @@ -2411,13 +2031,8 @@ namespace VEPROMS.CSLA.Library }; public class displayTextElement { - private E_TextElementType _Type; - public E_TextElementType Type - { - get { return _Type; } - set { _Type = value; } - } - protected string _Text; + public E_TextElementType Type { get; set; } + protected string _Text; virtual public string Text { get { return _Text; } @@ -2426,49 +2041,38 @@ namespace VEPROMS.CSLA.Library } public class displayLinkElement : displayTextElement { - private string _Link; - public string Link - { - get { return _Link; } - set { _Link = value; } - } - private string _TextAndLink; - public string TextAndLink - { - get { return _TextAndLink; } - set { _TextAndLink = value; } - } - /// - /// Text - this should parse the text and return the results - /// - override public string Text + public string Link { get; set; } + public string TextAndLink { get; set; } + /// + /// Text - this should parse the text and return the results + /// + override public string Text { get { - if (_TextAndLink != null) + if (TextAndLink != null) { - Match m = Regex.Match(_TextAndLink, @"", RegexOptions.Singleline); - if(m.Groups[3].Value == " ") - return m.Groups[4].Value; - return m.Groups[3].Value + m.Groups[4].Value; + Match m = Regex.Match(TextAndLink, @"", RegexOptions.Singleline); + if(m.Groups[3].Value == " ") + return m.Groups[4].Value; + return m.Groups[3].Value + m.Groups[4].Value; } return _Text; } set { - if (_TextAndLink != null) + if (TextAndLink != null) { - Match m = Regex.Match(_TextAndLink, @"", RegexOptions.Singleline); - int myIndex = m.Groups[4].Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index; - myLength += m.Groups[3].Length; - } - string gg = _TextAndLink.Substring(myIndex, myLength); - string newvalue = value.Replace("{", @"\{").Replace("}", @"\}"); - _TextAndLink = _TextAndLink.Substring(0, myIndex) + newvalue + _TextAndLink.Substring(myIndex + myLength); + Match m = Regex.Match(TextAndLink, @"", RegexOptions.Singleline); + int myIndex = m.Groups[4].Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index; + myLength += m.Groups[3].Length; + } + string newvalue = value.Replace("{", @"\{").Replace("}", @"\}"); + TextAndLink = TextAndLink.Substring(0, myIndex) + newvalue + TextAndLink.Substring(myIndex + myLength); } _Text = value; } @@ -2478,9 +2082,9 @@ namespace VEPROMS.CSLA.Library public class FoundMatches : SortedList { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private string _Text; - private VE_Font _Font; - private ItemInfo _MyItemInfo; + private readonly string _Text; + private readonly VE_Font _Font; + private readonly ItemInfo _MyItemInfo; public FoundMatches(string text, VE_Font font, ItemInfo myItemInfo) : base() { @@ -2503,11 +2107,8 @@ namespace VEPROMS.CSLA.Library Add(myMatch, null);// Exclude from Replace Words } } - private bool IsTransition(string link) - { - return link.Contains("#Link:Transition"); - } - private static Regex regRefObj = new Regex(@"\#Link\:ReferencedObject:([0-9]*) ([0-9a-zA-Z]*) ([0-9]*)", RegexOptions.Singleline); + private bool IsTransition(string link) => link.Contains("#Link:Transition"); + private static readonly Regex regRefObj = new Regex(@"\#Link\:ReferencedObject:([0-9]*) ([0-9a-zA-Z]*) ([0-9]*)", RegexOptions.Singleline); private static bool DidMsgBox = false; private static bool IsSetpointRO(string link, DocVersionInfo myDocVersion) { @@ -2527,7 +2128,7 @@ namespace VEPROMS.CSLA.Library FlexibleMessageBox.Show(string.Format("{0} does not have Referenced Object Path set.", myDocVersion.MyFolder.Name), "No RO Path Set", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } - return myROFst==null?false:myROFst.IsSetpointDB(dbid, myDocVersion); + return myROFst != null && myROFst.IsSetpointDB(dbid, myDocVersion); } return false; } @@ -2565,11 +2166,9 @@ namespace VEPROMS.CSLA.Library { // B2022-015 BNPPalr: Determine whether RO text should have Replace Words applied. InLinkAndNotInRoFlag checks // for flag on replace word item & checks that it is within and RO link - bool InLinkAndNotInRoFlag = ((foundMatch.MyWord.Flag & E_ReplaceFlags.NotInRO) != 0) ? VerifyWithinLink(text, foundMatch, offset) : false; + bool InLinkAndNotInRoFlag = ((foundMatch.MyWord.Flag & E_ReplaceFlags.NotInRO) != 0) && VerifyWithinLink(text, foundMatch, offset); if (!InLinkAndNotInRoFlag && VerifyNoHardSpace(text, foundMatch, offset) && VerifyNoLink(text, foundMatch, offset)) { - //if(offset != 0 || foundMatch.MyMatch.Index != 0 || !foundMatch.MyWord.ReplaceWith.StartsWith(@"{\par}")) - //{ if (((foundMatch.MyWord.Flag & E_ReplaceFlags.DiffUnit) == 0) || DiffUnit(foundMatch.MyWord.ReplaceWord, _MyItemInfo, "UNIT ")) { string with = foundMatch.MyWord.ReplaceWith; @@ -2600,10 +2199,6 @@ namespace VEPROMS.CSLA.Library with = with.Replace(@"\b0\", @"\"); if (with.EndsWith(@"\b0")) with = with.Replace(@"\b0", ""); - // Removed the following two lines of code to fix B2019-164. This change was not needed for - // B2019-092, a format file changed fixed that problem: - //if (with.LastIndexOf(@"\") > with.LastIndexOf(" ")) // B2019-092 - make sure there is a space char to terminate remaining rft formatting command - // with = with + " "; } bool IsUnderline = (((_Font.Style & E_Style.Underline) == E_Style.Underline) && with.Contains(@"\ul ")); // handle where replace words replaces a string with 'underline on'string'underline off', for example Point Beach @@ -2629,10 +2224,6 @@ namespace VEPROMS.CSLA.Library with = with.Replace(@"\ulnone\", @"\"); if (with.EndsWith(@"\ulnone")) with = with.Replace(@"\ulnone", ""); - // Removed the following two lines of code to fix B2019-164. This change was not needed for - // B2019-092, a format file changed fixed that problem: - //if (with.LastIndexOf(@"\") > with.LastIndexOf(" ")) // B2019-092 - make sure there is a space char to terminate remaining rft formatting command - // with = with + " "; } string preceedingText = text.Substring(0, offset + foundMatch.MyMatch.Index); int ndxBold = preceedingText.LastIndexOf(@"\b"); @@ -2719,22 +2310,12 @@ namespace VEPROMS.CSLA.Library } public class FoundMatch { - private Match _MyMatch; - public Match MyMatch - { - get { return _MyMatch; } - set { _MyMatch = value; } - } - private ReplaceStr _MyWord; - public ReplaceStr MyWord - { - get { return _MyWord; } - set { _MyWord = value; } - } + public Match MyMatch { get; set; } + public ReplaceStr MyWord { get; set; } public FoundMatch(Match myMatch, ReplaceStr myWord) { - _MyMatch = myMatch; - _MyWord = myWord; + MyMatch = myMatch; + MyWord = myWord; } } public class TextForBaseline @@ -2755,11 +2336,9 @@ namespace VEPROMS.CSLA.Library } return rtnVal; } - public static string FixText(string str) // C2018-004 create meta file for baseline compares - { - return FixText(str, false); - } - public static string FixText(string str, bool doingWordDoc) // C2018-004 create meta file for baseline compares + // C2018-004 create meta file for baseline compares + public static string FixText(string str) => FixText(str, false); + public static string FixText(string str, bool doingWordDoc) // C2018-004 create meta file for baseline compares { // put a description of know symbols and ascii commands inbetween square brackets if (str == null) return null; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs index f633bae7..0a34b84d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DocVersionExt.cs @@ -18,7 +18,6 @@ using System.IO; using System.Threading; using System.Xml; using System.Text.RegularExpressions; -//using VEPROMS.Properties; namespace VEPROMS.CSLA.Library { @@ -26,8 +25,6 @@ namespace VEPROMS.CSLA.Library { public static DocVersion GetFromDB(int versionID) // get data from database (don't look in cache first) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a DocVersion"); try { DocVersion tmp = DataPortal.Fetch(new PKCriteria(versionID)); @@ -146,18 +143,15 @@ namespace VEPROMS.CSLA.Library return _DocVersionConfig; } } - private void _DocVersionConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) - { - Config = _DocVersionConfig.ToString(); - } - #endregion - #region UserSettings - /// - /// These settings are set on the user interface side. - /// This is used to control whether the Name and/or Title is displayed - /// next to the tree nodes in the user interface - /// - private bool _DisplayTreeNodeNames = true; + private void _DocVersionConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) => Config = _DocVersionConfig.ToString(); + #endregion + #region UserSettings + /// + /// These settings are set on the user interface side. + /// This is used to control whether the Name and/or Title is displayed + /// next to the tree nodes in the user interface + /// + private bool _DisplayTreeNodeNames = true; public bool DisplayTreeNodeNames { get { return _DisplayTreeNodeNames; } @@ -182,50 +176,12 @@ namespace VEPROMS.CSLA.Library rtnstr += Title; } return rtnstr; - //return string.Format("{0} - {1}", Name, Title); } - #region IVEDrillDown - //public System.Collections.IList GetChildren() - //{ - // return null; - //} - //public bool HasChildren - //{ - // get { return _ItemID > 0; } - //} - //public IVEDrillDown ActiveParent - //{ - // get - // { - // return MyFolder; - // } - //} - //private Format _ActiveFormat = null; - //public Format ActiveFormat - //{ - // get - // { - // if (_ActiveFormat == null) - // _ActiveFormat = LocalFormat != null ? LocalFormat : ActiveParent.ActiveFormat; - // return _ActiveFormat; - // } - // set - // { - // _ActiveFormat = null; - // } - //} - //public Format LocalFormat - //{ - // get { return MyFormat; } - //} - public ConfigDynamicTypeDescriptor MyConfig - { - get { return DocVersionConfig; } - } - #endregion - public DocVersionInfo MyDocVersionInfo - { get { return DocVersionInfo.Get(VersionID); } } - } + #region IVEDrillDown + public ConfigDynamicTypeDescriptor MyConfig => DocVersionConfig; + #endregion + public DocVersionInfo MyDocVersionInfo => DocVersionInfo.Get(VersionID); + } public partial class DocVersionInfo : IVEDrillDownReadOnly { public TimeSpan tsTimeOut = TimeSpan.FromSeconds(6); @@ -249,9 +205,10 @@ namespace VEPROMS.CSLA.Library } return exists; } - // The following dictionary is used to store the state of the ro.fst check so that it is - // not made repeatedly in NewerRoFst. (B2017-050) - private static Dictionary NewerRoFstLookup = new Dictionary(); + // The following dictionary is used to store the state of the ro.fst check so that it is + // not made repeatedly in NewerRoFst. (B2017-050) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary NewerRoFstLookup = new Dictionary(); private static bool AddToRoFstLookup(string key, bool result) { if (!NewerRoFstLookup.ContainsKey(key)) NewerRoFstLookup.Add(key, result); @@ -267,7 +224,6 @@ namespace VEPROMS.CSLA.Library RODbInfo rdi = RODbInfo.GetJustRODB(roFstInfo.RODbID); string rofstPath = rdi.FolderPath + @"\ro.fst"; - //if (!File.Exists(rofstPath)) return false; if (!pathExists(rofstPath)) { _MyLog.WarnFormat("RO Path '{0}' could not be found", rofstPath); @@ -369,10 +325,10 @@ namespace VEPROMS.CSLA.Library return _SearchDVPath; } } - public string SearchPath { get { return ""; } } + public string SearchPath => ""; - // B2021-076: Proms search results are not presented in order when printed to PDF - public string SearchDefaultSort { get { return string.Empty; } } + // B2021-076: Proms search results are not presented in order when printed to PDF + public string SearchDefaultSort => string.Empty; #endregion #region UnlinkEnhancedDocVersion @@ -420,22 +376,15 @@ namespace VEPROMS.CSLA.Library #region DocVersion Config [NonSerialized] private DocVersionConfig _DocVersionConfig; - public DocVersionConfig DocVersionConfig - { get { return (_DocVersionConfig != null ? _DocVersionConfig : _DocVersionConfig = new DocVersionConfig(this)); } } - private void DocVersionConfigRefresh() - { - _DocVersionConfig = null; - } - #endregion + public DocVersionConfig DocVersionConfig => _DocVersionConfig ?? (_DocVersionConfig = new DocVersionConfig(this)); + private void DocVersionConfigRefresh() => _DocVersionConfig = null; + #endregion - #region MOVE TO DOCVERSION CONFIG + #region MOVE TO DOCVERSION CONFIG - private string GetProfile(string grp, string nam) - { - return GetProfile(grp, nam, false); - } + private string GetProfile(string grp, string nam) => GetProfile(grp, nam, false); - private string GetProfile(string grp, string nam, bool flag) + private string GetProfile(string grp, string nam, bool flag) { DocVersionConfig dvcfg = DocVersionConfig; string buff = null; @@ -454,16 +403,14 @@ namespace VEPROMS.CSLA.Library } // B2021-066: Procedure PC/PC resolve procedure number with Unit Specific info - public string UnitSpecific(string str, int len, ItemInfo ii) + public string UnitSpecific(ItemInfo ii) { - ProcedureInfo pi = ii as ProcedureInfo; + if (!(ii is ProcedureInfo pi)) // B2022-004: Don't crash if Proc PC/PC (ii is from a list, so wasn't an ItemInfo) + { + pi = ProcedureInfo.Get(ii.ItemID); + } - if (pi == null) // B2022-004: Don't crash if Proc PC/PC (ii is from a list, so wasn't an ItemInfo) - { - pi = ProcedureInfo.Get(ii.ItemID); - } - - if (pi == null) return ""; + if (pi == null) return ""; // B2023-035 for save the current select child (selectedSlave) and use the child number // that was selected when printed. This is needed for when "Other" applicability @@ -478,9 +425,8 @@ namespace VEPROMS.CSLA.Library } string unitdes = "ID"; string prefix = null; - string fromunitdes = null; - str = ItemInfo.ConvertToDisplayText(pi.MyContent.Number); - bool hastoken = false; + string str = ItemInfo.ConvertToDisplayText(pi.MyContent.Number); + bool hastoken = false; // Determine if there is a token in the procedure number data, default is ID if (str.ToUpper().Contains(@" 0 && prefix[prefix.Length - 1] != ',' ? "," : "") + tokRepAndPrefix); + if (procAppl && tokRepAndPrefix != "") prefix += (prefix == null ? tokRepAndPrefix : (prefix != null && prefix.Length > 0 && prefix[prefix.Length - 1] != ',' ? "," : "") + tokRepAndPrefix); } str = Regex.Replace(str, @"\<[uU]-[a-zA-Z]+\>", ""); str = Regex.Replace(str, @"\<[uU]\>", ""); - return (!sometext) ? str: "[" + prefix + "]" + str; + return (!sometext) ? str: $"[{prefix}]{str}"; } - public string UnitSpecific(string str, int len) + public string UnitSpecific(string str) { // This routine retrieves the procedure number format from the @@ -587,20 +534,8 @@ namespace VEPROMS.CSLA.Library string retvalu = ""; string asis = "#"; if (str == null || str.Equals(string.Empty)) return retvalu; // return a null (empty) string - /* - * Bug fix: B2005-017 3/2/2005 - * Need to use the largest procedure number length that's in the - * SET.DFF file. "LargestNumber" is the largest length after the - * procedure number is replaced via the SET.INI file "replace" list. - * - if(len==0)len=LargestNumber; - */ - // TODO: Do we need this line?-->>> if(len==0)len=LargestRawSetNumber; - //GetPrivateProfileString("unit", "procedure number", asis, mstr, MAXPATH, "proc.ini"); string pnum = asis; - //rhm/jcb stuff 20120511 - //string mstr = GetProfile("Unit", "ProcedureNumber", true); string mstr = DocVersionConfig.Unit_ProcedureNumber; if (mstr != null && !mstr.Equals(string.Empty)) pnum = mstr; @@ -684,11 +619,11 @@ namespace VEPROMS.CSLA.Library case 'P': //TODO: THIS IS A GLOBAL IN THE 16 BIT CODE!!!! string procnumber = ""; - pn = UnitSpecific(procnumber, 0); + pn = UnitSpecific(procnumber); retval = GetProfile(pn, substr, true); break; } - if (retval == null) // .Equals(string.Empty)) + if (retval == null) swptr++; } str += sav; @@ -752,13 +687,9 @@ namespace VEPROMS.CSLA.Library #endregion ItemInfoList _Procedures = null; - public ItemInfoList Procedures - { get { return (_Procedures != null ? _Procedures : _Procedures = ItemInfoList.GetList(_ItemID, (int)E_FromType.Procedure)); } } - public void ResetProcedures() - { - _Procedures = null; - } - public static void ResetProcedures(int versionID) + public ItemInfoList Procedures => _Procedures ?? (_Procedures = ItemInfoList.GetList(_ItemID, (int)E_FromType.Procedure)); + public void ResetProcedures() => _Procedures = null; + public static void ResetProcedures(int versionID) { string key = versionID.ToString(); if (_CacheByPrimaryKey.ContainsKey(key)) @@ -778,31 +709,12 @@ namespace VEPROMS.CSLA.Library foreach (DocVersionInfo dvi in _CacheList) dvi.ResetProcedures(); } - #region IVEReadOnlyItem - public System.Collections.IList GetChildren() - { - return Procedures; - } - //public bool ChildrenAreLoaded - //{ - // get { return _iil == null; } - //} - public bool HasChildren - { - get { return _ItemID > 0; } - } - public IVEDrillDownReadOnly ActiveParent - { - get - { - return MyFolder; - } - } - public FormatInfo ActiveFormat - { - get { return LocalFormat != null ? LocalFormat : ActiveParent.ActiveFormat; } - } - public FormatInfo LocalFormat + #region IVEReadOnlyItem + public System.Collections.IList GetChildren() => Procedures; + public bool HasChildren => _ItemID > 0; + public IVEDrillDownReadOnly ActiveParent => MyFolder; + public FormatInfo ActiveFormat => LocalFormat ?? ActiveParent.ActiveFormat; + public FormatInfo LocalFormat { get { @@ -810,17 +722,14 @@ namespace VEPROMS.CSLA.Library return MyFormat; } } - public ConfigDynamicTypeDescriptor MyConfig + public ConfigDynamicTypeDescriptor MyConfig => DocVersionConfig; + #region PasteChild + public ItemInfo PasteChild(int copyStartID) // pastes into an 'empty' docversion { - get { return DocVersionConfig; } - } - //public bool HasStandardSteps() - //{ return false; } - #region PasteChild - public ItemInfo PasteChild(int copyStartID) // pastes into an 'empty' docversion - { - ItemInfo cpItem = ItemInfo.Get(copyStartID); - try +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Kept for Side Effect and Debugging + ItemInfo cpItem = ItemInfo.Get(copyStartID); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + try { DocVersionInfo dvi = DataPortal.Fetch(new VersionPastingPartCriteria(VersionID, copyStartID, DateTime.Now, Volian.Base.Library.VlnSettings.UserID)); ItemInfo tmp = dvi.Procedures[0] as ItemInfo; @@ -831,8 +740,8 @@ namespace VEPROMS.CSLA.Library } return tmp; } - catch (Exception ex) - { + catch (Exception) + { System.Windows.Forms.MessageBox.Show("Details were written to the Error Log.", "Paste Failed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return null; } @@ -869,23 +778,12 @@ namespace VEPROMS.CSLA.Library rtnstr += Title; } return rtnstr; - //return string.Format("{0} - {1}", Name, Title); } - //public string ToString(string str,System.IFormatProvider ifp) - //{ - // return ToString(); - //} - public ItemInfo LastChild() - { - return MyItem.LastSibling; - } - public ItemInfo FirstChild() - { - return MyItem; - } - #endregion - #region DataPortal - private void DataPortal_Fetch(VersionPastingPartCriteria criteria) + public ItemInfo LastChild() => MyItem.LastSibling; + public ItemInfo FirstChild() => MyItem; + #endregion + #region DataPortal + private void DataPortal_Fetch(VersionPastingPartCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfo.DataPortal_Fetch", GetHashCode()); try @@ -899,10 +797,12 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@VersionID", criteria.VersionID); cm.Parameters.AddWithValue("@StartItemID", criteria.StartItemID); cm.Parameters.AddWithValue("@DTS", criteria.DTS); //ABC - cm.Parameters.AddWithValue("@UserID", criteria.UserID); //ABC - SqlParameter param_ContentID = new SqlParameter("@ThisVersionID", SqlDbType.Int); - param_ContentID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ContentID); + cm.Parameters.AddWithValue("@UserID", criteria.UserID); //ABC + SqlParameter param_ContentID = new SqlParameter("@ThisVersionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ContentID); cm.CommandText = "PasteDocVersionChild"; cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) @@ -934,12 +834,9 @@ namespace VEPROMS.CSLA.Library #region Extension partial class DocVersionInfoExtension : extensionBase { - public override void Refresh(DocVersionInfo tmp) - { - tmp.DocVersionConfigRefresh(); - } + public override void Refresh(DocVersionInfo tmp) => tmp.DocVersionConfigRefresh(); - } + } #endregion public ROFstInfo GetROFst(int rodbid) { @@ -967,7 +864,8 @@ namespace VEPROMS.CSLA.Library rodbid, DocVersionAssociations.Count, VersionID, MyFolder.Name); return null; } - private static List _HasBadRODBIDProblem = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _HasBadRODBIDProblem = new List(); private bool FirstBadRODBIDProblemDetected { get @@ -977,49 +875,13 @@ namespace VEPROMS.CSLA.Library return true; } } - public bool IsFolder - { - get - { - return false; - } - } - public bool IsDocVersion - { - get - { - return true; - } - } - public bool IsProcedure - { - get - { - return false; - } - } - public bool IsSection - { - get - { - return false; - } - } - public bool IsStep - { - get - { - return false; - } - } - public int MultiUnitCount - { - get - { - return DocVersionConfig.Unit_Count; - } - } - private string[] _UnitNames; + public bool IsFolder => false; + public bool IsDocVersion => true; + public bool IsProcedure => false; + public bool IsSection => false; + public bool IsStep => false; + public int MultiUnitCount => DocVersionConfig.Unit_Count; + private string[] _UnitNames; public string[] UnitNames { get @@ -1138,7 +1000,8 @@ namespace VEPROMS.CSLA.Library { public DocVersionNonEnhancedListCriteria() { ;} } - private void DataPortal_Fetch(DocVersionNonEnhancedListCriteria criteria) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + private void DataPortal_Fetch(DocVersionNonEnhancedListCriteria criteria) { this.RaiseListChangedEvents = false; try diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs index 5d7095b0..39fabd35 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/DocumentExt.cs @@ -6,7 +6,6 @@ using Csla; using Csla.Data; using System.Data; using System.Data.SqlClient; -//----------------- using System.Drawing; using System.Text.RegularExpressions; using LBWordLibrary; @@ -14,7 +13,6 @@ using System.Drawing.Imaging; using Volian.Base.Library; using System.Diagnostics; using System.Runtime.InteropServices; -using System.Runtime; using System.Linq; namespace VEPROMS.CSLA.Library @@ -28,15 +26,8 @@ namespace VEPROMS.CSLA.Library public delegate void VolianStatusChange(VolianStatusType type, int count, string text); public partial class Document { - public string DocumentTitle - { - get - { - if (_LibTitle == string.Empty) return string.Format("Document {0}", _DocID); - return _LibTitle; - } - } - private static LBApplicationClass _MyApp = null; + public string DocumentTitle => _LibTitle == string.Empty ? $"Document {_DocID}" : _LibTitle; + private static LBApplicationClass _MyApp = null; public static LBApplicationClass MyApp { get @@ -84,11 +75,7 @@ namespace VEPROMS.CSLA.Library public void StatusChanged(VolianStatusType type, int count, string text) { - //if (Parent != null && Parent.Parent != null && Parent.Parent.Parent is DisplayTabControl) - //{ - // DisplayTabControl tc = Parent.Parent.Parent as DisplayTabControl; - // tc.ONStatusChanged(this, new DisplayTabControlStatusEventArgs(type, count, text)); - //} + //Do nothing } public void RestoreWordDoc(ItemInfo myItemInfo) @@ -117,9 +104,9 @@ namespace VEPROMS.CSLA.Library myDoc.Close(); break; } - catch (Exception ex) - { - if (myDoc != null) myDoc.Close(); + catch (Exception) + { + myDoc?.Close(); continue; // get next document audit item. } } @@ -145,17 +132,16 @@ namespace VEPROMS.CSLA.Library pdfFile.Delete(); Pdf.DeleteAll(DocID); // clear the PDF table for DocID first DocStyle myDocStyle = myItemInfo.ActiveSection.MyDocStyle; - SectionConfig sc = myItemInfo.ActiveSection.MyConfig as SectionConfig; - if (sc != null && sc.Section_WordMargin == "Y") - { - using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) {; } - } - else - { - using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, - (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) {; } - } - UpdateDRoUsages(roids); + if (myItemInfo.ActiveSection.MyConfig is SectionConfig sc && sc.Section_WordMargin == "Y") + { + using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) {; } + } + else + { + using (Pdf myPdf = Pdf.MakePdf(this, MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, + (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) {; } + } + UpdateDRoUsages(roids); Save(); } } @@ -169,17 +155,11 @@ namespace VEPROMS.CSLA.Library public static void ConvertWordSectionToDOCX(ItemInfo itmInfo) { FrmPopupStatusMessage pmsg = null; - DSOFile myfile = null; - LBWordLibrary.LBApplicationClass ap = null; + LBWordLibrary.LBApplicationClass ap = null; LBWordLibrary.LBDocumentClass doc = null; - string orgFilename = null; - string filename = null; - FileInfo fi = null; + FileInfo fi = null; FileStream fs = null; - SectionInfo msi = null; - Section sec = null; - SectionConfig cfg = null; - DocumentInfo docInfo = null; + DocumentInfo docInfo = null; try { // check the Word file extension that is saved in the tblDocuments SQL database table @@ -194,21 +174,21 @@ namespace VEPROMS.CSLA.Library pmsg = new FrmPopupStatusMessage("Converting This Section to Word DOCX", statMsg); pmsg.Show(); - // Get Document as file - it's placed in the user's temporary folder (like we do when we edit a Word section) - myfile = new DSOFile(docInfo); + // Get Document as file - it's placed in the user's temporary folder (like we do when we edit a Word section) + DSOFile myfile = new DSOFile(docInfo); - // Open MSWord App - ap = new LBWordLibrary.LBApplicationClass(); + // Open MSWord App + ap = new LBWordLibrary.LBApplicationClass(); doc = ap.Documents.Open(myfile.FullName); - // Older versions of PROMS saved the Word section as either a RTF or the old-style Word DOC file - // In either case, we want to convert it to a Word DOCX file - // So now create a file name with the .DOCX extension - orgFilename = myfile.FullName.ToUpper(); - filename = orgFilename.Replace(".RTF", ".DOCX").Replace(".DOC", ".DOCX"); // we want to convert either .RTF or .DOC Word sections + // Older versions of PROMS saved the Word section as either a RTF or the old-style Word DOC file + // In either case, we want to convert it to a Word DOCX file + // So now create a file name with the .DOCX extension + string orgFilename = myfile.FullName.ToUpper(); + string filename = orgFilename.Replace(".RTF", ".DOCX").Replace(".DOC", ".DOCX"); - // This calls Word's convert function to convert the opened .DOC or .RTF to DOCX and save it to our new DOCX file name - doc.SaveAs(filename, LBWordLibrary.LBWdSaveFormat.wdFormatXMLDocument); // Convert to Word DOCX + // This calls Word's convert function to convert the opened .DOC or .RTF to DOCX and save it to our new DOCX file name + doc.SaveAs(filename, LBWdSaveFormat.wdFormatXMLDocument); // Convert to Word DOCX doc.Close(); doc = null; @@ -222,15 +202,15 @@ namespace VEPROMS.CSLA.Library bool isLibraryDocument = (docInfo.LibTitle != null && docInfo.LibTitle != ""); Document myDoc = null; if (isLibraryDocument) - myDoc = Document.Get(docInfo.DocID); + myDoc = Get(docInfo.DocID); else - myDoc = Document.MakeDocument(null, ByteArray, docInfo.DocAscii, docInfo.Config, ".DOCX"); + myDoc = MakeDocument(null, ByteArray, docInfo.DocAscii, docInfo.Config, ".DOCX"); - // update the document information in the database - msi = itmInfo as SectionInfo; - sec = msi.Get(); - cfg = sec.SectionConfig; - if (!isLibraryDocument) + // update the document information in the database + SectionInfo msi = itmInfo as SectionInfo; + Section sec = msi.Get(); + SectionConfig cfg = sec.SectionConfig; + if (!isLibraryDocument) cfg.MySection.MyContent.MyEntry.MyDocument = myDoc; // resetting MyDocument will clear the library doc link - so don't do if a library document else cfg.MySection.MyContent.MyEntry.MyDocument.DocContent = ByteArray; // only update .DocContent for library documents @@ -257,36 +237,14 @@ namespace VEPROMS.CSLA.Library } finally { - if (pmsg != null) - pmsg.Close();// close the statue message - if (ap != null) - ap.Quit(); // close the Word app - if (doc != null) - doc.Close(); - if (fs != null) - fs.Close(); + pmsg?.Close();// close the statue message + ap?.Quit(); // close the Word app + doc?.Close(); + fs?.Close(); if (fi != null && fi.Exists) fi.Delete();// delete the temporary .DOCX file } } - - /// - /// FixString processes the string returned and changes any symbols (0xF0??) to normal characters - /// - /// - /// - //private static string FixString(string str) - //{ - // StringBuilder results = new StringBuilder(); - // foreach (char c in str) - // { - // if ((c & 0xFF00) == 0xF000) - // results.Append((char)(c & 0xFF)); - // else - // results.Append((char)(c)); - // } - // return results.ToString(); - //} } public partial class DocumentInfo { @@ -297,15 +255,8 @@ namespace VEPROMS.CSLA.Library get { return _ContentIsDirty; } set { _ContentIsDirty = value; } } - public string DocumentTitle - { - get - { - if (_LibTitle == string.Empty) return string.Format("Document {0}", _DocID); - return _LibTitle; - } - } - public string LibraryDocumentUsage + public string DocumentTitle => _LibTitle == string.Empty ? $"Document {_DocID}" : _LibTitle; + public string LibraryDocumentUsage { get { @@ -323,11 +274,11 @@ namespace VEPROMS.CSLA.Library --limit; if (limit < 0) { - sb.Append(sep + "..."); + sb.Append($"{sep}..."); return sb.ToString(); } ItemInfo proc = myItem.MyProcedure; - sb.Append(sep + proc.DisplayNumber + " - " + proc.DisplayText); + sb.Append($"{sep}{proc.DisplayNumber} - {proc.DisplayText}"); sep = "\r\n "; } } @@ -351,7 +302,7 @@ namespace VEPROMS.CSLA.Library foreach (ItemInfo myItem in myEntry.MyContent.ContentItems) { ItemInfo proc = myItem.MyProcedure; - sb.Append(sep + proc.DisplayNumber + " - " + proc.DisplayText); + sb.Append($"{sep}{proc.DisplayNumber} - {proc.DisplayText}"); sep = "\r\n "; } } @@ -385,14 +336,10 @@ namespace VEPROMS.CSLA.Library #region DocumentConfig [NonSerialized] private DocumentConfig _DocumentConfig; - public DocumentConfig DocumentConfig - { get { return (_DocumentConfig != null ? _DocumentConfig : _DocumentConfig = new DocumentConfig(this)); } } - public void RefreshConfig() - { - _DocumentConfig = null; - } - #endregion - public static DocumentInfo GetByLibDocName(string libdoc, int versionID) + public DocumentConfig DocumentConfig => _DocumentConfig ?? (_DocumentConfig = new DocumentConfig(this)); + public void RefreshConfig() => _DocumentConfig = null; + #endregion + public static DocumentInfo GetByLibDocName(string libdoc, int versionID) { try { @@ -407,13 +354,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class LibDocCriteria { - private string _LibDoc; - public string LibDoc - { get { return _LibDoc; } } - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - public LibDocCriteria(string libdoc, int versionid) + private readonly string _LibDoc; + public string LibDoc => _LibDoc; + private readonly int _VersionID; + public int VersionID => _VersionID; + public LibDocCriteria(string libdoc, int versionid) { _LibDoc = libdoc; _VersionID = versionid; @@ -482,12 +427,10 @@ namespace VEPROMS.CSLA.Library get { return _IsLibrary; } set { _IsLibrary = value; } } - public LibraryCriteria(bool islibrary) - { - _IsLibrary = islibrary; - } - } - private void DataPortal_Fetch(LibraryCriteria criteria) + public LibraryCriteria(bool islibrary) => _IsLibrary = islibrary; + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until CSLA replaced")] + private void DataPortal_Fetch(LibraryCriteria criteria) { this.RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentInfoList.DataPortal_Fetch", GetHashCode()); @@ -525,64 +468,31 @@ namespace VEPROMS.CSLA.Library private bool _IsDisposed; private DocumentInfo _MyDocument = null; private FileInfo _MyFile = null; - private string _Extension = "DOC"; - #endregion + #endregion - #region Properties - public DocumentInfo MyDocument + #region Properties + public DocumentInfo MyDocument { get { return _MyDocument; } set { - // B2017-249 Don't delete last DSOFile - //TryDelete(); _MyDocument = value; CreateFile(); } } - public FileInfo MyFile - { - get { return _MyFile; } - } - public string Extension - { - get { return _Extension; } - set { _Extension = value; } - } - #endregion + public FileInfo MyFile => _MyFile; + public string Extension { get; set; } = "DOC"; + #endregion - #region Private Methods - private void TryDelete() - { - if (_MyDocument == null) return; - if (_MyFile == null) return; - // B2017-249 Recover Temporary File And AutoSave support for MSWord - _MyFile.Refresh(); - if (_MyFile.Exists && (TimeSpan.FromTicks(_MyDocument.DTS.Ticks - _MyFile.LastWriteTimeUtc.Ticks).TotalSeconds > 1.0)) - { - try - { - _MyFile.Delete(); - } - catch (IOException ex) - { - // _MyLog.Error("TryDelete", ex); - } - finally - { - _MyFile = null; - _MyDocument = null; - } - } - } - private bool _Created = false; + #region Private Methods + private bool _Created = false; private int _Unique = 0; private string Unique { get { string retval = string.Empty; - if (_Unique != 0) retval = "_" + _Unique.ToString(); + if (_Unique != 0) retval = $"_{_Unique}"; _Unique++; return retval; } @@ -601,21 +511,11 @@ namespace VEPROMS.CSLA.Library return _MyFile.Exists && (_MyFile.LastWriteTimeUtc > StartDTS); } } - private DateTime _StartDTS; - public DateTime StartDTS - { - get { return _StartDTS; } - set { _StartDTS = value; } - } - //B2017-260 Prefix the Temporary document file with server name and database name - private static string _TempFilePrefix = string.Empty; - public static string TempFilePrefix - { - get { return DSOFile._TempFilePrefix; } - set { DSOFile._TempFilePrefix = value; } - } - private void CreateTemporaryFile() + public DateTime StartDTS { get; set; } + public static string TempFilePrefix { get; set; } = string.Empty; + + private void CreateTemporaryFile() { _Unique = 0; try @@ -692,7 +592,7 @@ namespace VEPROMS.CSLA.Library } } - public void SaveFile(float length, string ascii, ItemInfo myItemInfo, bool cvtLibDoc, VolianStatusChange statusChange) + public void SaveFile(string ascii, ItemInfo myItemInfo, bool cvtLibDoc, VolianStatusChange statusChange) { // TODO: Add Try & Catch logic if (_MyDocument == null) return; @@ -734,15 +634,15 @@ namespace VEPROMS.CSLA.Library doc.FileExtension = MyFile.Extension; doc.DocContent = buf; doc.DocAscii = ascii; - //doc.UpdateDocAscii(_MyFile.FullName); - DocumentConfig cfg = new DocumentConfig(doc); - cfg.Edit_Initialized = true; - doc.Config = cfg.ToString(); - doc.UserID = Volian.Base.Library.VlnSettings.UserID; + DocumentConfig cfg = new DocumentConfig(doc) + { + Edit_Initialized = true + }; + doc.Config = cfg.ToString(); + doc.UserID = VlnSettings.UserID; // B2017-262 use the date time stamp from the file rather than the clock doc.DTS = _MyFile.LastWriteTimeUtc; - //doc.DTS = DateTime.Now.ToUniversalTime(); doc = doc.Save(); if (myItemInfo != null) // B2016-131 if myItemInfo is null, the lib doc is not referenced from any procedure. Just save changes, but don't generate a PDF @@ -760,47 +660,38 @@ namespace VEPROMS.CSLA.Library Pdf.DeleteAll(doc.DocID); // clear the PDF table for DocID first DocStyle myDocStyle = myItemInfo.ActiveSection.MyDocStyle; - SectionConfig sc = myItemInfo.ActiveSection.MyConfig as SectionConfig; - if (sc != null && sc.Section_WordMargin == "Y") - { - using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) {; } - } - else - { - using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, - (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) {; } - } + if (myItemInfo.ActiveSection.MyConfig is SectionConfig sc && sc.Section_WordMargin == "Y") + { + using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)myItemInfo.MSWordPageCount, buf)) {; } + } + else + { + using (Pdf myPdf = Pdf.MakePdf(doc, MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, + (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)myItemInfo.MSWordPageCount, buf)) {; } + } - doc.UpdateDRoUsages(roids); + doc.UpdateDRoUsages(roids); doc.Save(); if (savLen != _MyFile.Length) _MyLog.ErrorFormat("DSO FRAMER: File size changed during Save for Word Document, beginSize = {0}, endSize = {1}", savLen, _MyFile.Length); } } - #endregion + #endregion - #region Properties + #region Properties - // B2017-249 Recover Temporary File And AutoSave support for MSWord - private bool _Temporary = false; - public bool Temporary - { - get { return _Temporary; } - set { _Temporary = value; } - } + // B2017-249 Recover Temporary File And AutoSave support for MSWord + public bool Temporary { get; set; } = false; - #endregion + #endregion - #region Constructors + #region Constructors - public DSOFile(DocumentInfo myDocument) - { - MyDocument = myDocument; - } + public DSOFile(DocumentInfo myDocument) => MyDocument = myDocument; - public DSOFile(DocumentInfo myDocument, bool temporary) + public DSOFile(DocumentInfo myDocument, bool temporary) { Temporary = temporary; MyDocument = myDocument; @@ -821,13 +712,12 @@ namespace VEPROMS.CSLA.Library GC.SuppressFinalize(this); } - protected void Dispose(bool disposing) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping disposing to match old signature")] + protected void Dispose(bool disposing) { if (!_IsDisposed) { _IsDisposed = true; - // B2017-249 Don't Delete last DSOFile - //TryDelete(); } } @@ -855,64 +745,51 @@ namespace VEPROMS.CSLA.Library #region Fields // B2019-123 Verify that the RO token is the correct format - private static Regex _ROAccPageTokenPattern = new Regex("[<][^<>-]+-[^<>]+[>]"); + private static readonly Regex _ROAccPageTokenPattern = new Regex("[<][^<>-]+-[^<>]+[>]"); // used to save Word sections with resolved ROs (for export generated from Approve) private static LBApplicationClass _MyApp = null; private static SectionInfo _MySection; - private static Dictionary _DocReplace; - private static bool _CloseWordWhenDone = true; - private static System.Drawing.Color _OverrideColor = System.Drawing.Color.Transparent; - private static System.Windows.Forms.Form _FormForPlotGraphics = null; - private static int _DebugStatus = 0; - // B2018-071 Save list of DocIDs for invalid document so that error log messages are not repeated - private static List _MissingDocs = new List(); - private static bool _Automatic = false; + // B2018-071 Save list of DocIDs for invalid document so that error log messages are not repeated + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _MissingDocs = new List(); - // B2022-083: Support Conditional RO Values --> Added an internal rochild dictionary cache specifically for printing - // - // As you loop through all of the specific RO AccPageKeys for the current MsWord Document Section, the code will first - // check the internal rochild cache for the base (12) digit roid Key/Value, if it doesn't already exist, then load the - // RoChild from the database, add it to the rochild print cache, and then based on the length of the roid, either (12) or (16), - // return either the base RoChild Object with its collection of children return values or the specific return value RoChild object. - // - // Notes** - // 1) Every base RoChild object must have one to many specific return values. - // 2) The first RoChild return value in the "children" collection will always have a roid Ext of "0041" or and a accPage Ext of "A" - // 3) The first RoChild return value in the "children" collection "0041/A" will also be used as the Default RoChild return value if a - // specific RoChild return value (by (4) digit Extension) doesn't exist in the base RoChild Objects "children" collection of return values. - // Ex: The specific RoChild return value for the roidExt "0044" doesn't exist now for some reason, then always return - // the first RoChild return value "0041" as the Default RO return value for that RO Object - // 4) Any (16) digit roids with an invalid/padded roid Ext (last (4) digits of roid = "0000") are automatically converted to use the "0041" - // roid Ext so the RO's with the older roidExt formats will be backwards compatible with the new logic/code and they will now be more consistent like - // the newer roidExt formats. The actual data in the database records with the roids that have the older "0000" extension (ROUsages & DROUsages Tables) - // are not physically modified or updated in the source tables. The RofstLookup method "FormatRoidKey" is always called first in the code before attempting - // to do any lookups or comparisons with any other roids. By standardizing the roid / accPageID formats and values first before running any other rules/logic, - // dramatically simplifies the down stream code for how to process/convert the Ro values - // 5) If a specific RoChild return value does not exist (maybe it was removed in the ROEditor / latest RO.FST file), then just return - // the first RoChild return value in the "children" collection (0041) instead + // B2022-083: Support Conditional RO Values --> Added an internal rochild dictionary cache specifically for printing + // + // As you loop through all of the specific RO AccPageKeys for the current MsWord Document Section, the code will first + // check the internal rochild cache for the base (12) digit roid Key/Value, if it doesn't already exist, then load the + // RoChild from the database, add it to the rochild print cache, and then based on the length of the roid, either (12) or (16), + // return either the base RoChild Object with its collection of children return values or the specific return value RoChild object. + // + // Notes** + // 1) Every base RoChild object must have one to many specific return values. + // 2) The first RoChild return value in the "children" collection will always have a roid Ext of "0041" or and a accPage Ext of "A" + // 3) The first RoChild return value in the "children" collection "0041/A" will also be used as the Default RoChild return value if a + // specific RoChild return value (by (4) digit Extension) doesn't exist in the base RoChild Objects "children" collection of return values. + // Ex: The specific RoChild return value for the roidExt "0044" doesn't exist now for some reason, then always return + // the first RoChild return value "0041" as the Default RO return value for that RO Object + // 4) Any (16) digit roids with an invalid/padded roid Ext (last (4) digits of roid = "0000") are automatically converted to use the "0041" + // roid Ext so the RO's with the older roidExt formats will be backwards compatible with the new logic/code and they will now be more consistent like + // the newer roidExt formats. The actual data in the database records with the roids that have the older "0000" extension (ROUsages & DROUsages Tables) + // are not physically modified or updated in the source tables. The RofstLookup method "FormatRoidKey" is always called first in the code before attempting + // to do any lookups or comparisons with any other roids. By standardizing the roid / accPageID formats and values first before running any other rules/logic, + // dramatically simplifies the down stream code for how to process/convert the Ro values + // 5) If a specific RoChild return value does not exist (maybe it was removed in the ROEditor / latest RO.FST file), then just return + // the first RoChild return value in the "children" collection (0041) instead - // B2022-088: Find Doc Ro button not working in Word Sections - public static Dictionary RoPrintCache = new Dictionary(); + // B2022-088: Find Doc Ro button not working in Word Sections + public static Dictionary RoPrintCache = new Dictionary(); - #endregion + #endregion - #region Properties + #region Properties - public static Dictionary DocReplace - { - get { return MSWordToPDF._DocReplace; } - set { MSWordToPDF._DocReplace = value; } - } + public static Dictionary DocReplace { get; set; } - public static bool CloseWordWhenDone - { - get { return MSWordToPDF._CloseWordWhenDone; } - set { MSWordToPDF._CloseWordWhenDone = value; } - } + public static bool CloseWordWhenDone { get; set; } = true; - public static LBApplicationClass MyApp + public static LBApplicationClass MyApp { get { @@ -921,41 +798,26 @@ namespace VEPROMS.CSLA.Library } } - public static int DebugStatus - { - get { return MSWordToPDF._DebugStatus; } - set { MSWordToPDF._DebugStatus = value; } - } + public static int DebugStatus { get; set; } = 0; - public static System.Drawing.Color OverrideColor - { - get { return MSWordToPDF._OverrideColor; } - set { MSWordToPDF._OverrideColor = value; } - } + public static System.Drawing.Color OverrideColor { get; set; } = Color.Transparent; - public static System.Windows.Forms.Form FormForPlotGraphics - { - get { return MSWordToPDF._FormForPlotGraphics; } - set { MSWordToPDF._FormForPlotGraphics = value; } - } + public static System.Windows.Forms.Form FormForPlotGraphics { get; set; } = null; + // C2018-035 Don't use a MessageBox if in automatic (Baseline) testing mode. + public static bool Automatic { get; set; } = false; - public static bool Automatic - { - // C2018-035 Don't use a MessageBox if in automatic (Baseline) testing mode. - get { return MSWordToPDF._Automatic; } - set { MSWordToPDF._Automatic = value; } - } + #endregion - #endregion + #region Public Methods - #region Public Methods - - public static string GetDocPdf(SectionInfo sect, Color overrideColor) + public static string GetDocPdf(SectionInfo sect, Color overrideColor) { _MySection = sect; - DocumentInfo mydoc = sect.MyContent.MyEntry.MyDocument; - UpdateDocPdf(mydoc, overrideColor, sect); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Keeping due to Side Effect Code + DocumentInfo mydoc = sect.MyContent.MyEntry.MyDocument; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + UpdateDocPdf(overrideColor, sect); string fileName = GetFileName(sect); FileInfo fi = new FileInfo(fileName); @@ -967,17 +829,18 @@ namespace VEPROMS.CSLA.Library return fileName; } - public static bool UpdateDocPdf(DocumentInfo mydoc, Color overrideColor, ItemInfo sect) + public static bool UpdateDocPdf(Color overrideColor, ItemInfo sect) { //B2019-144 Set the document text color to Red (overlay) or Black (normal) - Color lastColor = MSWordToPDF.OverrideColor;// Remember last override color - if (MSWordToPDF.OverrideColor != overrideColor) MSWordToPDF.OverrideColor = overrideColor; + Color lastColor = OverrideColor;// Remember last override color + if (OverrideColor != overrideColor) OverrideColor = overrideColor; +#pragma warning disable IDE0059 // Unnecessary assignment of a value - keeping due to side effect code + PdfInfo myPdf = PdfInfo.Get(sect, DocReplace != null); +#pragma warning restore IDE0059 // Unnecessary assignment of a value - PdfInfo myPdf = PdfInfo.Get(sect, DocReplace != null); + //B2019-144 Set the document text color to Red (overlay) or Black (normal) + if (OverrideColor != lastColor) OverrideColor = lastColor; // Restore last override color - //B2019-144 Set the document text color to Red (overlay) or Black (normal) - if (MSWordToPDF.OverrideColor != lastColor) MSWordToPDF.OverrideColor = lastColor; // Restore last override color - //MSWordToPDF.OverrideColor = Color.Black; // B2019-090 reset to black text (when a Complete RO Report was created after printing procedure, X/Y Plot was in red text) return true; } @@ -988,10 +851,10 @@ namespace VEPROMS.CSLA.Library try { - pdfTmp = MSWordToPDF.ToPDFReplaceROs(docInfo, roids, sect, null); + pdfTmp = ToPDFReplaceROs(docInfo, roids, sect, null); } - catch (Exception ex) - { + catch (Exception) + { if (!_MissingDocs.Contains(docInfo.DocID))// B2018-071 Only add the message once to the error log { _MyLog.WarnFormat("Error trying to create PDF DocID = {0}", docInfo.DocID);// 2018-071 MS Word section could not be converted to PDF @@ -1014,16 +877,15 @@ namespace VEPROMS.CSLA.Library using (Document doc = docInfo.Get()) { DocStyle myDocStyle = sect.ActiveSection.MyDocStyle; - SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; - if (sc != null && sc.Section_WordMargin == "Y") + if (sect.ActiveSection.MyConfig is SectionConfig sc && sc.Section_WordMargin == "Y") { - using (Pdf myPdf = Pdf.MakePdf(doc, ss * 10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0, (double)sect.MSWordPageCount, buf)) {; } + using (Pdf myPdf = Pdf.MakePdf(doc, ss * 10 + DebugStatus, 0, 0, 0, 0, (double)sect.MSWordPageCount, buf)) {; } } else { - using (Pdf myPdf1 = Pdf.MakePdf(doc, ss * 10 + MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, + using (Pdf myPdf1 = Pdf.MakePdf(doc, ss * 10 + DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth, (double)sect.MSWordPageCount, buf)) {; } } @@ -1036,9 +898,10 @@ namespace VEPROMS.CSLA.Library return true; } - public static string ToPDFReplaceROs(DocumentInfo doc, List roids, ItemInfo sect, VolianStatusChange statusChange) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping doc to match legacy signatures")] + public static string ToPDFReplaceROs(DocumentInfo doc, List roids, ItemInfo sect, VolianStatusChange statusChange) { - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("WrdSec SecNum=\"{0}\" SecTitle=\"{1}\" Itemid={2}", sect.ActiveSection.DisplayNumber, sect.ActiveSection.DisplayText, sect.ItemID); // C2018-003 fixed use of getting the active section + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) BaselineMetaFile.WriteLine("WrdSec SecNum=\"{0}\" SecTitle=\"{1}\" Itemid={2}", sect.ActiveSection.DisplayNumber, sect.ActiveSection.DisplayText, sect.ItemID); // C2018-003 fixed use of getting the active section return ToPDFReplaceROs(sect, false, roids, statusChange); } @@ -1054,7 +917,7 @@ namespace VEPROMS.CSLA.Library ROFstInfo rofst = null; ROFSTLookup lookup = null; - bool convertCaretToDeltaSymbol = (sect.ActiveSection != null) ? sect.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta : false; // C2018-003 fixed use of getting the active section + bool convertCaretToDeltaSymbol = (sect.ActiveSection != null) && sect.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.ConvertCaretToDelta; // C2018-003 fixed use of getting the active section if (dvi.DocVersionAssociationCount > 0) { @@ -1092,46 +955,41 @@ namespace VEPROMS.CSLA.Library // Use positions relative to margins bool adjustMargins = true; - // Set Application Level Properties - //MyApp.Visible = false; - // Open new Document LBDocumentClass myDoc = MyApp.Documents.Open(myFile.FullName, false); try { - SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; + if (!(sect.ActiveSection.MyConfig is SectionConfig sc) || sc.Section_WordMargin == "N") + { + AdjustMargins(myDocStyle, myDoc, true); - if (sc == null || sc.Section_WordMargin == "N") - { - AdjustMargins(myDocStyle, myDoc, true); + // B2020-122 Reset RightIndent to zero if it is set AP Enhanced Background Documents/AP-RHR.2 + // B2020-136 for Ginna (RGE) only. Causes problems for WCN Training/APs/AP30E-002 + myDoc.Application.Selection.WholeStory(); - // B2020-122 Reset RightIndent to zero if it is set AP Enhanced Background Documents/AP-RHR.2 - // B2020-136 for Ginna (RGE) only. Causes problems for WCN Training/APs/AP30E-002 - myDoc.Application.Selection.WholeStory(); - - if (myDoc.Application.Selection.ParagraphFormat.RightIndent != 0 && (sect.ActiveFormat.Name.StartsWith("RGE") || sect.ActiveFormat.Name.StartsWith("Ginna"))) - { - myDoc.Application.Selection.ParagraphFormat.RightIndent = 0; - } - } - else - { - adjustMargins = false; // Use absolute positions - } - } - catch (Exception ex) - { + if (myDoc.Application.Selection.ParagraphFormat.RightIndent != 0 && (sect.ActiveFormat.Name.StartsWith("RGE") || sect.ActiveFormat.Name.StartsWith("Ginna"))) + { + myDoc.Application.Selection.ParagraphFormat.RightIndent = 0; + } + } + else + { + adjustMargins = false; // Use absolute positions + } + } + catch (Exception) + { // B2018-089 - Made error log output more useful AddErrorLogInfoMarginNotFixed(sect, "Word section could not adjust margins"); } string txtForBaseline = string.Empty; // C2018-018 save the contents of Word sections - after resolving RO values - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) Volian.Base.Library.BaselineMetaFile.WriteLine("++BgnTxt++"); + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) BaselineMetaFile.WriteLine("++BgnTxt++"); LBSelection sel = MyApp.Selection; sel.WholeStory(); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = sel.Text; + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) txtForBaseline = sel.Text; LBSelection selxy = hasRos ? FindXyPlot() : null; // look for XY Plot language typed into word section (not an RO) string pngFile = VlnSettings.TemporaryFolder + @"\XYPlot1.png"; //@"C:\Temp\XYPlot1.png"; @@ -1150,7 +1008,7 @@ namespace VEPROMS.CSLA.Library xyplot = xyplot.Replace("`", "\xB0"); xyplot = xyplot.Replace("\xF8", "\xB0"); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) { txtForBaseline = txtForBaseline.Replace("`", "\xB0"); txtForBaseline = txtForBaseline.Replace("\xF8", "\xB0"); @@ -1161,7 +1019,7 @@ namespace VEPROMS.CSLA.Library xyplot = xyplot.Replace("^", "\x394"); // delta xyplot = xyplot.Replace("\x7F", "\x394"); //delta - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) { txtForBaseline = txtForBaseline.Replace("^", "\x394"); txtForBaseline = txtForBaseline.Replace("\x7F", "\x394"); @@ -1195,7 +1053,7 @@ namespace VEPROMS.CSLA.Library else { selxy.Text = string.Empty; - if (cnt > 0) for (int icnt = 0; icnt < cnt; icnt++) selxy.Text = selxy.Text + "\r"; + if (cnt > 0) for (int icnt = 0; icnt < cnt; icnt++) selxy.Text += "\r"; } pngFile = VlnSettings.TemporaryFolder + @"\XYPlot" + filecount.ToString() + @".png"; //@"C:\Temp\XYPlot1.png"; @@ -1248,8 +1106,8 @@ namespace VEPROMS.CSLA.Library sel.WholeStory(); string roTokenForBaseline = string.Empty; - if (statusChange != null) statusChange(VolianStatusType.Initialize, sel.End, "Refreshing ROs"); - sel = hasRos ? FindRO() : null; + statusChange?.Invoke(VolianStatusType.Initialize, sel.End, "Refreshing ROs"); + sel = hasRos ? FindRO() : null; int roCount = 0; // force Print of MS Word Attachment to Final without revisions and comments @@ -1262,12 +1120,12 @@ namespace VEPROMS.CSLA.Library { if (!string.IsNullOrEmpty(sel.Text)) { - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) roTokenForBaseline = sel.Text; - if (statusChange != null) statusChange(VolianStatusType.Update, sel.Start, string.Format("{0} ROs Refreshed", roCount++)); - - // B2022-088: [JPR] Find Doc Ro button not working in Word Sections - // B2022-098: [JPR] ROs not being resolved in Word Sections - ROFSTLookup.rochild roc = GetCachedRoByAccPageID(lookup, sel.Text, convertCaretToDeltaSymbol); + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) roTokenForBaseline = sel.Text; + statusChange?.Invoke(VolianStatusType.Update, sel.Start, string.Format("{0} ROs Refreshed", roCount++)); + + // B2022-088: [JPR] Find Doc Ro button not working in Word Sections + // B2022-098: [JPR] ROs not being resolved in Word Sections + ROFSTLookup.rochild roc = GetCachedRoByAccPageID(lookup, sel.Text, convertCaretToDeltaSymbol); int roType = roc.type; string roValue = roc.value; @@ -1286,15 +1144,9 @@ namespace VEPROMS.CSLA.Library bool imageROTokenReplaced = false; string[] vals = roValue.Split("\n".ToCharArray()); - ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); - - if (roImage == null) - { - // need code to go and get an ROImaage if it exists - roImage = rofst.GetROImageByFilename(vals[0], sect); - } - - if (roImage != null) + // need code to go and get an ROImaage if it exists + ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]) ?? rofst.GetROImageByFilename(vals[0], sect); + if (roImage != null) { ROImageFile roImageFile = new ROImageFile(roImage); float width = 72 * Int32.Parse(vals[3], System.Globalization.NumberStyles.AllowHexSpecifier) / 12.0F; @@ -1335,7 +1187,7 @@ namespace VEPROMS.CSLA.Library shape.Top = pt.Y; //_MyLog.WarnFormat("Shape.Left={0}, Shape.Top={1}", shape.Left, shape.Top); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, string.Format("[{0}]", vals[0])); + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, string.Format("[{0}]", vals[0])); imageROTokenReplaced = true; } @@ -1343,7 +1195,7 @@ namespace VEPROMS.CSLA.Library if (!imageROTokenReplaced) { sel.Text = string.Format("Bad Image Link (Missing Image File:{0})", vals[0]); - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, sel.Text); + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(roTokenForBaseline, sel.Text); } } @@ -1352,7 +1204,7 @@ namespace VEPROMS.CSLA.Library try { // B2017-007 Fixed logic to properly position an XY Plot - if (Volian.Base.Library.BaselineMetaFile.IsOpen && Volian.Base.Library.BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(sel.Text, roValue); + if (BaselineMetaFile.IsOpen && BaselineMetaFile.IncludeWordSecText) txtForBaseline = txtForBaseline.Replace(sel.Text, roValue); // An X/Y Plot RO type might have text preceding the Plot Commands int pstart = roValue.IndexOf("<(); + RoPrintCache = new Dictionary(); // Check if the Rochild is in the PrintCache (use base accPageID without specific extension) if (!RoPrintCache.ContainsKey(accPageKey)) //B2023-006 pass in the actual key instead of the base key.//old code=> accPageBase)) @@ -1589,19 +1435,19 @@ namespace VEPROMS.CSLA.Library grfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; grfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; grfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; - grfx.Clear(MSWordToPDF.DebugStatus == 1 ? System.Drawing.Color.Transparent : System.Drawing.Color.White); + grfx.Clear(DebugStatus == 1 ? Color.Transparent : Color.White); - XYPlots.XYPlot.BlackColor = MSWordToPDF.OverrideColor == Color.Red ? Color.Red : Color.Black; + XYPlots.XYPlot.BlackColor = OverrideColor == Color.Red ? Color.Red : Color.Black; XYPlots.XYPlot myPlot = new XYPlots.XYPlot(xyPlot); myPlot.SetMargins(0, 0, 0, 0); - VG.IVGOutput vgOut = new VG.VGOut_Graphics(grfx); - vgOut.DebugStatus = MSWordToPDF.DebugStatus; - myPlot.Process(vgOut); + VG.IVGOutput vgOut = new VG.VGOut_Graphics(grfx) + { + DebugStatus = DebugStatus + }; + myPlot.Process(vgOut); grfx.Dispose(); - //GC.Collect(); // memory garbage collection (Regex bug) - GraphicsUnit gu = new GraphicsUnit(); retval = mf.GetBounds(ref gu); retval.Width *= dpi / resolution; @@ -1733,10 +1579,11 @@ namespace VEPROMS.CSLA.Library float newLeft = (float)myDocStyle.Layout.LeftMargin; float newLength = (float)myDocStyle.Layout.PageLength; float newWidth = (float)myDocStyle.Layout.PageWidth; - float oldTop = myDoc.PageSetup.TopMargin; - float oldLeft = myDoc.PageSetup.LeftMargin; - float oldBottom = myDoc.PageSetup.BottomMargin; - float oldRight = myDoc.PageSetup.RightMargin; + //For Debugging - Add watches + //oldTop = myDoc.PageSetup.TopMargin; + //oldLeft = myDoc.PageSetup.LeftMargin; + //oldBottom = myDoc.PageSetup.BottomMargin; + //oldRight = myDoc.PageSetup.RightMargin; float oldHeight = myDoc.PageSetup.PageHeight; float oldWidth = myDoc.PageSetup.PageWidth; @@ -1775,8 +1622,8 @@ namespace VEPROMS.CSLA.Library myDoc.PageSetup.LeftMargin = newLeft; myDoc.PageSetup.TopMargin = newTop; } - catch (Exception ex) - { + catch (Exception) + { if (_MySection != null) { // B2018-089 - Made error log output more useful @@ -1799,8 +1646,8 @@ namespace VEPROMS.CSLA.Library myDoc.PageSetup.LeftMargin = newLeft; myDoc.PageSetup.TopMargin = newTop; } - catch (Exception ex) - { + catch (Exception) + { if (_MySection != null) { // B2018-089 - Made error log output more useful @@ -2027,8 +1874,6 @@ namespace VEPROMS.CSLA.Library // newline in return string. if (nxtIndxCmd > 0) { - string mydebug = p.Substring(indxClose + 1); - for (int i = indxClose + 1; i < nxtIndxCmd; i++) { if (!System.Char.IsWhiteSpace(p[i])) @@ -2086,7 +1931,7 @@ namespace VEPROMS.CSLA.Library private static int WordColor(System.Drawing.Color color) { - System.Drawing.Color c1 = System.Drawing.Color.FromArgb(0, color.B, color.G, color.R); + System.Drawing.Color c1 = Color.FromArgb(0, color.B, color.G, color.R); return c1.ToArgb(); } @@ -2147,15 +1992,14 @@ namespace VEPROMS.CSLA.Library find.MatchSoundsLike = false; find.MatchAllWordForms = false; - // B2022-053 in a Barakah word attachment (ST procedure set procedure DG-5204) the RO tokens are not resolved after a certain - // point in a table. - // Turns out this happens when a table cell had text that begins with a "<" and it does not end with a ">" and there is no - // space or other word following that text in the table cell. For example, there was a table cell who's text - // was "<90" cause the Word Find command to return an entire table row which cause PROMS to stop processing - // the rest of the Word attachment section. - bool tryagain = false; - - do + // B2022-053 in a Barakah word attachment (ST procedure set procedure DG-5204) the RO tokens are not resolved after a certain + // point in a table. + // Turns out this happens when a table cell had text that begins with a "<" and it does not end with a ">" and there is no + // space or other word following that text in the table cell. For example, there was a table cell who's text + // was "<90" cause the Word Find command to return an entire table row which cause PROMS to stop processing + // the rest of the Word attachment section. + bool tryagain; + do { tryagain = false; executeResult = find.Execute(); @@ -2236,25 +2080,19 @@ namespace VEPROMS.CSLA.Library #region Fields // B2019-161 When tracking timing time this action - private static VolianTimer _TimeActivity = new VolianTimer("DocumentExt.cs CloseWordApp_Tick", 1548); + private static readonly VolianTimer _TimeActivity = new VolianTimer("DocumentExt.cs CloseWordApp_Tick", 1548); - LBApplicationClass _MyApp; + #endregion - #endregion + #region Constructor - #region Constructor + public LBApplicationClass MyApp { get; set; } - public LBApplicationClass MyApp - { - get { return _MyApp; } - set { _MyApp = value; } - } + #endregion - #endregion + #region Public Methods - #region Public Methods - - public CloseWordApp(LBApplicationClass myApp, int interval) + public CloseWordApp(LBApplicationClass myApp, int interval) { MyApp = myApp; Interval = interval; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/FigureExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/FigureExt.cs index 62ecebf4..5dfb0852 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/FigureExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/FigureExt.cs @@ -1,12 +1,8 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.IO; -using Volian.Base.Library; namespace VEPROMS.CSLA.Library { @@ -16,13 +12,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class AddByROFstIDImageIDCriteria { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - private string _ImagedIDs; - public string ImagedIDs - { get { return _ImagedIDs; } } - public AddByROFstIDImageIDCriteria(int rOFstID, string imagedIDs) + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + private readonly string _ImagedIDs; + public string ImagedIDs => _ImagedIDs; + public AddByROFstIDImageIDCriteria(int rOFstID, string imagedIDs) { _ROFstID = rOFstID; _ImagedIDs = imagedIDs; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/FolderExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/FolderExt.cs index 61904404..4b4e70ae 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/FolderExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/FolderExt.cs @@ -13,10 +13,7 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.Drawing; -using System.Collections.Generic; using System.ComponentModel; using System.Text.RegularExpressions; using System.Linq; @@ -40,73 +37,19 @@ namespace VEPROMS.CSLA.Library return _FolderConfig; } } - public void FolderConfigRefresh() - { - _FolderConfig = null; - } - private void _FolderConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) - { - Config = _FolderConfig.ToString(); - } - #endregion - public override string ToString() - { - return _Title; - } - #region IVEReadOnlyItem - //public System.Collections.IList GetChildren() - //{ - // if (FolderDocVersionCount != 0) return FolderDocVersions; - // if (ChildFolderCount != 0) return ChildFolders; - // return null; - //} - //public bool HasChildren - //{ - // get { return _FolderDocVersionCount > 0 || _ChildFolderCount > 0; } - //} - //public IVEDrillDown ActiveParent - //{ - // get - // { - // return MyParent; - // } - //} - //private Format _ActiveFormat = null; - //public Format ActiveFormat - //{ - // get - // { - // if (_ActiveFormat == null) - // _ActiveFormat = (LocalFormat != null ? LocalFormat : ActiveParent != null ? ActiveParent.ActiveFormat : null); - // return _ActiveFormat; - // } - // set - // { - // _ActiveFormat = null; // Reset - // } - //} - //public Format LocalFormat - //{ - // get { return MyFormat; } - //} - public ConfigDynamicTypeDescriptor MyConfig - { - get { return FolderConfig; } - } - #endregion - #region MakeFolders for ManualOrder - public static Folder MakeFolder(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, string config, DateTime dts, string usrID) - { - return MakeFolder(myParent, myConnection, name, title, shortName, myFormat, null, config, dts, usrID); - } - public static Folder MakeFolder(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, string config) - { - return MakeFolder(myParent, myConnection, name, title, shortName, myFormat, null, config); - } - #endregion - public FolderInfo MyFolderInfo - { get { return FolderInfo.Get(FolderID); } } - } + public void FolderConfigRefresh() => _FolderConfig = null; + private void _FolderConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) => Config = _FolderConfig.ToString(); + #endregion + public override string ToString() => _Title; + #region IVEReadOnlyItem + public ConfigDynamicTypeDescriptor MyConfig => FolderConfig; + #endregion + #region MakeFolders for ManualOrder + public static Folder MakeFolder(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, string config, DateTime dts, string usrID) => MakeFolder(myParent, myConnection, name, title, shortName, myFormat, null, config, dts, usrID); + public static Folder MakeFolder(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, string config) => MakeFolder(myParent, myConnection, name, title, shortName, myFormat, null, config); + #endregion + public FolderInfo MyFolderInfo => FolderInfo.Get(FolderID); + } public partial class FolderInfo:IVEDrillDownReadOnly { #region Search Paths @@ -125,26 +68,20 @@ namespace VEPROMS.CSLA.Library return _SearchDVPath; } } - public string SearchPath { get { return ""; } } + public string SearchPath => ""; - // B2021-076: Proms search results are not presented in order when printed to PDF - public string SearchDefaultSort { get { return string.Empty; } } - - #endregion - #region Folder Config (Read-Only) - [NonSerialized] + // B2021-076: Proms search results are not presented in order when printed to PDF + public string SearchDefaultSort => string.Empty; + + #endregion + #region Folder Config (Read-Only) + [NonSerialized] private FolderConfig _FolderConfig; - public FolderConfig FolderConfig - { get { - return (_FolderConfig != null ? _FolderConfig : _FolderConfig = new FolderConfig(this)); - } } - private void FolderConfigRefresh() - { - _FolderConfig = null; - } - #endregion - #region SortingChildren - private static bool IsInManualOrderNullFix = false; + public FolderConfig FolderConfig => _FolderConfig ?? (_FolderConfig = new FolderConfig(this)); + private void FolderConfigRefresh() => _FolderConfig = null; + #endregion + #region SortingChildren + private static bool IsInManualOrderNullFix = false; [NonSerialized] public Csla.SortedBindingList _SortedChildFolders; @@ -180,8 +117,6 @@ namespace VEPROMS.CSLA.Library if (_SortedChildFolders == null) { _SortedChildFolders = new SortedBindingList(ChildFolders); - //_SortedChildFolders.ApplySort("FolderID", ListSortDirection.Ascending); - //_SortedChildFolders.ApplySort("Name", ListSortDirection.Ascending); } else if (_SortedChildFolders.Count != ChildFolders.Count) { @@ -266,43 +201,20 @@ namespace VEPROMS.CSLA.Library public System.Collections.IList GetChildren() { if(FolderDocVersionCount != 0)return FolderDocVersions; - //if (ChildFolderCount != 0) return ChildFolders; if (ChildFolderCount != 0) return SortedChildFolders; return null; } - //public bool ChildrenAreLoaded - //{ - // get { return _FolderDocVersions != null || _ChildFolders != null; } - //} - public bool HasChildren - { - get { return FolderDocVersionCount > 0 || ChildFolderCount > 0; } - } - public IVEDrillDownReadOnly ActiveParent - { - get - { - return MyParent; - } - } - public FormatInfo ActiveFormat - { - get { return LocalFormat != null ? LocalFormat : ( ActiveParent != null ? ActiveParent.ActiveFormat : null); } - } - public FormatInfo LocalFormat - { - get { return MyFormat; } - } - public ConfigDynamicTypeDescriptor MyConfig - { - get { return FolderConfig; } - } - /// - /// These settings are set on the user interface side. - /// This is used to control whether the Name and/or Title is displayed - /// next to the tree nodes in the user interface - /// - private bool _DisplayTreeNodeNames = true; + public bool HasChildren => FolderDocVersionCount > 0 || ChildFolderCount > 0; + public IVEDrillDownReadOnly ActiveParent => MyParent; + public FormatInfo ActiveFormat => LocalFormat ?? (ActiveParent?.ActiveFormat); + public FormatInfo LocalFormat => MyFormat; + public ConfigDynamicTypeDescriptor MyConfig => FolderConfig; + /// + /// These settings are set on the user interface side. + /// This is used to control whether the Name and/or Title is displayed + /// next to the tree nodes in the user interface + /// + private bool _DisplayTreeNodeNames = true; public bool DisplayTreeNodeNames { get { return _DisplayTreeNodeNames; } @@ -326,12 +238,7 @@ namespace VEPROMS.CSLA.Library rtnstr += Title; } return rtnstr; - //return string.Format("{0} - {1}", Name, Title); } - //public string ToString(string str, System.IFormatProvider ifp) - //{ - // return ToString(); - //} #endregion public Color BackColor { get { return FolderConfig.Default_BkColor; } } @@ -351,15 +258,10 @@ namespace VEPROMS.CSLA.Library #region Extension partial class FolderInfoExtension : extensionBase { - public override void Refresh(FolderInfo tmp) - { - tmp.FolderConfigRefresh(); - } - } + public override void Refresh(FolderInfo tmp) => tmp.FolderConfigRefresh(); + } public static FolderInfo GetTop() { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Folder"); try { FolderInfo tmp = DataPortal.Fetch(new TopCriteria()); @@ -375,7 +277,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FolderInfo.GetTop", ex); } } - private void DataPortal_Fetch(TopCriteria criteria) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + private void DataPortal_Fetch(TopCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FolderInfo.DataPortal_Fetch", GetHashCode()); try @@ -416,41 +319,11 @@ namespace VEPROMS.CSLA.Library { public TopCriteria() { ;} } - public bool IsFolder - { - get - { - return true; - } - } - public bool IsDocVersion - { - get - { - return false; - } - } - public bool IsProcedure - { - get - { - return false; - } - } - public bool IsSection - { - get - { - return false; - } - } - public bool IsStep - { - get - { - return false; - } - } - } + public bool IsFolder => true; + public bool IsDocVersion => false; + public bool IsProcedure => false; + public bool IsSection => false; + public bool IsStep => false; + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/FontTab.cs b/PROMS/VEPROMS.CSLA.Library/Extension/FontTab.cs deleted file mode 100644 index 71618376..00000000 --- a/PROMS/VEPROMS.CSLA.Library/Extension/FontTab.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace VEPROMS.CSLA.Library -{ - //public static class FontTab - //{ - // private static Dictionary FontIndx = null; - // // This dictionary takes a color name and converts it to the rtf string: - // private static Dictionary FontRtf = null; - // public enum E_Fonts : int - // { - // None = 0, PrestigeEliteTall = 64, CourierNew = 2, TimesNewRoman = 0, LetterGothic = 66, Arial = 202, VolianDraw = 70, GothicUltra = 63, LetterGothicTall = 67, VolianScript = 71, ArialUnicode = 35 - // } - // #region FontIndex - // /// - // /// GetIndex - Use this to get the number of the font in the font table based on the input - // /// string. - // /// - // /// - // /// - // public static int GetIndex(string font) - // { - // // if the dictionary hasn't been set yet, - // if (FontIndx==null) - // { - // FontIndx = new Dictionary(); - // FontIndx["Prestige Elite Tall"] = 64; - // FontIndx["Courier New"] = 2; - // FontIndx["Times New Roman"] = 0; - // FontIndx["Letter Gothic"] = 66; - // FontIndx["Arial"] = 202; - // FontIndx["Volian Draw"] = 70; - // FontIndx["Gothic Ultra"] = 63; - // FontIndx["Letter Gothic Tall"] = 67; - // FontIndx["VolianScript"] = 71; - // FontIndx["Arial Unicode"] = 35; - - // } - // return FontIndx[font]; - // } - // #endregion - // #region ColorRtf - // /// - // /// GetTableString - Use this to get the string to add to font table based on the input - // /// string. - // /// - // public static string GetTableString(string font) - // { - // if (FontRtf == null) - // { - // FontRtf = new Dictionary(); - // FontRtf["Prestige Elite Tall"] = "{\\f64\\fmodern\\fcharset2\\fprq1 Prestige Elite Tall;}"; - // FontRtf["Courier New"] = "{\\f2\\fmodern\\fcharset0\\fprq1 Courier New;}"; - // FontRtf["Times New Roman"] = "{\\f0\\froman\\fcharset0\\fprq2 Times New Roman;}"; - // FontRtf["Letter Gothic"] = "{\\f66\\fmodern\\fcharset2\\fprq1 Letter Gothic;}"; - // FontRtf["Arial"] = "{\\f1\\fswiss\\fcharset0\\fprq2 Arial;}"; - // FontRtf["Volian Draw"] = "{\\f70\\fmodern\\fcharset2\\fprq1 VolianDraw;}"; - // FontRtf["Gothic Ultra"] = "{\\f63\\fmodern\\fcharset2\\fprq1 Gothic Ultra;}"; - // FontRtf["Letter Gothic Tall"] = "{\\f67\\fmodern\\fcharset2\\fprq1 Letter Gothic Tall;}"; - // FontRtf["VolianScript"] = "{\\f71\\fswiss\\fcharset2\\fprq2 VolianScript;}"; - // FontRtf["Arial Unicode"] = "{\\f35\\fswiss\\fcharset128\\fprq2 Arial Unicode MS;}"; - // } - // return FontRtf[font]; - // } - // #endregion - //} -} diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/FormatExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/FormatExt.cs index 44176423..080a141c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/FormatExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/FormatExt.cs @@ -13,10 +13,8 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; using System.IO; using System.Xml; -using System.Drawing; using System.ComponentModel; using System.Collections.Generic; using Volian.Base.Library; @@ -33,17 +31,12 @@ namespace VEPROMS.CSLA.Library get { return _AllFormats; } set { _AllFormats = value; } } - public CriteriaAllFormats(bool allFormats) - { - _AllFormats = allFormats; - } - } + public CriteriaAllFormats(bool allFormats) => _AllFormats = allFormats; + } public partial class Format { public static Format GetJustFormat(int formatID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Format"); try { Format tmp = GetCachedByPrimaryKey(formatID); @@ -67,14 +60,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteriaJustFormat { - private int _FormatID; - public int FormatID - { get { return _FormatID; } } - public PKCriteriaJustFormat(int formatID) - { - _FormatID = formatID; - } - } + private readonly int _FormatID; + public int FormatID => _FormatID; + public PKCriteriaJustFormat(int formatID) => _FormatID = formatID; + } private void DataPortal_Fetch(PKCriteriaJustFormat criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.DataPortal_Fetch JustFormat", GetHashCode()); @@ -123,92 +112,66 @@ namespace VEPROMS.CSLA.Library } public class FormatEventArgs { - private string _Status; - public string Status - { - get { return _Status; } - set { _Status = value; } - } - public FormatEventArgs(string status) - { - _Status = status; - } - } + public string Status { get; set; } + public FormatEventArgs(string status) => Status = status; + } public delegate void FormatEvent(object sender,FormatEventArgs args); public partial class Format:IFormatOrFormatInfo { #region PlantFormat [NonSerialized] private PlantFormat _PlantFormat; - public PlantFormat PlantFormat - { get { return (_PlantFormat != null ? _PlantFormat : _PlantFormat = new PlantFormat(this, Config)); } } - #endregion - public static event FormatEvent FormatLoaded; - private static void OnFormatLoaded(object sender, FormatEventArgs args) - { - if (FormatLoaded != null) - FormatLoaded(sender, args); - } - public IFormatOrFormatInfo MyIParent { get { return MyParent; } } - public override string ToString() - { - //return Name; - //return PlantFormat.FormatData.Name; - return FullName; - } - public string FullName + public PlantFormat PlantFormat => _PlantFormat ?? (_PlantFormat = new PlantFormat(this, Config)); + #endregion + public static event FormatEvent FormatLoaded; + private static void OnFormatLoaded(object sender, FormatEventArgs args) => FormatLoaded?.Invoke(sender, args); + public IFormatOrFormatInfo MyIParent => MyParent; + public override string ToString() => FullName; + public string FullName { get { - if (ParentID == 1) return Description + " (" + Name + ")"; - if (Description.StartsWith("*")) return Description.Substring(1) + " (" + Name + ")"; + if (ParentID == 1) return $"{Description} ({Name})"; + if (Description.StartsWith("*")) return $"{Description.Substring(1)} ({Name})"; // C2019-029: if UCF, just use description & name, using parent is confusing - if (Config != null && Config != "") return Description + " (" + Name + ")"; - return MyParent.Description + " - " + Description + " (" + Name + ")"; + if (Config != null && Config != "") return $"{Description} ({Name})"; + return $"{MyParent.Description} - {Description} ({Name})"; } } public static void UpdateFormats(string fmtPath, string genmacPath) { - Format basefmt = null; - Format parent = null; - - - // Load base format. - basefmt = AddFormatToDB(null, "base", false, DateTime.Now, "Migration", fmtPath, genmacPath); - if (basefmt == null) return; + // Load base format. + Format basefmt = AddFormatToDB(null, "base", false, "Migration", fmtPath, genmacPath); + if (basefmt == null) return; // now loop through all files... If there is an _ in the name, it's a subformat // (for example, AEP_00.xml) skip it in main loop, it's handled for each format. DirectoryInfo di = new DirectoryInfo(fmtPath); //(@"c:\development\fmtall"); FileInfo[] fis = di.GetFiles("*.xml"); - OnFormatLoaded(null, new FormatEventArgs(fis.Length.ToString() + " Formats to Load")); + OnFormatLoaded(null, new FormatEventArgs($"{fis.Length} Formats to Load")); foreach (FileInfo fi in fis) { - //if (fi.Name.ToUpper() == "WCN2ALL.XML"|| fi.Name.ToUpper() == "OHLPALL.XML") - //{ - bool issub = (fi.Name.IndexOf("_") > 0) ? true : false; + bool issub = (fi.Name.IndexOf("_") > 0); if (!issub && fi.Name.ToLower() != "baseall.xml") { string fmtname = fi.Name.Substring(0, fi.Name.Length - 7); // remove the all.xml part of the filename. try { - parent = AddFormatToDB(basefmt, fmtname, issub, DateTime.Now, "Migration", fmtPath, genmacPath); - if (parent != null) + Format parent = AddFormatToDB(basefmt, fmtname, issub, "Migration", fmtPath, genmacPath); + if (parent != null) { // now see if there are any subformats associated with this, if so // add them here... DirectoryInfo sdi = new DirectoryInfo(fmtPath); //("c:\\development\\fmtall"); - FileInfo[] sfis = di.GetFiles(fmtname + "_*.xml"); + FileInfo[] sfis = di.GetFiles($"{fmtname}_*.xml"); foreach (FileInfo sfi in sfis) { string nm = sfi.Name.Substring(0, sfi.Name.Length - 7); - OnFormatLoaded(null, new FormatEventArgs("Loading SubFormat " + sfi.Name)); - //Console.WriteLine("Processing {0}", sfi.Name); - //frmMain.Status = string.Format("Processing Format {0}", sfi.Name); + OnFormatLoaded(null, new FormatEventArgs($"Loading SubFormat {sfi.Name}")); try { - AddFormatToDB(parent, nm, true, DateTime.Now, "Migration",fmtPath,genmacPath); + AddFormatToDB(parent, nm, true, "Migration",fmtPath,genmacPath); } catch (Exception ex) { @@ -242,7 +205,7 @@ namespace VEPROMS.CSLA.Library string fmtname = Path.GetFileNameWithoutExtension(fi.Name); try { - AddEPFormatToDB(fmtname, DateTime.Now, VlnSettings.UserID, epPath); + AddEPFormatToDB(fmtname, VlnSettings.UserID, epPath); } catch (Exception ex) { @@ -283,16 +246,15 @@ namespace VEPROMS.CSLA.Library _ = LookupFormats; } - private static Format AddFormatToDB(Format parent, string format, bool issub, DateTime Dts, string Userid, string fmtPath, string genmacPath) + private static Format AddFormatToDB(Format parent, string format, bool issub, string Userid, string fmtPath, string genmacPath) { string fmtdata = null; FileInfo fmtfi = null; string genmacdata = null; XmlDocument xd = null; - OnFormatLoaded(null, new FormatEventArgs("Loading Format "+format)); - //string path = "c:\\development\\fmtall\\" + format + "all.xml"; - string path = fmtPath + "\\" + format + "all.xml"; + OnFormatLoaded(null, new FormatEventArgs($"Loading Format {format}")); + string path = $"{fmtPath}\\{format}all.xml"; if (File.Exists(path)) { try @@ -301,12 +263,11 @@ namespace VEPROMS.CSLA.Library fmtfi = new FileInfo(path); xd = new XmlDocument(); xd.Load(srf); - //xd.Load(path); fmtdata = xd.OuterXml; } - catch (Exception ex) - { - OnFormatLoaded(null, new FormatEventArgs("Error Loading Format " + format)); + catch (Exception) + { + OnFormatLoaded(null, new FormatEventArgs($"Error Loading Format {format}")); _MyLog.ErrorFormat("AddFormatToDB('{0}','{1}')", (parent == null)?"Base": parent.Name, path); return null; } @@ -315,8 +276,7 @@ namespace VEPROMS.CSLA.Library // Do we need genmac - only if non-subformat if (!issub) { - //path = "c:\\development\\genmacall\\" + format + ".svg"; - path = genmacPath + "\\" + format + ".svg"; + path = $"{genmacPath}\\{format}.svg"; if (File.Exists(path)) { try @@ -327,9 +287,8 @@ namespace VEPROMS.CSLA.Library //xdg.Load(path); genmacdata = xdg.OuterXml; } - catch (Exception ex) - { - //frmMain.AddError(ex, "AddFormatToDB('{0}','{1}')", parent.Name, path); + catch (Exception) + { _MyLog.ErrorFormat("AddFormatToDB('{0}','{1}')", parent.Name, path); return null; } @@ -344,12 +303,11 @@ namespace VEPROMS.CSLA.Library if (parent != null) { XmlNode nmnode = xd.SelectSingleNode("//FormatData"); - if (nmnode is XmlElement) - { - XmlElement xm = (XmlElement)nmnode; - nmattr = xm.GetAttribute("Name"); - } - } + if (nmnode is XmlElement xm) + { + nmattr = xm.GetAttribute("Name"); + } + } // use the format name if base or non sub. If it's a sub, remove the "_". string fname = issub ? format.Replace("_", "") : format; Format rec = null; @@ -369,40 +327,39 @@ namespace VEPROMS.CSLA.Library rec = rec.Save(); } } - catch (Exception ex) + catch (Exception) { - //frmMain.AddError(ex, "AddFormatToDB-make format('{0}','{1}')", parent.Name, path); + //Do Nothing --- if Debugging: frmMain.AddError(ex, "AddFormatToDB-make format('{0}','{1}')", parent.Name, path); } return rec; } //C2025-023 - Electronic Procedures - Modifications to PROMS //Procedure to load the EP format fiels into the DB - private static void AddEPFormatToDB(string formatname, DateTime Dts, string Userid, string epPath) + private static void AddEPFormatToDB(string formatname, string Userid, string epPath) { string fmtdata = null; - FileInfo fmtfi = null; - XmlDocument xd = null; + OnFormatLoaded(null, new FormatEventArgs($"Loading Format {formatname}")); - OnFormatLoaded(null, new FormatEventArgs("Loading Format " + formatname)); - - string path = Path.Combine(epPath, formatname + ".xml"); + string path = Path.Combine(epPath, $"{formatname}.xml"); if (File.Exists(path)) { try { using (StreamReader srf = new StreamReader(path)) { - fmtfi = new FileInfo(path); - xd = new XmlDocument(); - xd.XmlResolver = null; - xd.Load(srf); + FileInfo fmtfi = new FileInfo(path); + XmlDocument xd = new XmlDocument + { + XmlResolver = null + }; + xd.Load(srf); fmtdata = xd.OuterXml; } } - catch (Exception ex) + catch (Exception) { - OnFormatLoaded(null, new FormatEventArgs("Error Loading Format " + formatname)); + OnFormatLoaded(null, new FormatEventArgs($"Error Loading Format {formatname}")); _MyLog.ErrorFormat($"AddEPFormatToDB('{path}')"); return; } @@ -414,7 +371,7 @@ namespace VEPROMS.CSLA.Library { EPFormatFile.UpdateEPFormat(formatname, fmtdata, Userid); } - catch (Exception ex) + catch (Exception) { _MyLog.ErrorFormat($"AddFormatToDB-make format('{path}')"); } @@ -441,13 +398,10 @@ public partial class FormatInfo : IFormatOrFormatInfo [Serializable()] private class FormatIDCriteria { - private int _FormatID; - public int FormatID { get { return _FormatID; } } - public FormatIDCriteria(int formatID) - { - _FormatID = formatID; - } - } + private readonly int _FormatID; + public int FormatID => _FormatID; + public FormatIDCriteria(int formatID) => _FormatID = formatID; + } private void DataPortal_Fetch(FormatIDCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_Fetch", GetHashCode()); @@ -478,17 +432,10 @@ public partial class FormatInfo : IFormatOrFormatInfo throw new DbCslaException("FormatInfo.DataPortal_Fetch", ex); } } - //end transition report stuff - public virtual Format GetJustFormat() - { - return _Editable = Format.GetJustFormat(_FormatID); - } - public static bool HasLatestChanges() - { - if (!HasSeqTabFmtTabToken()) return false; - return true; - } - private static bool HasSeqTabFmtTabToken() + //end transition report stuff + public virtual Format GetJustFormat() => _Editable = Format.GetJustFormat(_FormatID); + public static bool HasLatestChanges() => HasSeqTabFmtTabToken(); + private static bool HasSeqTabFmtTabToken() { using (FormatInfo fi = FormatInfo.Get("WCN2")) { @@ -517,17 +464,13 @@ public partial class FormatInfo : IFormatOrFormatInfo return _PROMSBaseFormat; } } - public static void Reset() - { - _PROMSBaseFormat = null; - } + public static void Reset() => _PROMSBaseFormat = null; public static FormatInfo Get(string name) { try { FormatInfo tmp = DataPortal.Fetch(new NameCriteria(name)); - //AddToCache(tmp); if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up FormatInfo @@ -563,14 +506,10 @@ public partial class FormatInfo : IFormatOrFormatInfo } protected class NameCriteria { - private string _Name; - public string Name - { get { return _Name; } } - public NameCriteria(string name) - { - _Name = name; - } - } + private readonly string _Name; + public string Name => _Name; + public NameCriteria(string name) => _Name = name; + } private void DataPortal_Fetch(NameCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfo.DataPortal_Fetch", GetHashCode()); @@ -611,17 +550,11 @@ public partial class FormatInfo : IFormatOrFormatInfo #region PlantFormat [NonSerialized] private PlantFormat _PlantFormat; - public PlantFormat PlantFormat - { get { return (_PlantFormat != null ? _PlantFormat : _PlantFormat = new PlantFormat(this, Config)); } } - #endregion - public IFormatOrFormatInfo MyIParent { get { return MyParent; } } - public override string ToString() - { - //return Name; - //return PlantFormat.FormatData.Name; - return FullName; - } - public string FullName + public PlantFormat PlantFormat => _PlantFormat ?? (_PlantFormat = new PlantFormat(this, Config)); + #endregion + public IFormatOrFormatInfo MyIParent => MyParent; + public override string ToString() => FullName; + public string FullName { get { @@ -632,15 +565,9 @@ public partial class FormatInfo : IFormatOrFormatInfo return MyParent.Description + " - " + Description + " (" + Name + ")"; } } - public StepSectionLayoutData MyStepSectionLayoutData - { - get { return PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData; } - } - public StepSectionPrintData MyStepSectionPrintData - { - get { return PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData; } - } - } + public StepSectionLayoutData MyStepSectionLayoutData => PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData; + public StepSectionPrintData MyStepSectionPrintData => PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData; + } public partial class FormatInfoList { /// @@ -658,7 +585,8 @@ public partial class FormatInfo : IFormatOrFormatInfo throw new DbCslaException("Error on FormatInfoList.GetAll", ex); } } - private void DataPortal_Fetch(CriteriaAllFormats myCrit) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + private void DataPortal_Fetch(CriteriaAllFormats myCrit) { this.RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfoList.DataPortal_Fetch", GetHashCode()); @@ -716,7 +644,8 @@ public partial class FormatInfo : IFormatOrFormatInfo protected class FormatInfoListUsedCriteria { } - private void DataPortal_Fetch(FormatInfoListUsedCriteria criteria) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + private void DataPortal_Fetch(FormatInfoListUsedCriteria criteria) { try { @@ -749,13 +678,13 @@ public partial class FormatInfo : IFormatOrFormatInfo } public class FormatVersion { - private string _Title; - public string Title { get { return _Title; } } - private int _FormatID; - public int FormatID { get { return _FormatID; } } - private int _VersionID; - public int VersionID { get { return _VersionID; } } - public FormatVersion(string title, int formatID, int versionID) + private readonly string _Title; + public string Title => _Title; + private readonly int _FormatID; + public int FormatID => _FormatID; + private readonly int _VersionID; + public int VersionID => _VersionID; + public FormatVersion(string title, int formatID, int versionID) { _Title = title; _FormatID = formatID; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/GridExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/GridExt.cs index a4b023d8..8bdcc1a2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/GridExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/GridExt.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; using Csla; @@ -12,69 +11,23 @@ namespace VEPROMS.CSLA.Library // B2022-047 - refresh the Content/Text field for table. Get all grids in database. public class CriteriaAllGridIds { - bool _AllGridIds; - public bool AllGridIds - { - get { return _AllGridIds; } - set { _AllGridIds = value; } - } - public CriteriaAllGridIds(bool allGridIds) - { - _AllGridIds = allGridIds; - } - } + public bool AllGridIds { get; set; } + public CriteriaAllGridIds(bool allGridIds) => AllGridIds = allGridIds; + } [Serializable()] [TypeConverter(typeof(FormatInfoListConverter))] public partial class GridInfoList : ReadOnlyListBase { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - internal new IList Items - { get { return base.Items; } } - 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; } } - ~GridInfoList() - { - _CountFinalized++; - } + #endregion + private bool _Disposed = false; public void Dispose() { if (_Disposed) return; - _CountDisposed++; _Disposed = true; } public static GridInfoList _GridInfoList = null; - /// - /// Return a list of all GridInfo. Commented out - GridInfoList was added to fix B2022-047. Have this code here in - /// case it is needed in the future. - /// - //public static GridInfoList Get() - //{ - // try - // { - // if (_GridInfoList != null) - // return _GridInfoList; - // GridInfoList tmp = DataPortal.Fetch(); - // _GridInfoList = tmp; - // return tmp; - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on FormatInfoList.Get", ex); - // } - //} public static List GetIds() { try @@ -108,53 +61,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on GridInfoList.Get", ex); } } - // Commented out - GridInfoList was added to fix B2022-047. Have this code here in - // case it is needed in the future. The associated query 'getGrids' does not exist. - //private void DataPortal_Fetch() - //{ - // this.RaiseListChangedEvents = false; - // if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridInfoList.DataPortal_Fetch", GetHashCode()); - // try - // { - // using (SqlConnection cn = Database.VEPROMS_SqlConnection) - // { - // using (SqlCommand cm = cn.CreateCommand()) - // { - // cm.CommandType = CommandType.StoredProcedure; - // cm.CommandText = "getGrids"; - // cm.CommandTimeout = Database.DefaultTimeout; - // using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) - // { - // IsReadOnly = false; - // while (dr.Read()) this.Add(new GridInfo(dr)); - // IsReadOnly = true; - // } - // } - // } - // } - // catch (Exception ex) - // { - // if (_MyLog.IsErrorEnabled) _MyLog.Error("GridInfoList.DataPortal_Fetch", ex); - // throw new DbCslaException("GridInfoList.DataPortal_Fetch", ex); - // } - // this.RaiseListChangedEvents = true; - //} } public partial class GridInfo { - public void ResetContent(Grid myGrid) - { - RefreshFields(myGrid); - } - public void SetData(string myData) + public void ResetContent(Grid myGrid) => RefreshFields(myGrid); + public void SetData(string myData) { _Data = myData; RemoveFromCache(this); } public static GridInfo GetNonCached(int contentID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Grid"); try { GridInfo tmp = DataPortal.Fetch(new PKCriteria(contentID)); diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs index f153243f..6824a985 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ItemExt.cs @@ -129,18 +129,17 @@ namespace VEPROMS.CSLA.Library bool wasfirstchild = false; ItemInfo parentInfo = pInfo as ItemInfo; DocVersionInfo parentInfoDV = pInfo as DocVersionInfo; - IList children = null; - E_FromType partType = 0; // this is needed later to determine sub-group type. - if (parentInfo != null) - { - // this may have subgroups, need to use part type to get children list... - ItemInfo thisinfo = ItemInfo.Get(ItemID); - partType = thisinfo.FirstSibling.ItemParts[0].PartType; - children = (IList)parentInfo.Lookup((int)partType); - } - else - children = (IList)parentInfoDV.GetChildren(); - int numChild = children.Count; + E_FromType partType = 0; // this is needed later to determine sub-group type. + IList children; + if (parentInfo != null) + { + // this may have subgroups, need to use part type to get children list... + ItemInfo thisinfo = ItemInfo.Get(ItemID); + partType = thisinfo.FirstSibling.ItemParts[0].PartType; + children = (IList)parentInfo.Lookup((int)partType); + } + else + children = (IList)parentInfoDV.GetChildren(); if (this.PreviousID == null) wasfirstchild = true;//Use PreviousID rather than MyPrevious so the item is not cached Item origNextItem = null; @@ -229,9 +228,8 @@ namespace VEPROMS.CSLA.Library this.MyPrevious = null; this.Save(); } - if (origNextItem != null) origNextItem.Dispose(); - if (parentInfo != null) - parentInfo.MyContent.RefreshContentParts(); + origNextItem?.Dispose(); + parentInfo?.MyContent.RefreshContentParts(); } //ShowItemAndSections("After MoveItem", pInfo as ItemInfo); if (parentInfoDV != null) @@ -264,7 +262,7 @@ namespace VEPROMS.CSLA.Library DocVersionInfo parentInfoDV = parentInfoDD as DocVersionInfo; using (Content cont = Content.New(number, title, type, null, null)) { - using (Item fromitem = previousInfo == null ? null : previousInfo.Get()) + using (Item fromitem = previousInfo?.Get()) { ItemInfo nextInfo = null; // Check to see if the item is being inserted in the middle of some items. if (previousInfo != null) @@ -326,10 +324,8 @@ namespace VEPROMS.CSLA.Library } } } - if (parentInfo != null) - parentInfo.MyContent.RefreshContentParts(); - if (parentInfoDV != null) - parentInfoDV.ResetProcedures(); + parentInfo?.MyContent.RefreshContentParts(); + parentInfoDV?.ResetProcedures(); return newitemid; } } @@ -548,13 +544,11 @@ namespace VEPROMS.CSLA.Library foreach (ItemInfo itm in movedItems) ItemInfo.Refresh(itm); } - DocVersionInfo parentInfoDV = pInfo as DocVersionInfo; - if (parentInfoDV != null) - DocVersionInfo.ResetProcedures(parentInfoDV.VersionID); - ItemInfo parentInfo = pInfo as ItemInfo; - if (parentInfo != null) - ItemInfo.ResetParts(parentInfo.ItemID); - } + if (pInfo is DocVersionInfo parentInfoDV) + DocVersionInfo.ResetProcedures(parentInfoDV.VersionID); + if (pInfo is ItemInfo parentInfo) + ItemInfo.ResetParts(parentInfo.ItemID); + } public static void Refresh(ItemInfo tmp) { @@ -569,18 +563,18 @@ namespace VEPROMS.CSLA.Library { if (_PreviousID != tmp.PreviousID) { - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value + MyPrevious?.RefreshNextItems(); // Update List for old value _PreviousID = tmp.PreviousID; // Update the value } _MyPrevious = null; // Reset list so that the next line gets a new list - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value + MyPrevious?.RefreshNextItems(); // Update List for new value //if (_ContentID != tmp.ContentID) //{ - if (MyContent != null) MyContent.RefreshContentItems(); // Update List for old value + MyContent?.RefreshContentItems(); // Update List for old value _ContentID = tmp.ContentID; // Update the value //} _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentItems(); // Update List for new value + MyContent?.RefreshContentItems(); // Update List for new value _DTS = tmp.DTS; _UserID = tmp.UserID; _ItemInfoExtension.Refresh(this); @@ -689,14 +683,13 @@ namespace VEPROMS.CSLA.Library itemInfo.ActiveSection = (itemInfo as SectionInfo) ?? sectionInfo;// - possible fix for not accessing correct format else itemInfo.ActiveSection = sectionInfo;// If not a Word Section use the parent - itemInfo.ActiveFormat = itemInfo.MyContent.MyFormat != null ? itemInfo.MyContent.MyFormat : sectionInfo == null ? itemParent.ActiveFormat : sectionInfo.ActiveFormat; + itemInfo.ActiveFormat = itemInfo.MyContent.MyFormat ?? (sectionInfo == null ? itemParent.ActiveFormat : sectionInfo.ActiveFormat); itemInfo.MyProcedure = procInfo; itemInfo.MyDocVersion = docVersionInfo; if (itemInfo.IsStep) { - ItemInfo ip = itemParent as ItemInfo; - int profileDepth = ProfileTimer.Push(">>>> itemInfo.CombinedTab"); - itemInfo.CombinedTab = (ip == null) ? itemInfo.MyTab.CleanText.Trim() : GetCombinedTab(itemInfo, ip.CombinedTab); + int profileDepth = ProfileTimer.Push(">>>> itemInfo.CombinedTab"); + itemInfo.CombinedTab = (!(itemParent is ItemInfo ip)) ? itemInfo.MyTab.CleanText.Trim() : GetCombinedTab(itemInfo, ip.CombinedTab); ProfileTimer.Pop(profileDepth); } if (itemInfo.MyContent.ContentGridCount > 0) @@ -729,9 +722,8 @@ namespace VEPROMS.CSLA.Library /// public ItemInfo GetNextItem() { - ItemInfo mypar = this.MyParent as ItemInfo; - if (mypar == null) return null; - if (mypar.MyContent.ContentPartCount > 0) + if (!(this.MyParent is ItemInfo mypar)) return null; + if (mypar.MyContent.ContentPartCount > 0) foreach (PartInfo pi in mypar.MyContent.ContentParts) { bool foundMe = false; @@ -757,8 +749,6 @@ namespace VEPROMS.CSLA.Library public static int TranFixCount = 0; public static int TranConvertCount = 0;// B2018-002 - Invalid Transitions - Declare Transition Conversion Count public static int TranCantFixCount = 0; - internal static TransitionInfoList TransitionsToDisconnected; - internal static TransitionInfoList TransitionsToNonEditable; internal static void MyRefreshTransitions(ItemInfo itemInfo, IVEDrillDownReadOnly itemParent, SectionInfo sectionInfo, ProcedureInfo procInfo, DocVersionInfo docVersionInfo, TransitionLookup tranLookup) { @@ -1002,16 +992,6 @@ namespace VEPROMS.CSLA.Library } } - private static bool IsTransitionToNonEditable(TransitionInfo ti) - { - foreach (TransitionInfo til in TransitionsToNonEditable) - { - if (ti.TransitionID == til.TransitionID) - return true; - } - return false; - } - public static void ResetROCounters() { ROCheckCount = 0; @@ -1180,7 +1160,7 @@ namespace VEPROMS.CSLA.Library using (Content content = Content.Get(itemInfo.MyContent.ContentID)) { - content.CheckROLinkTextandUsage(ref BadROLinksCount, ref CheckROLinksCount, ref FixedROLinksCount); + content.CheckROLinkTextandUsage(ref BadROLinksCount, ref CheckROLinksCount); } /*** comment out for now incase we decide to fix bad RO links Content content = Content.Get(itemInfo.MyContent.ContentID); @@ -1291,7 +1271,7 @@ namespace VEPROMS.CSLA.Library public static string GetCombinedTab(ItemInfo itemInfo, string parTab) { - string pTab = parTab == null ? "" : parTab; + string pTab = parTab ?? ""; int profileDepth = ProfileTimer.Push(">>>> itemInfo.MyTab.CleanText.Trim"); string thisTab = itemInfo.MyTab.CleanText.Trim(); ProfileTimer.Pop(profileDepth); @@ -1325,14 +1305,13 @@ namespace VEPROMS.CSLA.Library itemInfo.MyParent = itemParent as ItemInfo; // itemInfo.ActiveSection = (itemInfo as SectionInfo) ?? sectionInfo; itemInfo.ActiveSection = sectionInfo; - itemInfo.ActiveFormat = itemInfo.MyContent.MyFormat != null ? itemInfo.MyContent.MyFormat : sectionInfo == null ? itemParent.ActiveFormat : sectionInfo.ActiveFormat; + itemInfo.ActiveFormat = itemInfo.MyContent.MyFormat ?? (sectionInfo == null ? itemParent.ActiveFormat : sectionInfo.ActiveFormat); itemInfo.MyDocVersion = docVersionInfo; if (itemInfo.IsStep) { - ItemInfo ip = itemParent as ItemInfo; - itemInfo.CombinedTab = (ip == null) ? itemInfo.MyTab.CleanText.Trim() : GetCombinedTab(itemInfo, ip.CombinedTab); - } + itemInfo.CombinedTab = (!(itemParent is ItemInfo ip)) ? itemInfo.MyTab.CleanText.Trim() : GetCombinedTab(itemInfo, ip.CombinedTab); + } if (docVersionInfo.DocVersionAssociationCount == 1) { @@ -1427,8 +1406,7 @@ namespace VEPROMS.CSLA.Library get { if (_PrintLevel != 0) return _PrintLevel; - int _PrintBias = 0; - _PrintLevel = GetStepLevel(); //ref _PrintBias); + _PrintLevel = GetStepLevel(); return _PrintLevel; } set { _PrintLevel = value; } @@ -1479,8 +1457,8 @@ namespace VEPROMS.CSLA.Library public event ItemInfoEvent OrdinalChanged; private void OnOrdinalChange() { - if (OrdinalChanged != null) OrdinalChanged(this); - } + OrdinalChanged?.Invoke(this); + } public static void OnOrdinalChange(int itemID) { ConvertListToDictionary(); @@ -1534,9 +1512,8 @@ namespace VEPROMS.CSLA.Library get { if (IsProcedure) return false; - SectionConfig scfg = ActiveSection.MyConfig as SectionConfig; - if (MyDocStyle.StructureStyle.Style == null || scfg == null) return false; - bool PlacekeepOption = ((ActiveFormat.PlantFormat.FormatData.PurchaseOptions & E_PurchaseOptions.AutoPlacekeeper) == E_PurchaseOptions.AutoPlacekeeper) + if (MyDocStyle.StructureStyle.Style == null || !(ActiveSection.MyConfig is SectionConfig scfg)) return false; + bool PlacekeepOption = ((ActiveFormat.PlantFormat.FormatData.PurchaseOptions & E_PurchaseOptions.AutoPlacekeeper) == E_PurchaseOptions.AutoPlacekeeper) && scfg.Section_Placekeeper.Equals("Y"); //return (PlacekeepOption && IsHigh); return (PlacekeepOption); @@ -1600,13 +1577,12 @@ namespace VEPROMS.CSLA.Library MatchCollection m2s = regexDBSeqPass2.Matches(m1.Groups[4].Value); StringBuilder retval = new StringBuilder(string.Format("\"{0}\"\t\"{1}\"\t\"{2}\"", m1.Groups[1].Value, m1.Groups[2].Value, m1.Groups[3].Value)); string prefix = "S"; - string suffix = ""; - foreach (Match m2 in m2s) + foreach (Match m2 in m2s) { int i = ((int)'0') + int.Parse(m2.Groups[2].Value); char c = (char)i; - suffix = c.ToString(); - switch (m2.Groups[1].Value) + string suffix = c.ToString(); + switch (m2.Groups[1].Value) { case "S": break; @@ -1653,7 +1629,6 @@ namespace VEPROMS.CSLA.Library private static int CalcStepLevel(ItemInfo item) { if (item == null) return 0; - int id = 0; // Determines the substep level. int level = CountLevels(item); @@ -1747,10 +1722,9 @@ namespace VEPROMS.CSLA.Library { get { - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) return false; - // B2018-104: Make the following check consistent with what is in CalcStepLevel (added ImplicitOr) - if (parent.IsExactType("And") || parent.IsExactType("Or") || parent.IsExactType("ImplicitOr")) return true; + if (!(ActiveParent is ItemInfo parent)) return false; + // B2018-104: Make the following check consistent with what is in CalcStepLevel (added ImplicitOr) + if (parent.IsExactType("And") || parent.IsExactType("Or") || parent.IsExactType("ImplicitOr")) return true; return parent.ParentAndOr; } } @@ -1758,10 +1732,9 @@ namespace VEPROMS.CSLA.Library { get { - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) return 0; - // B2018-104: Make the following check consistent with what is in CalcStepLevel (added ImplicitOr) - if (parent.IsExactType("And") || parent.IsExactType("Or") || parent.IsExactType("ImplicitOr")) return 1 + parent.ParentAndOrCount; + if (!(ActiveParent is ItemInfo parent)) return 0; + // B2018-104: Make the following check consistent with what is in CalcStepLevel (added ImplicitOr) + if (parent.IsExactType("And") || parent.IsExactType("Or") || parent.IsExactType("ImplicitOr")) return 1 + parent.ParentAndOrCount; return parent.ParentAndOrCount; } } @@ -1837,12 +1810,9 @@ namespace VEPROMS.CSLA.Library return true; } } - protected void ExtensionRefreshFields(Item tmp) - { - _ActiveParent = null; - } - #region LoadAtOnce2 - public static ItemInfo GetItemAndChildren2(int? itemID) + protected void ExtensionRefreshFields() => _ActiveParent = null; + #region LoadAtOnce2 + public static ItemInfo GetItemAndChildren2(int? itemID) { try { @@ -2436,15 +2406,14 @@ namespace VEPROMS.CSLA.Library if (MyContent.Type / 10000 != 2) _IsHigh = false; else { - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) _IsHigh = false; - // IsHigh was returning true if this item is a caution or note off of a section.. - // from the (parent.MyContent.Type / 1000) == 1. - else if ((parent.MyContent.Type / 10000) != 1) - _IsHigh = false; - else if (IsCaution || IsNote) _IsHigh = false; - else _IsHigh = true; - } + if (!(ActiveParent is ItemInfo parent)) _IsHigh = false; + // IsHigh was returning true if this item is a caution or note off of a section.. + // from the (parent.MyContent.Type / 1000) == 1. + else if ((parent.MyContent.Type / 10000) != 1) + _IsHigh = false; + else if (IsCaution || IsNote) _IsHigh = false; + else _IsHigh = true; + } ProfileTimer.Pop(profileDepth); return (bool)_IsHigh; } @@ -2507,9 +2476,8 @@ namespace VEPROMS.CSLA.Library { if (IsHigh) return false; if (IsRNOPart) return true; - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) return false; - return parent.IsInRNO; + if (!(ActiveParent is ItemInfo parent)) return false; + return parent.IsInRNO; } } public bool IsInSupInfo @@ -2518,9 +2486,8 @@ namespace VEPROMS.CSLA.Library { if (IsHigh) return false; if (IsSupInfoPart) return true; - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) return false; - return parent.IsInSupInfo; + if (!(ActiveParent is ItemInfo parent)) return false; + return parent.IsInSupInfo; } } public bool IsRtfRaw @@ -2578,8 +2545,8 @@ namespace VEPROMS.CSLA.Library // check config value on my section, if null/default use Pmode of active format if (ActiveSection != null) { - SectionInfo si = null; - if (IsSection) si = this as SectionInfo; + SectionInfo si; + if (IsSection) si = this as SectionInfo; else si = ActiveSection as SectionInfo; if (si == null) si = SectionInfo.Get(ActiveSection.ItemID); //ActiveSection as SectionInfo; @@ -2677,9 +2644,8 @@ namespace VEPROMS.CSLA.Library public bool HasAncestor(ItemInfo ancestor) { if (ancestor == null) return false; - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) return false; - if (ancestor.ItemID == parent.ItemID) return true; + if (!(ActiveParent is ItemInfo parent)) return false; + if (ancestor.ItemID == parent.ItemID) return true; return parent.HasAncestor(ancestor); } #endregion @@ -2787,9 +2753,8 @@ namespace VEPROMS.CSLA.Library { if (IsHigh) return false; if (IsStepPart) return true; - ItemInfo parent = ActiveParent as ItemInfo; - if (parent == null) return false; - return parent.IsInSubStep; + if (!(ActiveParent is ItemInfo parent)) return false; + return parent.IsInSubStep; } } public bool IsInFirstLevelSubStep @@ -2832,11 +2797,11 @@ namespace VEPROMS.CSLA.Library ItemInfo parent = (ItemInfo)ActiveParent; if (!parent.IsProcedure) return false; ProcedureConfig pc = (ProcedureConfig)parent.MyConfig; - int sectstartid = -1; - string ss = pc == null ? null : pc.SectionStart; - if (ss != null && ss != "") sectstartid = System.Convert.ToInt32(ss); - else return false; - if (ItemID == sectstartid) return true; + string ss = pc?.SectionStart; + int sectstartid; + if (ss != null && ss != "") sectstartid = System.Convert.ToInt32(ss); + else return false; + if (ItemID == sectstartid) return true; SectionInfo si = SectionInfo.Get(sectstartid); if (si == null) return false; if (si.MyProcedure.ItemID == MyProcedure.ItemID) return false; @@ -2860,9 +2825,8 @@ namespace VEPROMS.CSLA.Library get { if (!IsSection) return false; - ItemInfo par = ActiveParent as ItemInfo; - if (par == null || !par.IsSection) return false; - return true; + if (!(ActiveParent is ItemInfo par) || !par.IsSection) return false; + return true; } } public bool IsSubsectionNumber @@ -2872,18 +2836,16 @@ namespace VEPROMS.CSLA.Library get { if (!IsSection) return false; - ItemInfo par = ActiveParent as ItemInfo; - if (par == null || !par.IsSection) return false; - string parNumber = par.DisplayNumber; + if (!(ActiveParent is ItemInfo par) || !par.IsSection) return false; + string parNumber = par.DisplayNumber; string myNumber = DisplayNumber; if (parNumber == null || myNumber == null) return false; - ItemInfo par2 = par.ActiveParent as ItemInfo; - if (par2 != null && par2.IsSection) - { - // check for 6.1 (parent) and 6.1.1. - if (DisplayNumber.StartsWith((ActiveParent as ItemInfo).DisplayNumber.Trim())) return true; - } - if (!parNumber.Trim().EndsWith(".0")) return false; + if (par.ActiveParent is ItemInfo par2 && par2.IsSection) + { + // check for 6.1 (parent) and 6.1.1. + if (DisplayNumber.StartsWith((ActiveParent as ItemInfo).DisplayNumber.Trim())) return true; + } + if (!parNumber.Trim().EndsWith(".0")) return false; return (myNumber.Trim().StartsWith(parNumber.Trim().Substring(0, parNumber.Length - 1))); } } @@ -3308,43 +3270,45 @@ namespace VEPROMS.CSLA.Library { // B2022-081 needed to add clock symbol so that it properly translate over to enhanced document if (_SpecialCharacters==null){ - _SpecialCharacters = new Dictionary(); - _SpecialCharacters.Add(@"\u916?", "{Delta}"); - _SpecialCharacters.Add(@"\line", "{Hard Return1}"); - _SpecialCharacters.Add("\r\n", "{Hard Return2}"); - _SpecialCharacters.Add(@"\'b0", "{Degree1}"); - _SpecialCharacters.Add(@"\'B0", "{Degree2}"); - _SpecialCharacters.Add(@"\u9586?","{backslash}"); - _SpecialCharacters.Add(@"\u8805?","{greater than or equal}"); - _SpecialCharacters.Add(@"\u8804?","{less than or equal}"); - _SpecialCharacters.Add(@"\'b1","{plus minus}"); - _SpecialCharacters.Add(@"\u931?","{sigma}"); - _SpecialCharacters.Add(@"\u947?","{gamma}"); - _SpecialCharacters.Add(@"\'bd","{half}"); - _SpecialCharacters.Add(@"\u9604?","{accum}"); - _SpecialCharacters.Add(@"\u9679?","{bullet}"); - _SpecialCharacters.Add(@"\u8776?","{approx eq}"); - _SpecialCharacters.Add(@"\u8773?","{similar eq}"); - _SpecialCharacters.Add(@"\'f7","{division}"); - _SpecialCharacters.Add(@"\u8730?","{square root}"); - _SpecialCharacters.Add(@"\u961?","{rho}"); - _SpecialCharacters.Add(@"\u960?","{pi}"); - _SpecialCharacters.Add(@"\u956?","{micro}"); - _SpecialCharacters.Add(@"\u948?","{lower case delta}"); - _SpecialCharacters.Add(@"\u963?","{lower case sigma}"); - _SpecialCharacters.Add(@"\'bc","{quarter}"); - _SpecialCharacters.Add(@"\'d8","{dist zero}"); - _SpecialCharacters.Add(@"\u274?","{energy}"); - _SpecialCharacters.Add(@"\'ec","{grave}"); - _SpecialCharacters.Add(@"\u9474?","{bar}"); - _SpecialCharacters.Add(@"\u949?","{epsilon}"); - _SpecialCharacters.Add(@"\u952?","{theta}"); - _SpecialCharacters.Add(@"\u8857?","{dot in oval}"); - _SpecialCharacters.Add(@"\u964?","{tau}"); - _SpecialCharacters.Add(@"\u9830?","{diamond}"); - _SpecialCharacters.Add(@"\u8593?","{Up Arrow}"); - _SpecialCharacters.Add(@"\u8595?","{Down Arrow}"); - _SpecialCharacters.Add(@"\u9774?","{Clock}"); + _SpecialCharacters = new Dictionary + { + { @"\u916?", "{Delta}" }, + { @"\line", "{Hard Return1}" }, + { "\r\n", "{Hard Return2}" }, + { @"\'b0", "{Degree1}" }, + { @"\'B0", "{Degree2}" }, + { @"\u9586?", "{backslash}" }, + { @"\u8805?", "{greater than or equal}" }, + { @"\u8804?", "{less than or equal}" }, + { @"\'b1", "{plus minus}" }, + { @"\u931?", "{sigma}" }, + { @"\u947?", "{gamma}" }, + { @"\'bd", "{half}" }, + { @"\u9604?", "{accum}" }, + { @"\u9679?", "{bullet}" }, + { @"\u8776?", "{approx eq}" }, + { @"\u8773?", "{similar eq}" }, + { @"\'f7", "{division}" }, + { @"\u8730?", "{square root}" }, + { @"\u961?", "{rho}" }, + { @"\u960?", "{pi}" }, + { @"\u956?", "{micro}" }, + { @"\u948?", "{lower case delta}" }, + { @"\u963?", "{lower case sigma}" }, + { @"\'bc", "{quarter}" }, + { @"\'d8", "{dist zero}" }, + { @"\u274?", "{energy}" }, + { @"\'ec", "{grave}" }, + { @"\u9474?", "{bar}" }, + { @"\u949?", "{epsilon}" }, + { @"\u952?", "{theta}" }, + { @"\u8857?", "{dot in oval}" }, + { @"\u964?", "{tau}" }, + { @"\u9830?", "{diamond}" }, + { @"\u8593?", "{Up Arrow}" }, + { @"\u8595?", "{Down Arrow}" }, + { @"\u9774?", "{Clock}" } + }; } return _SpecialCharacters; } @@ -3402,9 +3366,9 @@ namespace VEPROMS.CSLA.Library { // B2021-066: show Procedure level applicability in tree view if (ActiveFormat.PlantFormat.FormatData.ProcData.ProcAppl) - str = MyDocVersion.UnitSpecific(MyContent.Number, 1, this); + str = MyDocVersion.UnitSpecific(this); else - str = MyDocVersion.UnitSpecific(MyContent.Number, 1); + str = MyDocVersion.UnitSpecific(MyContent.Number); } else @@ -3628,9 +3592,9 @@ namespace VEPROMS.CSLA.Library VE_Font hdrFont = format.PlantFormat.FormatData.SectData.SectionHeader.Font; E_Style es = (E_Style)hdrFont.Style; if (format.PlantFormat.FormatData.SectData.SectionHeader.OnlyUnderlineTopSect) - es = es & E_Style.Bold; // only keep the underline (turn off the bold) + es &= E_Style.Bold; // only keep the underline (turn off the bold) if (format.PlantFormat.FormatData.SectData.SectionHeader.OnlyBoldTopSect) - es = es & E_Style.Underline; // only keep the bold (turn off underline) + es &= E_Style.Underline; // only keep the bold (turn off underline) font = new VE_Font(hdrFont.Family, (int)hdrFont.Size, es, (float)hdrFont.CPI); } else @@ -3807,7 +3771,6 @@ namespace VEPROMS.CSLA.Library { get { - string number = (MyContent.Type >= 20000 ? Ordinal.ToString() + "." : ((MyContent.Number ?? "") == "" ? MyContent.Text : MyContent.Number)); ItemInfo parent = this; while (parent.MyPrevious != null) parent = parent.MyPrevious; if (parent.ItemPartCount <= 0 || parent.ItemParts.Count == 0) @@ -3855,18 +3818,18 @@ namespace VEPROMS.CSLA.Library } internal ItemInfoList Lookup(int fromType) { - ItemInfoList itemInfoList = null; - if (MyContent.ContentPartCount != 0) - foreach (PartInfo partInfo in MyContent.ContentParts) - if (partInfo.FromType == fromType) - { - if (LoadAllAtOnce) - itemInfoList = partInfo._MyItems;// = ItemInfoList.GetList(partInfo.ItemID, partInfo.FromType); - else - itemInfoList = partInfo._MyItems = ItemInfoList.GetList(partInfo.ItemID, partInfo.FromType); - return itemInfoList; - } - return null; + if (MyContent.ContentPartCount != 0) + foreach (PartInfo partInfo in MyContent.ContentParts) + if (partInfo.FromType == fromType) + { + ItemInfoList itemInfoList; + if (LoadAllAtOnce) + itemInfoList = partInfo._MyItems;// = ItemInfoList.GetList(partInfo.ItemID, partInfo.FromType); + else + itemInfoList = partInfo._MyItems = ItemInfoList.GetList(partInfo.ItemID, partInfo.FromType); + return itemInfoList; + } + return null; } public static void ResetParts(int itemID) { @@ -4065,10 +4028,9 @@ namespace VEPROMS.CSLA.Library get { bool chg = HasChanges; - StepConfig sc = this.MyConfig as StepConfig; - if (sc == null) return false; - // if there is no override & return whether there was a change to the text. - if (chg && ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds && + if (!(this.MyConfig is StepConfig sc)) return false; + // if there is no override & return whether there was a change to the text. + if (chg && ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds && (sc.Step_ChangeID ?? "") == "") return false; // No Change ID - No Change Bar if ((sc.Step_SpellCheckerChangedText ?? "") == "NoChangeBar") @@ -4098,10 +4060,9 @@ namespace VEPROMS.CSLA.Library get { if (this.IsAccPages || this.IsProcedure || this.IsSection) return false; - StepConfig sc = this.MyConfig as StepConfig; - if (sc == null) return false; - // go back to source & see what date it has: - if (sc.MyEnhancedDocuments != null && sc.MyEnhancedDocuments.Count == 1 && sc.MyEnhancedDocuments[0].Type == 0) + if (!(this.MyConfig is StepConfig sc)) return false; + // go back to source & see what date it has: + if (sc.MyEnhancedDocuments != null && sc.MyEnhancedDocuments.Count == 1 && sc.MyEnhancedDocuments[0].Type == 0) { ItemInfo ii = ItemInfo.Get(sc.MyEnhancedDocuments[0].ItemID); if (ii == null) return false; // when deleting a source step, this was causing a crash (null ii) @@ -4226,8 +4187,8 @@ namespace VEPROMS.CSLA.Library if (IsHigh) _MyHLS = this; else { - if (MyActiveParent is ItemInfo) - _MyHLS = ((ItemInfo)MyActiveParent).MyHLS; + if (MyActiveParent is ItemInfo info) + _MyHLS = info.MyHLS; } } return _MyHLS; @@ -4322,12 +4283,11 @@ namespace VEPROMS.CSLA.Library _ActiveSection = this; else { - ItemInfo parent = ActiveParent as ItemInfo; - if (parent != null) - _ActiveSection = parent.ActiveSection; - else - _ActiveSection = this; - } + if (ActiveParent is ItemInfo parent) + _ActiveSection = parent.ActiveSection; + else + _ActiveSection = this; + } // B2018-018 Approval bug fix. Active section was in cache as an ItemInfo instead of a SectionInfo if (_ActiveSection != null && !(_ActiveSection is SectionInfo)) _ActiveSection = SectionInfo.Get(_ActiveSection.ItemID); @@ -4370,7 +4330,7 @@ namespace VEPROMS.CSLA.Library get { if (_ActiveFormat == null || !PrintAllAtOnce) // jsj added check for NULL ActiveParent - _ActiveFormat = (LocalFormat != null ? LocalFormat : (ActiveParent != null) ? ActiveParent.ActiveFormat : null); + _ActiveFormat = (LocalFormat ?? (ActiveParent?.ActiveFormat)); //Console.WriteLine("Active {0}", (_ActiveFormat == null) ? "_ActiveFormat is null" : _ActiveFormat.Name); return _ActiveFormat; } @@ -4634,14 +4594,8 @@ namespace VEPROMS.CSLA.Library } _TagsSetup = true; } - public bool SupplementalInformation - { - get - { - return MyDocStyle == null ? false : MyDocStyle.SupplementalInformation; - } - } - protected void SetTabText() + public bool SupplementalInformation => MyDocStyle != null && MyDocStyle.SupplementalInformation; + protected void SetTabText() { if (IsSection) // B2016-160 Support transitions to sections { @@ -4658,7 +4612,6 @@ namespace VEPROMS.CSLA.Library return; } string cltext = null; - int stepType = (int)(MyContent.Type % 10000); string tbformat; if ((ActiveFormat.MyStepSectionLayoutData.UseRNOParentIdent ?? "") != "" && bool.Parse(ActiveFormat.MyStepSectionLayoutData.UseRNOParentIdent)) tbformat = IsInRNO ? FormatStepData.TabData.RNOIdentPrint == "" ? this.MyParent.FormatStepData.TabData.RNOIdentPrint : FormatStepData.TabData.RNOIdentPrint : FormatStepData.TabData.IdentPrint; @@ -4839,22 +4792,20 @@ namespace VEPROMS.CSLA.Library if (ActiveFormat.MyStepSectionLayoutData.AddContActTagToHighLevelRNOWhenIncludedOnCAS && IsInRNO && !MyParent.IsInRNO && FormatStepData.TabData.CASPrintMacro != null) { - // B2026-009 needed to make sure parent wasn't a continuous action step type - // the ExcludeFromContActSum is set to False for continuous action - // step types and True for all others - StepConfig psc = MyParent.MyConfig as StepConfig; - if (MyParent.FormatStepData.ExcludeFromContActSum && psc != null && psc.Step_CAS != "True") - { - StepConfig sc = MyConfig as StepConfig; - if (sc != null && sc.Step_CAS == "True") - { - if (FormatStepData.TabData.CASPrintMacro != null) - _MyTab.Text = FormatStepData.TabData.CASPrintMacro + _MyTab.Text; - if (FormatStepData.TabData.CASEditTag != null) - _MyTab.CleanText = FormatStepData.TabData.CASEditTag + _MyTab.CleanText; - } - } - } + // B2026-009 needed to make sure parent wasn't a continuous action step type + // the ExcludeFromContActSum is set to False for continuous action + // step types and True for all others + if (MyParent.FormatStepData.ExcludeFromContActSum && MyParent.MyConfig is StepConfig psc && psc.Step_CAS != "True") + { + if (MyConfig is StepConfig sc && sc.Step_CAS == "True") + { + if (FormatStepData.TabData.CASPrintMacro != null) + _MyTab.Text = FormatStepData.TabData.CASPrintMacro + _MyTab.Text; + if (FormatStepData.TabData.CASEditTag != null) + _MyTab.CleanText = FormatStepData.TabData.CASEditTag + _MyTab.CleanText; + } + } + } _MyTab.RNOTabWidthAdjust = ((ItemInfo)ActiveParent).FormatStepData.TabData.RNOAdjustTabSize ?? 0; if (((ItemInfo)ActiveParent).MyTab.Offset != 0) _MyTab.Offset = ((ItemInfo)ActiveParent).MyTab.Offset; if (((ItemInfo)ActiveParent).FormatStepData.TabData.RNOExcludeMacros) @@ -4921,7 +4872,7 @@ namespace VEPROMS.CSLA.Library lv++; ii = ii.MyParent; } - lv = lv % 2; + lv %= 2; tbformat = (lv == 0) ? "{numeric}." : "{alpha}."; } } @@ -4991,48 +4942,52 @@ namespace VEPROMS.CSLA.Library // If token includes 'Wpar', the parent tab prefix's the tab. if (localPrintLevel > 0 && tbformat.Contains("Wpar}")) // C2025-036 reduce un-needed processing { - string parentTab = null; - ItemInfo myparent = ActiveParent as ItemInfo; - if (myparent != null && myparent.IsParagraph) - { - myparent = myparent.ActiveParent as ItemInfo; - if (myparent.MyTab.CleanText.Trim() == "") - { - if ((myparent.ActiveParent as ItemInfo).MyTab.CleanText.Trim() != "") - myparent = myparent.ActiveParent as ItemInfo; - } - } - else if (myparent.IsSection || myparent.IsHigh || myparent.IsSequential || (myparent.IsRNOPart && myparent.FormatStepData.NumberHighLevel && tbformat.ToUpper().Contains("WPAR"))) - { - parentTab = (dontTrimParentTabBeforeAppending) ? myparent.MyTab.CleanText : myparent.MyTab.CleanText.Trim(); // B2019-011 for Barakah Alarm format adde the don't trim flag - if ((((MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_AddDotZeroStdHLS) == E_DocStructStyle.DSS_AddDotZeroStdHLS) && myparent.MyContent.Type == 20002) || - (myparent.IsStepPart && myparent.FormatStepData.AppendDotZero)) // F2018-022 Added step type flag to append a ".0" to the end of the high level step - put in for Westinghouse single column format (wst1), B2018-119 only do this for steps - parentTab = parentTab.Replace(".0", ""); // this was added in, remove for substeps. - tbformat = parentTab + (parentTab.EndsWith(".") ? "" : parentTab == "" ? "" : ".") + tbformat.TrimStart(); - HasParentTab = true; // F2020-023: tab includes parent tab - } - else if (IsSequential && ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SkipNonSeqTabWithPar) - { - // this was added for Wolf Creek WCN1: if this has a 'wpar' flag, then walk up until finding - // a sequential or high and use that tab (ignore non-sequential steps when walking up parents). - // Note that the format flag 'SkipNonSeqTabWithPar' was added to prevent this code being run for Westinghouse and Farley. + ItemInfo myparent = ActiveParent as ItemInfo; + string parentTab; + if (myparent != null && myparent.IsParagraph) + { + myparent = myparent.ActiveParent as ItemInfo; + if (myparent.MyTab.CleanText.Trim() == "") + { + if ((myparent.ActiveParent as ItemInfo).MyTab.CleanText.Trim() != "") + { +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Keeping for Debugging / side effect + myparent = myparent.ActiveParent as ItemInfo; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + } + } + } + else if (myparent.IsSection || myparent.IsHigh || myparent.IsSequential || (myparent.IsRNOPart && myparent.FormatStepData.NumberHighLevel && tbformat.ToUpper().Contains("WPAR"))) + { + parentTab = (dontTrimParentTabBeforeAppending) ? myparent.MyTab.CleanText : myparent.MyTab.CleanText.Trim(); // B2019-011 for Barakah Alarm format adde the don't trim flag + if ((((MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_AddDotZeroStdHLS) == E_DocStructStyle.DSS_AddDotZeroStdHLS) && myparent.MyContent.Type == 20002) || + (myparent.IsStepPart && myparent.FormatStepData.AppendDotZero)) // F2018-022 Added step type flag to append a ".0" to the end of the high level step - put in for Westinghouse single column format (wst1), B2018-119 only do this for steps + parentTab = parentTab.Replace(".0", ""); // this was added in, remove for substeps. + tbformat = parentTab + (parentTab.EndsWith(".") ? "" : parentTab == "" ? "" : ".") + tbformat.TrimStart(); + HasParentTab = true; // F2020-023: tab includes parent tab + } + else if (IsSequential && ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SkipNonSeqTabWithPar) + { + // this was added for Wolf Creek WCN1: if this has a 'wpar' flag, then walk up until finding + // a sequential or high and use that tab (ignore non-sequential steps when walking up parents). + // Note that the format flag 'SkipNonSeqTabWithPar' was added to prevent this code being run for Westinghouse and Farley. - // the following prevents the concatenation of parent tabs onto this once the indenting is - // past the number of seqtabs. - if (localPrintLevel < seqtabs.MaxIndex || (PrintLevel < seqtabs.MaxIndex && seqtabs[PrintLevel].TabToken.ToUpper().Contains("WPAR"))) - { - ItemInfo mpar = myparent; - while (mpar != null && !mpar.IsSection && !mpar.IsHigh && !mpar.IsSequential) mpar = (mpar.MyParent as ItemInfo); - if (mpar != null && !mpar.IsSection) - { - parentTab = mpar.MyTab.CleanText.Trim(); - tbformat = parentTab + (parentTab.EndsWith(".") ? "" : ".") + tbformat.TrimStart(); - HasParentTab = true; // F2020-023: tab includes parent tab - //if (_MyLog.IsInfoEnabled) _MyLog.InfoFormat("==>PARTAB: [{0}]", ShortPath + ", " + ItemID.ToString()); - } - } - } - } + // the following prevents the concatenation of parent tabs onto this once the indenting is + // past the number of seqtabs. + if (localPrintLevel < seqtabs.MaxIndex || (PrintLevel < seqtabs.MaxIndex && seqtabs[PrintLevel].TabToken.ToUpper().Contains("WPAR"))) + { + ItemInfo mpar = myparent; + while (mpar != null && !mpar.IsSection && !mpar.IsHigh && !mpar.IsSequential) mpar = (mpar.MyParent as ItemInfo); + if (mpar != null && !mpar.IsSection) + { + parentTab = mpar.MyTab.CleanText.Trim(); + tbformat = parentTab + (parentTab.EndsWith(".") ? "" : ".") + tbformat.TrimStart(); + HasParentTab = true; // F2020-023: tab includes parent tab + //if (_MyLog.IsInfoEnabled) _MyLog.InfoFormat("==>PARTAB: [{0}]", ShortPath + ", " + ItemID.ToString()); + } + } + } + } if (tbformat.IndexOf("#2#") > -1 || tbformat.IndexOf("#1#") > -1) { @@ -5080,8 +5035,8 @@ namespace VEPROMS.CSLA.Library { ordinal = int.Parse("0" + LinkedTab ?? "0"); } - catch (Exception ex) - { + catch (Exception) + { // use LinkedTab and don't do the AlphabeticalNumbering below. LinkedTab had alpha chars useLinked = true; } @@ -5143,8 +5098,8 @@ namespace VEPROMS.CSLA.Library // otherwise add a space. if (ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.WolfCreekBackgroundFormat && IsBackgroundStep()) { - string stpTab = null; - if (useLinked) + string stpTab; + if (useLinked) stpTab = (!tbformat.Contains(".") ? " " : "") + ((ordinal == 0) ? "NA" : LinkedTab); else stpTab = (!tbformat.Contains(".") ? " " : "") + ((ordinal == 0) ? "NA" : ordinal.ToString()); @@ -5209,7 +5164,7 @@ namespace VEPROMS.CSLA.Library { int macrolen = eidx - macroindx + 1; cltext = cltext == null ? tbformat.Remove(macroindx, macrolen) : cltext.Remove(macroindx, macrolen); - cltext = cltext + " "; + cltext += " "; cltext = cltext.Substring(0, macroindx) + FormatStepData.TabData.MacroEditTag + cltext.Substring(macroindx); } } @@ -5221,7 +5176,7 @@ namespace VEPROMS.CSLA.Library else { cltext = cltext == null ? tbformat.Remove(macroindx, 5) : cltext.Remove(macroindx, 5); - cltext = cltext + " "; + cltext += " "; } } //CSM F2024 - 080: For South Texas - if format contains initial line and it is not disabled, show an initial line @@ -5240,13 +5195,13 @@ namespace VEPROMS.CSLA.Library if (macroindx > -1) //i found it { cltext = cltext == null ? tbformat.Remove(macroindx, 11) : cltext.Remove(macroindx, 11); - cltext = cltext + " "; + cltext += " "; } macroindx = tbformat.IndexOf("{!diamond}"); if (macroindx > -1) //i found it { cltext = cltext == null ? tbformat.Remove(macroindx, 10) : cltext.Remove(macroindx, 10); - cltext = cltext + " "; + cltext += " "; } // "{Null}" was introduced so that inheritance in format files could differentiate between an // empty string, and null. And also, so that if a tab was null but it's parent had text in the @@ -5255,10 +5210,8 @@ namespace VEPROMS.CSLA.Library { // check if there is font information for the separator, use it. If not use the font information // that is associated with the tab. - VE_Font hdrFont = ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.Separator == null ? null : - ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.Separator.Font; - if (hdrFont == null) hdrFont = FormatStepData.TabData.Font; - if (_MyHeader == null) _MyHeader = new MetaTag(hdrFont); + VE_Font hdrFont = (ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.Separator?.Font) ?? FormatStepData.TabData.Font; + if (_MyHeader == null) _MyHeader = new MetaTag(hdrFont); else _MyHeader.MyFont = hdrFont; _MyHeader.Text = FormatStepData.Sep; @@ -5305,8 +5258,7 @@ namespace VEPROMS.CSLA.Library // if this has an alternate tab, use it. These have been used in background documents. if (!IsSection && FormatStepData.TabData.IdentAltPrint != null && FormatStepData.TabData.IdentAltPrint != "") { - string newtab = null; - string fmtAltPrintTab = FormatStepData.TabData.IdentAltPrint; + string fmtAltPrintTab = FormatStepData.TabData.IdentAltPrint; int idxClock = -1; int idxEndClock = -1; if (fmtAltPrintTab.Contains("{!Clock}")) @@ -5321,8 +5273,8 @@ namespace VEPROMS.CSLA.Library if (indxnewtab >= 0) { _MyTab.BasicTab = isAlpha ? alpha : ordinal.ToString(); - newtab = fmtAltPrintTab.Substring(indxnewtab + 1); - if (newtab.Contains("{numeric}") || newtab.Contains("{LNK Step Num}")) + string newtab = fmtAltPrintTab.Substring(indxnewtab + 1); + if (newtab.Contains("{numeric}") || newtab.Contains("{LNK Step Num}")) { newtab = tbformat; if (idxClock > -1) @@ -5362,7 +5314,7 @@ namespace VEPROMS.CSLA.Library cltext = cltext.Replace("{LJ}", "").TrimStart(); } _MyTab.Text = tbformat; - _MyTab.CleanText = cltext != null ? cltext : tbformat; + _MyTab.CleanText = cltext ?? tbformat; } private int SectionLevel() { @@ -5558,8 +5510,8 @@ namespace VEPROMS.CSLA.Library int numidx = ActiveSection.DisplayNumber.IndexOf(" "); string attNum = (numidx > -1 && (ActiveSection.DisplayNumber.Length > numidx + 1) && !FormatStepData.TabData.UseEntireSectionNum) ? ActiveSection.DisplayNumber.Substring(numidx + 1) : ActiveSection.DisplayNumber; Match m = Regex.Match(attNum, @"[a-zA-Z]"); // for alpha, use non-touched displaynumber - int indx = -1; - if (m.Success) + int indx; + if (m.Success) { indx = attNum.IndexOf("."); if (indx < 0) return attNum; @@ -5601,7 +5553,7 @@ namespace VEPROMS.CSLA.Library if (subsection >= 1) { string tmptab = ActiveSection.MyTab.CleanText.TrimEnd(); - if (tmptab.LastIndexOf(".") != tmptab.Length - 1) tmptab = tmptab + "."; + if (tmptab.LastIndexOf(".") != tmptab.Length - 1) tmptab += "."; return tmptab; } // If the tbformat is "{Section Prefix}{numeric}" and section prefix ends in an integer, add a '.' @@ -5613,7 +5565,7 @@ namespace VEPROMS.CSLA.Library string l = tmptab.Substring(tmptab.Length - 1); if (char.IsLetterOrDigit(l[0])) { - if (tmptab.LastIndexOf(".") != tmptab.Length - 1) tmptab = tmptab + "."; + if (tmptab.LastIndexOf(".") != tmptab.Length - 1) tmptab += "."; return tmptab; } } @@ -5751,7 +5703,7 @@ namespace VEPROMS.CSLA.Library (MyPrevious != null && MyPrevious.MyContent.Type == MyContent.Type) || (NextItem != null && nextItem.MyContent.Type == MyContent.Type)) { - tbformat = tbformat + ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; + tbformat += ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; TabToIdentBAdjustFont(); } } @@ -5765,7 +5717,7 @@ namespace VEPROMS.CSLA.Library (FormatStepData.TabData.UsePreviousStyle && !nextStepData.TabData.UsePreviousStyle && tbformat == nextTbFormat) || ((prevTbFormat != tbformat && (nextItem.MyContent.Type == MyContent.Type))))) { - tbformat = tbformat + ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; + tbformat += ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; if (TabToIdentBAdjustFont()) _MyTab.RemovedStyleUnderline = true; } @@ -5776,7 +5728,7 @@ namespace VEPROMS.CSLA.Library (FormatStepData.TabData.UsePreviousStyle && !nextStepData.TabData.UsePreviousStyle && tbformat == nextTbFormat) || ((prevTbFormat != tbformat && (nextItem.MyContent.Type == (int)(MyContent.Type % 10000)))))) { - tbformat = tbformat + ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; + tbformat += ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; //string bstr = ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.IdentB; //int bstrlen = bstr.Length; //string tstr = tbformat.Substring(tbformat.Length - bstrlen); @@ -5983,17 +5935,16 @@ namespace VEPROMS.CSLA.Library { if (!_ParentNoteOrCautionLoaded) { - ItemInfo parent = ActiveParent as ItemInfo; - if (parent != null) - { - if (parent.IsCautionPart || parent.IsNotePart) - _ParentNoteOrCaution = parent; - else if (!parent.IsHigh) - { - _ParentNoteOrCaution = parent.ParentNoteOrCaution; - } - } - _ParentNoteOrCautionLoaded = true; + if (ActiveParent is ItemInfo parent) + { + if (parent.IsCautionPart || parent.IsNotePart) + _ParentNoteOrCaution = parent; + else if (!parent.IsHigh) + { + _ParentNoteOrCaution = parent.ParentNoteOrCaution; + } + } + _ParentNoteOrCautionLoaded = true; } return _ParentNoteOrCaution; } @@ -6109,17 +6060,16 @@ namespace VEPROMS.CSLA.Library { if (_TemplateColumnMode == null) { - ItemInfo pi = ActiveParent as ItemInfo; - if (pi != null) - { - if (!pi.IsStep) // only steps are in template - _TemplateColumnMode = -1; - else if (pi.FormatStepData.UseOldTemplate) - _TemplateColumnMode = pi.TemplateChildColumnMode; - else - _TemplateColumnMode = pi.TemplateColumnMode; // go up parents until find of columnmode or section - } - } + if (ActiveParent is ItemInfo pi) + { + if (!pi.IsStep) // only steps are in template + _TemplateColumnMode = -1; + else if (pi.FormatStepData.UseOldTemplate) + _TemplateColumnMode = pi.TemplateChildColumnMode; + else + _TemplateColumnMode = pi.TemplateColumnMode; // go up parents until find of columnmode or section + } + } return _TemplateColumnMode ?? -1; } } @@ -6218,15 +6168,14 @@ namespace VEPROMS.CSLA.Library if (pd.CheckOffData == null || pd.CheckOffData.CheckOffHeaderList == null || pd.CheckOffData.CheckOffHeaderList.MaxIndex <= 1) _SectionCheckOffHeader = string.Empty; else { - SectionConfig sc = ActiveSection.MyConfig as SectionConfig; - if (sc == null) _SectionCheckOffHeader = string.Empty; - else if (sc.Section_CheckoffHeaderSelection <= 0) _SectionCheckOffHeader = string.Empty; - else - { - _SectionCheckOffHeader = pd.CheckOffData.CheckOffHeaderList[sc.Section_CheckoffHeaderSelection].CheckOffHeading; - if (_SectionCheckOffHeader.Contains("{NO HEADING}")) _SectionCheckOffHeader = string.Empty; - } - } + if (!(ActiveSection.MyConfig is SectionConfig sc)) _SectionCheckOffHeader = string.Empty; + else if (sc.Section_CheckoffHeaderSelection <= 0) _SectionCheckOffHeader = string.Empty; + else + { + _SectionCheckOffHeader = pd.CheckOffData.CheckOffHeaderList[sc.Section_CheckoffHeaderSelection].CheckOffHeading; + if (_SectionCheckOffHeader.Contains("{NO HEADING}")) _SectionCheckOffHeader = string.Empty; + } + } } return _SectionCheckOffHeader; } @@ -6239,22 +6188,20 @@ namespace VEPROMS.CSLA.Library int maxindx = pd.CheckOffData.CheckOffList.MaxIndexNoInherit; if (pd.CheckOffData == null || pd.CheckOffData.CheckOffList == null || maxindx <= 0) return false; if (pd.CheckOffData.CheckOffHeaderList == null || pd.CheckOffData.CheckOffHeaderList.MaxIndex <= 1) return true; - //if (pd.CheckOffData == null || pd.CheckOffData.CheckOffHeaderList == null || pd.CheckOffData.CheckOffHeaderList.Count <= 1) return false; + //if (pd.CheckOffData == null || pd.CheckOffData.CheckOffHeaderList == null || pd.CheckOffData.CheckOffHeaderList.Count <= 1) return false; - // To find whether the step has a checkoff, first check that the section - // has a check off header. If it doesn't, just return -1. - // if config item is set for checkoffindex, use it. If it == 0, then use - // the section default. - SectionConfig sc = ActiveSection.MyConfig as SectionConfig; - if (sc == null) return false; - if (sc.Section_CheckoffHeaderSelection < 0) return false; + // To find whether the step has a checkoff, first check that the section + // has a check off header. If it doesn't, just return -1. + // if config item is set for checkoffindex, use it. If it == 0, then use + // the section default. + if (!(ActiveSection.MyConfig is SectionConfig sc)) return false; + if (sc.Section_CheckoffHeaderSelection < 0) return false; return true; } public int CheckOffIndex() { - StepConfig stc = MyConfig as StepConfig; - if (stc == null) return 0; //section default. - if (stc != null && stc.Step_CheckOffIndex == 1) return -1; // index of 1, always means 'No Checkoff' + if (!(MyConfig is StepConfig stc)) return 0; //section default. + if (stc != null && stc.Step_CheckOffIndex == 1) return -1; // index of 1, always means 'No Checkoff' return stc.Step_CheckOffIndex; } private int SectionConfigCheckOffIndex @@ -6298,9 +6245,8 @@ namespace VEPROMS.CSLA.Library { get { - StepConfig stc = MyConfig as StepConfig; - return (stc != null && stc.Step_CheckOffIndex == 0); - } + return (MyConfig is StepConfig stc && stc.Step_CheckOffIndex == 0); + } } private CheckOff SectionDefaultEnabledCheckOff @@ -6437,7 +6383,7 @@ namespace VEPROMS.CSLA.Library set { _RNOTabWidthAdjust = value; } } public int AsteriskOffset; - private static Regex _ReplaceSymbols = new Regex("^[^0-9A-Za-z]*"); // trim anything that isn't an ascii alpha/numeric from the beginning + private static readonly Regex _ReplaceSymbols = new Regex("^[^0-9A-Za-z]*"); // trim anything that isn't an ascii alpha/numeric from the beginning public string CleanTextNoSymbols { get @@ -7412,7 +7358,6 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - string FoundROs = ""; while (dr.Read()) { ItemInfo itemInfo = null; @@ -7594,16 +7539,16 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ItemListTransitionSearchCriteria { - private string _DocVersionList; - public string DocVersionList { get { return _DocVersionList; } } - private int _TranType; - public int TranType { get { return _TranType; } } - private string _TranCategory; - public string TranCategory { get { return _TranCategory; } } - // added stepTypeList parameter to allow a transition search is selected step elements (B2015-055) - private string _StepTypeList; - public string StepTypeList { get { return _StepTypeList; } } - public ItemListTransitionSearchCriteria(string docVersionList, int tranType, string tranCategory, string stepTypeList) + private readonly string _DocVersionList; + public string DocVersionList => _DocVersionList; + private readonly int _TranType; + public int TranType => _TranType; + private readonly string _TranCategory; + public string TranCategory => _TranCategory; + // added stepTypeList parameter to allow a transition search is selected step elements (B2015-055) + private readonly string _StepTypeList; + public string StepTypeList => _StepTypeList; + public ItemListTransitionSearchCriteria(string docVersionList, int tranType, string tranCategory, string stepTypeList) { _DocVersionList = docVersionList; _TranType = tranType; @@ -7735,7 +7680,6 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - string FoundROs = ""; while (dr.Read()) { ItemInfo itemInfo = null; @@ -7959,30 +7903,25 @@ namespace VEPROMS.CSLA.Library } public partial class TransitionLookup { - public event TransitionLookupEvent NewLookupNeeded; - private Dictionary> _MyLookups; - public Dictionary> MyLookups + //False Positive - Event is In Use + #pragma warning disable 67 + public event TransitionLookupEvent NewLookupNeeded; +#pragma warning restore 67 + public Dictionary> MyLookups { get; set; } + public int ApplicabilityUnit { get; set; } + public TransitionLookup(int applicabilityUnit, int procID, Dictionary mylookup) { - get { return _MyLookups; } - set { _MyLookups = value; } - } - private int _ApplicabilityUnit; - public int ApplicabilityUnit - { - get { return _ApplicabilityUnit; } - set { _ApplicabilityUnit = value; } - } - public TransitionLookup(int applicabilityUnit, int procID, Dictionary mylookup) - { - _MyLookups = new Dictionary>(); - _MyLookups.Add(procID, mylookup); - _ApplicabilityUnit = applicabilityUnit; + MyLookups = new Dictionary> + { + { procID, mylookup } + }; + ApplicabilityUnit = applicabilityUnit; } public void AddProcLookup(int procID, Dictionary mylookup) { - if (!_MyLookups.ContainsKey(procID)) + if (!MyLookups.ContainsKey(procID)) { - _MyLookups.Add(procID, mylookup); + MyLookups.Add(procID, mylookup); //Console.WriteLine("AddProcLookup: {0}", procID); } } @@ -8028,7 +7967,7 @@ namespace VEPROMS.CSLA.Library foreach (PartInfo pi in ii.MyContent.ContentParts) pi.Dispose(); ii.MyContent.ContentParts.Dispose(); } - if (ii.MyContent.MyGrid != null) ii.MyContent.MyGrid.Dispose(); + ii.MyContent.MyGrid?.Dispose(); ii.MyContent.Dispose(); ii.Dispose(); } @@ -8097,7 +8036,7 @@ namespace VEPROMS.CSLA.Library { if (Sections != null) // B2017-145 If no sections don't check { - foreach (SectionInfo mySection in Sections) + foreach (SectionInfo mySection in Sections.OfType()) { if (mySection.MyDocStyle.SupplementalInformation && mySection.HasSupInfoSteps) return true; } @@ -8134,14 +8073,11 @@ namespace VEPROMS.CSLA.Library public void ResetChangeBar() => _ChangeBarDate = null; public Dictionary MyLookup = null; - public override void SetupTags() - { - base.SetupTags(); - } - protected override void RefreshFields(Item tmp) + public override void SetupTags() => base.SetupTags(); + protected override void RefreshFields(Item tmp) { base.RefreshFields(tmp); - ExtensionRefreshFields(tmp); + ExtensionRefreshFields(); _ChangeBarDate = null; _ProcedureConfig = null; } @@ -8153,8 +8089,6 @@ namespace VEPROMS.CSLA.Library private ProcedureInfo() : base() { ;} public new static ProcedureInfo Get(int itemID, bool forcerefresh = false) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Item"); try { //C2019-036 View Only mode work with Checked Out Procedures @@ -8189,29 +8123,15 @@ namespace VEPROMS.CSLA.Library return ii as ProcedureInfo; return null; } - public void MoveProcedure(IVEDrillDownReadOnly pInfo, int index) + public void MoveProcedure(IVEDrillDownReadOnly pInfo, int index) => MoveItem(pInfo, index); + public new Procedure Get() => (Procedure)(_Editable = Procedure.Get(ItemID)); + public static void RefreshTransitions(ProcedureInfo tmp) { - MoveItem(pInfo, index); - //using (Item ii = Item.Get(this.ItemID)) - //{ - // ii.MoveItem(pInfo, index); - //} - } - public new Procedure Get() - { - return (Procedure)(_Editable = Procedure.Get(ItemID)); - } - //public static void RefreshTransitions(ProcedureInfo tmp) - //{ - // RefreshTransitions(tmp, null, null); - //} - public static void RefreshTransitions(ProcedureInfo tmp)//, TransitionInfoList transitionToDisconnected, TransitionInfoList transitionsToNonEditable) - { - //TransitionsToDisconnected = transitionToDisconnected; - //TransitionsToNonEditable = transitionsToNonEditable; - TransitionLookup tranLookup = new TransitionLookup(0, tmp.ItemID, tmp.MyLookup); - tranLookup.ApplicabilityUnit = tmp.MyDocVersion.DocVersionConfig.SelectedSlave; - tranLookup.NewLookupNeeded += new TransitionLookupEvent(GetNewLookup); + TransitionLookup tranLookup = new TransitionLookup(0, tmp.ItemID, tmp.MyLookup) + { + ApplicabilityUnit = tmp.MyDocVersion.DocVersionConfig.SelectedSlave + }; + tranLookup.NewLookupNeeded += new TransitionLookupEvent(GetNewLookup); if (tmp.MyDocVersion.DocVersionConfig.SelectedSlave <= 0) MyRefreshTransitions(tmp, tmp.MyDocVersion, null, tmp, tmp.MyDocVersion, tranLookup); } @@ -8229,9 +8149,11 @@ namespace VEPROMS.CSLA.Library } public static void RefreshPageNumTransitions(ProcedureInfo tmp) { - TransitionLookup tranLookup = new TransitionLookup(0, tmp.ItemID, tmp.MyLookup); - tranLookup.ApplicabilityUnit = tmp.MyDocVersion.DocVersionConfig.SelectedSlave; - tranLookup.NewLookupNeeded += new TransitionLookupEvent(GetNewLookup); + TransitionLookup tranLookup = new TransitionLookup(0, tmp.ItemID, tmp.MyLookup) + { + ApplicabilityUnit = tmp.MyDocVersion.DocVersionConfig.SelectedSlave + }; + tranLookup.NewLookupNeeded += new TransitionLookupEvent(GetNewLookup); SetParentSectionAndDocVersionPageNum(tmp, tmp.MyDocVersion, null, tmp, tmp.MyDocVersion, tranLookup); } public void ClearChangeBarOverrides() @@ -8278,21 +8200,11 @@ namespace VEPROMS.CSLA.Library (tmp.MyConfig as ProcedureConfig).SelectedSlave = (int)unitID; TransitionLookup tranLookup = new TransitionLookup((int)unitID, (int)itemID, tmp.MyLookup); tranLookup.NewLookupNeeded += new TransitionLookupEvent(GetNewLookup); - //ItemInfo.ResetTicks(); - //DateTime dt = DateTime.Now; tmp.FromType = E_FromType.Procedure; SetFromType(tmp); // B2022-107: Display Progress Bar Messages/Statuses when a new ROFST binary file is loaded into the database // Added Parameter "isAutomatic" to disable the RofstLoadingStatus pop-up screen when printing baselines SetParentSectionAndDocVersion(tmp, tmp.MyDocVersion, null, tmp.MyDocVersion, tranLookup, isAutomatic); - // B2022-025: dispose cached items after setting transition text that gets done in SetParentSectionAndDocVersion & collect related garbage - // B2022-076: comment out dispose. Needed to resolve page number transitions. Note that since B2022-025 was worked, memory improvements have been done for ROs - //tranLookup.Dispose(tmp.ItemID); - //tranLookup = null; - //GC.Collect(); - //TimeSpan ts = DateTime.Now.Subtract(dt); - //ticksItems = ts.Ticks - (ticksROUsage + ticksTrans); - //ItemInfo.ShowTicks(); } return tmp; } @@ -8306,20 +8218,11 @@ namespace VEPROMS.CSLA.Library ProcedureInfo tmp = DataPortal.Fetch(new ItemAndChildrenByUnitCriteria(args.ProcID, 0, args.UnitID)); if (tmp.MyDocVersion != null) { - //if (tmp.MyDocVersion.VersionID == args.MyDocVersion.VersionID) - //{ - // args.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitID; - // (tmp.MyConfig as ProcedureConfig).SelectedSlave = args.UnitID; - // ItemInfo.SetParentSectionAndDocVersion(tmp, args.MyDocVersion, null, tmp, args.MyDocVersion); - //} - //else - //{ tmp.MyDocVersion.DocVersionConfig.SelectedSlave = args.UnitID; (tmp.MyConfig as ProcedureConfig).SelectedSlave = args.UnitID; tmp.FromType = E_FromType.Procedure; SetFromType(tmp); ItemInfo.SetParentSectionAndDocVersion(tmp, tmp.MyDocVersion, null, tmp, tmp.MyDocVersion); - //} } return tmp; } @@ -8376,7 +8279,6 @@ namespace VEPROMS.CSLA.Library { if (dr.GetInt32("Level") == 0) { - //tmp = itemInfo; ReadData(dr); AddContent(dr); lookup[this.ItemID] = this; @@ -8515,7 +8417,6 @@ namespace VEPROMS.CSLA.Library this.MyContent.Changed += new ContentInfoEvent(MyContent_Changed); } return _ProcedureConfig; - // return (_ProcedureConfig != null ? _ProcedureConfig : _ProcedureConfig = new ProcedureConfig(this)); } } @@ -8530,11 +8431,8 @@ namespace VEPROMS.CSLA.Library get { return ProcedureConfig; } set { _ProcedureConfig = null; } } - public DocVersionInfo MyDocVersion - { - get { return ActiveParent as DocVersionInfo; } - } - public static ProcedureInfo GetItemAndChildren(int? itemID, bool isAutomatic = false) + public new DocVersionInfo MyDocVersion => ActiveParent as DocVersionInfo; + public static ProcedureInfo GetItemAndChildren(int? itemID, bool isAutomatic = false) { try { @@ -8563,11 +8461,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ItemAndChildrenCriteria { - public ItemAndChildrenCriteria(int? itemID) - { - _ItemID = itemID; - } - private int? _ItemID; + public ItemAndChildrenCriteria(int? itemID) => _ItemID = itemID; + private int? _ItemID; public int? ItemID { get { return _ItemID; } @@ -8644,11 +8539,8 @@ namespace VEPROMS.CSLA.Library { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private int _ProcedureTransitionsCount; - public int ProcedureTransitionsCount - { - get { return _ProcedureTransitionsCount; } - } - private int _ItemID; + public int ProcedureTransitionsCount => _ProcedureTransitionsCount; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -8657,9 +8549,11 @@ namespace VEPROMS.CSLA.Library #region Factory Methods public static int Execute(int itemID) { - ProcedureTransitionsCountCommand cmd = new ProcedureTransitionsCountCommand(); - cmd.ItemID = itemID; - cmd = DataPortal.Execute(cmd); + ProcedureTransitionsCountCommand cmd = new ProcedureTransitionsCountCommand + { + ItemID = itemID + }; + cmd = DataPortal.Execute(cmd); return cmd.ProcedureTransitionsCount; } private ProcedureTransitionsCountCommand() @@ -8695,23 +8589,19 @@ namespace VEPROMS.CSLA.Library [Serializable()] public partial class Procedure : Item { - public ProcedureInfo MyProcedureInfo /* Return Info version of the current Item */ - { get { return ProcedureInfo.Get(ItemID); } } - public new static Procedure Get(int itemID) + public ProcedureInfo MyProcedureInfo /* Return Info version of the current Item */ +=> ProcedureInfo.Get(ItemID); + public new static Procedure Get(int itemID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Item"); try { Item itm = GetCachedByPrimaryKey(itemID); - Procedure tmp = itm as Procedure; - //Procedure tmp = (Procedure)GetExistingByPrimaryKey(itemID); - if (tmp == null) - { - tmp = DataPortal.Fetch(new PKCriteria(itemID)); - AddToCache(tmp); - } - if (tmp.ErrorMessage == "No Record Found") tmp = null; + if (!(itm is Procedure tmp)) + { + tmp = DataPortal.Fetch(new PKCriteria(itemID)); + AddToCache(tmp); + } + if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) @@ -8719,11 +8609,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on Item.Get", ex); } } - public new Procedure Save() - { - return (Procedure)base.Save(); - } - public static Procedure MakeProcedure(IVEDrillDownReadOnly parentInfo, ItemInfo previousInfo, string procNumber, string procTitle, int procType) + public new Procedure Save() => (Procedure)base.Save(); + public static Procedure MakeProcedure(IVEDrillDownReadOnly parentInfo, ItemInfo previousInfo, string procNumber, string procTitle, int procType) { int newitemid = MakeNewItem(parentInfo, previousInfo, procNumber, procTitle, procType, E_FromType.Procedure); return Procedure.Get(newitemid); @@ -8743,34 +8630,15 @@ namespace VEPROMS.CSLA.Library return _ProcedureConfig; } } - private void _ProcedureConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + private void _ProcedureConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) => MyContent.Config = _ProcedureConfig.ToString(); + #endregion + public class DisplayTabs { - MyContent.Config = _ProcedureConfig.ToString(); - } - #endregion - public class DisplayTabs - { - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } + public int ItemID { get; set; } + public string DisplayTabID { get; set; } + public string DisplayTabName { get; set; } - } - private string _DisplayTabID; - public string DisplayTabID - { - get { return _DisplayTabID; } - set { _DisplayTabID = value; } - } - private string _DisplayTabName; - public string DisplayTabName - { - get { return _DisplayTabName; } - set { _DisplayTabName = value; } - } - - public SafeDataReader Dr { get; } + public SafeDataReader Dr { get; } public DisplayTabs() { @@ -8779,16 +8647,13 @@ namespace VEPROMS.CSLA.Library public DisplayTabs(int itemID, String displayTabID, String displayTabName) { - _ItemID = itemID; - _DisplayTabID = displayTabID; - _DisplayTabName = displayTabName; + ItemID = itemID; + DisplayTabID = displayTabID; + DisplayTabName = displayTabName; } - public DisplayTabs(SafeDataReader dr) - { - Dr = dr; - } - } + public DisplayTabs(SafeDataReader dr) => Dr = dr; + } public static void AddDisplayTabsState(int itemID, string displayTabID, string displayTabName) //private void DataPortal_Fetch(int itemID, string displayTabID, string displayTabName) @@ -8807,11 +8672,6 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@displayTabID", displayTabID); cm.Parameters.AddWithValue("@displayTabName", displayTabName); cm.ExecuteNonQuery(); - //SqlDataAdapter da = new SqlDataAdapter(cm); - //da.Fill(dt); - //cn.Close(); - //da.Dispose(); - //return dt; // fix } catch (Exception ex) { @@ -8829,16 +8689,14 @@ namespace VEPROMS.CSLA.Library [Serializable()] public partial class SectionInfo : ItemInfo, IVEDrillDownReadOnly { - // B2017-192: The two dictionaries were introduced so that the lists off of the section were always found - // by the print code that determines what sup info steps go on the facing pages (the code was accessing the - // incorrect cached step section sometimes, so the list was not found. - // Keeps track of itemids for supplemental info steps where their associated steps would have page breaks. - private static Dictionary> _LookupStepSectPageBreaksForSupInfo = new Dictionary>(); - public static void ResetLookupStepSectPageBreaksForSupInfo() - { - _LookupStepSectPageBreaksForSupInfo.Clear(); - } - public List StepSectPageBreaksForSupInfo + // B2017-192: The two dictionaries were introduced so that the lists off of the section were always found + // by the print code that determines what sup info steps go on the facing pages (the code was accessing the + // incorrect cached step section sometimes, so the list was not found. + // Keeps track of itemids for supplemental info steps where their associated steps would have page breaks. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _LookupStepSectPageBreaksForSupInfo = new Dictionary>(); + public static void ResetLookupStepSectPageBreaksForSupInfo() => _LookupStepSectPageBreaksForSupInfo.Clear(); + public List StepSectPageBreaksForSupInfo { get { @@ -8846,13 +8704,11 @@ namespace VEPROMS.CSLA.Library return _LookupStepSectPageBreaksForSupInfo[ItemID]; } } - // Keeps track of step section itemids where page breaks occur - private static Dictionary> _LookupStepSectPageBreaks = new Dictionary>(); - public static void ResetLookupStepSectPageBreaks() - { - _LookupStepSectPageBreaks.Clear(); - } - public List StepSectPageBreaks + // Keeps track of step section itemids where page breaks occur + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _LookupStepSectPageBreaks = new Dictionary>(); + public static void ResetLookupStepSectPageBreaks() => _LookupStepSectPageBreaks.Clear(); + public List StepSectPageBreaks { get { @@ -8915,7 +8771,6 @@ namespace VEPROMS.CSLA.Library if (GetStepCheckOff(iic)) return true; return false; } - //private int? _TemplateColumnMode public override void SetupTags() { VE_Font font; @@ -8929,7 +8784,6 @@ namespace VEPROMS.CSLA.Library else font = ActiveFormat.PlantFormat.FormatData.SectData.SectionNumber.Font; - //MyTab = new Tab(ActiveFormat.PlantFormat.FormatData.SectData.SectionNumber.Font); MyTab = new Tab(font); string sectTab = GetSectionTab(false); _MyTab.Text = sectTab; @@ -8955,38 +8809,37 @@ namespace VEPROMS.CSLA.Library // if displaynumber ends with a '.', don't worry about catching the condition that a tab can be made such as // 'x. x', i.e. space between the . and the rest of tab. This was added for BGEEOPs. if (DisplayNumber.LastIndexOf('.') == DisplayNumber.Length - 1) return DisplayNumber; + string ch = DisplayNumber != null && DisplayNumber != "" ? DisplayNumber.Substring(0, 1) : null; + int Snum = GetSectionNum(); - string retStr = null; - string ch = DisplayNumber != null && DisplayNumber != "" ? DisplayNumber.Substring(0, 1) : null; - int Snum = GetSectionNum(); - if (Snum == -1) - { - if (ch[0] == ' ') ch = DisplayNumber != null && DisplayNumber.TrimStart() != "" ? DisplayNumber.TrimStart().Substring(0, 1) : null; - retStr = ch + "."; - } - else if (Snum == -2) // -2 flags to just use display number as is, don't prepend the parent's number. - { - string tmp = DisplayNumber.Trim(); - if (underline) - retStr = @"\ul " + DisplayNumber.Trim() + @"\ul0 "; - else - retStr = DisplayNumber.Trim(); - } - else - { - string tmp = DisplayNumber.IndexOf(".") > -1 ? DisplayNumber.Substring(0, DisplayNumber.IndexOf(".")) : DisplayNumber; - if (underline) - retStr = @"\ul " + tmp + "." + Snum.ToString() + @"\ul0 "; - else - retStr = tmp + "." + Snum.ToString(); - } - return retStr; + string retStr; + if (Snum == -1) + { + if (ch[0] == ' ') ch = DisplayNumber != null && DisplayNumber.TrimStart() != "" ? DisplayNumber.TrimStart().Substring(0, 1) : null; + retStr = ch + "."; + } + else if (Snum == -2) // -2 flags to just use display number as is, don't prepend the parent's number. + { + if (underline) + retStr = $@"\ul {DisplayNumber.Trim()}\ul0 "; + else + retStr = DisplayNumber.Trim(); + } + else + { + string tmp = DisplayNumber.IndexOf(".") > -1 ? DisplayNumber.Substring(0, DisplayNumber.IndexOf(".")) : DisplayNumber; + if (underline) + retStr = @"\ul " + tmp + "." + Snum.ToString() + @"\ul0 "; + else + retStr = $"{tmp}.{Snum}"; + } + return retStr; } private int GetSectionNum() { - int indx = -1; - if (DisplayNumber != null && DisplayNumber != "" && (indx = DisplayNumber.IndexOf(".")) > -1) + int indx; + if (DisplayNumber != null && DisplayNumber != "" && (indx = DisplayNumber.IndexOf(".")) > -1) { // if there is a number after the '.', return it as a number. For example if it is 001, return a 1: string tmpstr = indx + 1 < DisplayNumber.Length ? DisplayNumber.Substring(indx + 1) : null; @@ -8994,11 +8847,10 @@ namespace VEPROMS.CSLA.Library if (IsSection && tmpstr == null && System.Char.IsLetter(DisplayNumber.TrimStart(), 0)) return -1; if (tmpstr != null && tmpstr.IndexOf('-') >= 0) return -1; if (tmpstr == null) return 0; - Int32 x; - if (Int32.TryParse(tmpstr, out x)) return x; - // flag the case where the current section's tab already has prefixed in the parent's tab: - // (without this, BGE's section headers were coming up as 6.1.6.1.1...) - if (IsSection && ActiveParent.IsSection) + if (Int32.TryParse(tmpstr, out int x)) return x; + // flag the case where the current section's tab already has prefixed in the parent's tab: + // (without this, BGE's section headers were coming up as 6.1.6.1.1...) + if (IsSection && ActiveParent.IsSection) { if (DisplayNumber.StartsWith((ActiveParent as SectionInfo).DisplayNumber.Trim())) return -2; } @@ -9019,9 +8871,8 @@ namespace VEPROMS.CSLA.Library public int CheckOffHeadingIndex() { if (ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList == null || ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList.MaxIndex == 0) return -1; - SectionConfig sc = MyConfig as SectionConfig; - if (sc == null) return -1; - return sc.Section_CheckoffHeaderSelection; + if (!(MyConfig is SectionConfig sc)) return -1; + return sc.Section_CheckoffHeaderSelection; } public bool IsSeparatePagination() { @@ -9030,8 +8881,8 @@ namespace VEPROMS.CSLA.Library { if (SectionConfig != null) sp = SectionConfig.Section_Pagination; } - catch (Exception ex) - { + catch (Exception) + { sp = VEPROMS.CSLA.Library.SectionConfig.SectionPagination.Separate; } if (sp == VEPROMS.CSLA.Library.SectionConfig.SectionPagination.Separate) return true; @@ -9040,7 +8891,7 @@ namespace VEPROMS.CSLA.Library protected override void RefreshFields(Item tmp) { base.RefreshFields(tmp); - ExtensionRefreshFields(tmp); + ExtensionRefreshFields(); } #if ItemWithContent public SectionInfo(SafeDataReader dr) : base(dr, true) { } @@ -9048,10 +8899,8 @@ namespace VEPROMS.CSLA.Library public SectionInfo(SafeDataReader dr) : base(dr) { } #endif private SectionInfo() : base() { ;} - public new static SectionInfo Get(int itemID) + public static SectionInfo Get(int itemID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Item"); try { SectionInfo tmp = GetCachedByPrimaryKey(itemID); @@ -9078,26 +8927,15 @@ namespace VEPROMS.CSLA.Library return ii as SectionInfo; return null; } - public void MoveSection(IVEDrillDownReadOnly pInfo, int index) - { - MoveItem(pInfo, index); - //using (Item ii = Item.Get(this.ItemID)) - //{ - // ii.MoveItem(pInfo, index); - //} - } - public new Section Get() - { - return (Section)(_Editable = Section.Get(ItemID)); - } + public void MoveSection(IVEDrillDownReadOnly pInfo, int index) => MoveItem(pInfo, index); + public new Section Get() => (Section)(_Editable = Section.Get(ItemID)); - #region SectionConfig - [NonSerialized] + #region SectionConfig + [NonSerialized] public SectionConfig _SectionConfig; - public SectionConfig SectionConfig - { get { return (_SectionConfig != null ? _SectionConfig : _SectionConfig = new SectionConfig(this)); } } - #endregion - public new ConfigDynamicTypeDescriptor MyConfig + public SectionConfig SectionConfig => (_SectionConfig ?? (_SectionConfig = new SectionConfig(this))); + #endregion + public new ConfigDynamicTypeDescriptor MyConfig { get { return SectionConfig; } set { _SectionConfig = null; } @@ -9108,21 +8946,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] public partial class Section : Item { - public SectionInfo MySectionInfo /* Return Info version of the current Item */ - { get { return SectionInfo.Get(ItemID); } } - public new static Section Get(int itemID) + public SectionInfo MySectionInfo /* Return Info version of the current Item */ +=> SectionInfo.Get(ItemID); + public new static Section Get(int itemID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Item"); try { - Section tmp = GetCachedByPrimaryKey(itemID) as Section; - if (tmp == null) - { - tmp = DataPortal.Fetch
(new PKCriteria(itemID)); - AddToCache(tmp); - } - if (tmp.ErrorMessage == "No Record Found") tmp = null; + if (!(GetCachedByPrimaryKey(itemID) is Section tmp)) + { + tmp = DataPortal.Fetch
(new PKCriteria(itemID)); + AddToCache(tmp); + } + if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) @@ -9130,11 +8965,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on Item.Get", ex); } } - public new Section Save() - { - return (Section)base.Save(); - } - public static Section MakeSection(IVEDrillDownReadOnly parentInfo, ItemInfo previousInfo, string sectNumber, string sectTitle, int sectType) + public new Section Save() => (Section)base.Save(); + public static Section MakeSection(IVEDrillDownReadOnly parentInfo, ItemInfo previousInfo, string sectNumber, string sectTitle, int sectType) { int newitemid = MakeNewItem(parentInfo, previousInfo, sectNumber, sectTitle, sectType, E_FromType.Section); return Section.Get(newitemid); @@ -9154,12 +8986,9 @@ namespace VEPROMS.CSLA.Library return _SectionConfig; } } - private void _SectionConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) - { - MyContent.Config = _SectionConfig.ToString(); - } - #endregion - } + private void _SectionConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) => MyContent.Config = _SectionConfig.ToString(); + #endregion + } #endregion #region StepInfo [Serializable()] @@ -9167,11 +8996,10 @@ namespace VEPROMS.CSLA.Library { #region StepConfig public StepConfig _StepConfig; - public StepConfig StepConfig - { get { return (_StepConfig != null ? _StepConfig : _StepConfig = new StepConfig(this)); } } - #endregion - #region Tab - public override void SetupTags() + public StepConfig StepConfig => _StepConfig ?? (_StepConfig = new StepConfig(this)); + #endregion + #region Tab + public override void SetupTags() { _TagsSetup = true; // B2016-160 Support transitions to sections @@ -9187,22 +9015,16 @@ namespace VEPROMS.CSLA.Library protected override void RefreshFields(Item tmp) { base.RefreshFields(tmp); - ExtensionRefreshFields(tmp); + ExtensionRefreshFields(); } - //public override string ToString() - //{ - // return "Step " + base.ToString(); - //} #if ItemWithContent public StepInfo(SafeDataReader dr) : base(dr, true) { } #else public StepInfo(SafeDataReader dr) : base(dr) { } #endif private StepInfo() : base() { ;} - public new static StepInfo Get(int itemID) + public static StepInfo Get(int itemID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Item"); try { StepInfo tmp = GetCachedByPrimaryKey(itemID); @@ -9229,21 +9051,9 @@ namespace VEPROMS.CSLA.Library return ii as StepInfo; return null; } - public void MoveStep(IVEDrillDownReadOnly pInfo, int index) - { - MoveItem(pInfo, index); - //using (Item ii = Item.Get(this.ItemID)) - //{ - // ii.MoveItem(pInfo, index); - //} - } - public new Step Get() - { - return (Step)(_Editable = Step.Get(ItemID)); - } - //public E_FromType FromType - //{ get { return E_FromType.Step; } } - } + public void MoveStep(IVEDrillDownReadOnly pInfo, int index) => MoveItem(pInfo, index); + public new Step Get() => (Step)(_Editable = Step.Get(ItemID)); + } #endregion #region Step @@ -9252,8 +9062,6 @@ namespace VEPROMS.CSLA.Library { public new static Step Get(int itemID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Item"); try { Step tmp = (Step)GetCachedByPrimaryKey(itemID); @@ -9270,37 +9078,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on Item.Get", ex); } } - // TODO :MakeCaution; - // TODO :MakeNote; - // TODO :MakeRNO; - // TODO :MakeSection; - // TODO :MakeSubStep; - // TODO :MakeTable; public static Step MakeStep(IVEDrillDownReadOnly parentInfo, ItemInfo previousInfo, string stepNumber, string stepTitle, int stepType, E_FromType fromType) { int newitemid = MakeNewItem(parentInfo, previousInfo, stepNumber, stepTitle, stepType, fromType); return Step.Get(newitemid); } - //#region StepConfig - //[NonSerialized] - //private StepConfig _StepConfig; - //public StepConfig StepConfig - //{ - // get - // { - // if (_StepConfig == null) - // { - // _StepConfig = new StepConfig(this); - // _StepConfig.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_StepConfig_PropertyChanged); - // } - // return _SectionConfig; - // } - //} - //private void _StepConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) - //{ - // MyContent.Config = _StepConfig.ToString(); - //} - //#endregion } #endregion public enum ItemSearchIncludeLinks diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ItemInfoSearchExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ItemInfoSearchExt.cs index c3a747ee..f22b0b3f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ItemInfoSearchExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ItemInfoSearchExt.cs @@ -1,19 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace VEPROMS.CSLA.Library { public partial class ItemInfo { - public ItemInfo SearchNext - { - get - { - return SearchNextSkip(SkipPartType.This); - } - } - private ItemInfo SearchNextSkip(SkipPartType skip) + public ItemInfo SearchNext => SearchNextSkip(SkipPartType.This); + private ItemInfo SearchNextSkip(SkipPartType skip) { if (skip < SkipPartType.Caution && Cautions != null && Cautions.Count > 0) return Cautions[0].SearchTop; if (skip < SkipPartType.Note && Notes != null && Notes.Count > 0) return Notes[0].SearchTop; @@ -28,9 +18,8 @@ namespace VEPROMS.CSLA.Library bool iseditable = true; if (IsSection) { - SectionConfig sc = MyConfig as SectionConfig; - if (sc != null && sc.SubSection_Edit != "Y") iseditable = false; - } + if (MyConfig is SectionConfig sc && sc.SubSection_Edit != "Y") iseditable = false; + } if (iseditable && skip < SkipPartType.Steps && Steps != null && Steps.Count > 0) return Steps[0].SearchTop; if (NextItem != null) return NextItem.SearchTop; @@ -49,9 +38,8 @@ namespace VEPROMS.CSLA.Library { get { - ItemInfo parentItem = ActiveParent as ItemInfo; - if (parentItem == null) return null; - if (IsCautionPart) return parentItem.SearchNextSkip(SkipPartType.Caution); + if (!(ActiveParent is ItemInfo parentItem)) return null; + if (IsCautionPart) return parentItem.SearchNextSkip(SkipPartType.Caution); if (IsNotePart) return parentItem.SearchNextSkip(SkipPartType.Note); if (IsRNOPart) return parentItem.SearchNextSkip(SkipPartType.RNO); if (IsSupInfoPart) return parentItem.SearchNextSkip(SkipPartType.SupInfo); @@ -63,14 +51,8 @@ namespace VEPROMS.CSLA.Library return parentItem.UpOneNext; } } - public ItemInfo SearchPrev - { - get - { - return SearchPrevSkip(SkipPartType.This); - } - } - private ItemInfo SearchPrevSkip(SkipPartType skip) + public ItemInfo SearchPrev => SearchPrevSkip(SkipPartType.This); + private ItemInfo SearchPrevSkip(SkipPartType skip) { if (skip > SkipPartType.Steps && Steps != null) return Steps[0].LastSibling.SearchBottom; if (skip > SkipPartType.Sections && Sections != null) return Sections[0].LastSibling.SearchBottom; @@ -101,9 +83,8 @@ namespace VEPROMS.CSLA.Library { get { - ItemInfo parentItem = ActiveParent as ItemInfo; - if (parentItem == null) return null; - if (IsCautionPart) return parentItem.SearchPrevSkip(SkipPartType.Caution); + if (!(ActiveParent is ItemInfo parentItem)) return null; + if (IsCautionPart) return parentItem.SearchPrevSkip(SkipPartType.Caution); if (IsNotePart) return parentItem.SearchPrevSkip(SkipPartType.Note); if (IsRNOPart) return parentItem.SearchPrevSkip(SkipPartType.RNO); if (IsSupInfoPart) return parentItem.SearchPrevSkip(SkipPartType.SupInfo); diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ItemInsertExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ItemInsertExt.cs index 602b5422..7b83940b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ItemInsertExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ItemInsertExt.cs @@ -1,35 +1,24 @@ using System; using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; -using System.Text.RegularExpressions; using Csla; using Csla.Data; using System.Windows.Forms; using JR.Utils.GUI.Forms; +using System.Linq; namespace VEPROMS.CSLA.Library { public delegate void ItemInfoInsertEvent(object sender, ItemInfoInsertEventArgs args); public class ItemInfoInsertEventArgs { - private ItemInfo _ItemInserted; - public ItemInfo ItemInserted + public ItemInfo ItemInserted { get; set; } + public ItemInfo.EAddpingPart AddingPart { get; set; } + public ItemInfoInsertEventArgs(ItemInfo itemInserted,ItemInfo.EAddpingPart addingPart) { - get { return _ItemInserted; } - set { _ItemInserted = value; } - } - private ItemInfo.EAddpingPart _AddingPart; - public ItemInfo.EAddpingPart AddingPart - { - get { return _AddingPart; } - set { _AddingPart = value; } - } - public ItemInfoInsertEventArgs(ItemInfo itemInserted,ItemInfo.EAddpingPart addingPart) - { - _ItemInserted = itemInserted; - _AddingPart = addingPart; + ItemInserted = itemInserted; + AddingPart = addingPart; } } public partial class ItemInfo @@ -39,7 +28,7 @@ namespace VEPROMS.CSLA.Library // C2020-033: The dialog message has been changed to reference the Tools/Search/Incoming Transitions tab and // the return value was changed to return null (this was returning first in list, but now user gets all // listed in the search dialog). This comment is for each of the dialogs below. - string itemDesc = this.GetTypeDescription(); // C2020-018 made the message more accurate when deleting a Procedure, Section, or Step + string itemDesc = GetTypeDescription(); // C2020-018 made the message more accurate when deleting a Procedure, Section, or Step if (ex.Message.Contains("has External Transitions and has no next step")) { using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(ItemID)) @@ -75,124 +64,16 @@ namespace VEPROMS.CSLA.Library using (TransitionInfoList exTrans = TransitionInfoList.GetExternalTransitionsToChildren(ItemID)) { //C2020-018 build the message based on the type description - string msg1 = string.Format("Transitions exist to {0} this {1} and cannot be adjusted automatically.", (this.IsSection) ? "steps in" : "children of", itemDesc); - DialogResult ans = FlexibleMessageBox.Show(msg1 + - "\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", - "Cannot Delete This " + itemDesc, MessageBoxButtons.OK, MessageBoxIcon.Information); - } + string msg1 = string.Format("Transitions exist to {0} this {1} and cannot be adjusted automatically.", (IsSection) ? "steps in" : "children of", itemDesc); + _ = FlexibleMessageBox.Show(msg1 + + "\r\n\r\nThe list of all locations are shown in the Tools/Search/Incoming Transitions tab.", + "Cannot Delete This " + itemDesc, MessageBoxButtons.OK, MessageBoxIcon.Information); + } } else FlexibleMessageBox.Show(ex.Message, "SQL Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } - - #region Old Insert - //public ItemInfo InsertSiblingBeforeOld(string text) - //{ - // return InsertSiblingBefore(text, null); - //} - //public ItemInfo InsertSiblingBeforeOld(string text, string number) - //{ - // ItemInfo prevItemInfo = MyPrevious; - // ItemInfo newItemInfo = null; - // PartInfoList partInfoList = null; - // if (MyParent != null && MyParent.MyContent != null) - // { - // MyParent.MyContent.RefreshContentParts(); - // partInfoList = MyParent.MyContent.ContentParts; - // } - // using (Item prevItem = prevItemInfo == null ? null : prevItemInfo.Get()) // Get the previous Item - // { - // using (Item newItem = Item.MakeItem(prevItem, Content.MakeContent(number, text, MyContent.Type, null, null))) // Create the new Item - // { - // using (Item thisItem = Get()) // Get the next item in the list - // { - // thisItem.MyPrevious = newItem; // Point to the new item - // thisItem.Save(); // Save Changes - // if (prevItem == null) - // { - // PartInfo partInfo = partInfoList.Find(this); - // using (Part part = partInfo.Get()) - // { - // part.MyItem = newItem; - // part.Save(); - // } - // } - // } - // // ToDo: Need change PartInfo in PartInfoList - // newItemInfo = ItemInfo.Get(newItem.ItemID); - // newItemInfo.ResetOrdinal(); - // } - // } - // return newItemInfo; - //} - //public ItemInfo InsertSiblingAfterOld(string text) - //{ - // return InsertSiblingAfter(text, null); - //} - //public ItemInfo InsertSiblingAfterOld(string text, string number) - //{ - // return InsertSiblingAfter(text, number, MyContent.Type); - //} - //public ItemInfo InsertSiblingAfterOld(string text, string number, int? type) - //{ - // ItemInfo nextItemInfo = NextItem; - // ItemInfo newItemInfo = null; - // using (Item thisItem = Get()) // Get the Current Item - // { - // using (Item newItem = Item.MakeItem(thisItem, Content.MakeContent(number, text, type, null, null))) // Create the new Item - // { - // if (nextItemInfo != null) // Simple case, adding to end of list: - // using (Item nextItem = nextItemInfo.Get()) // Get the next item in the list - // { - // nextItem.MyPrevious = newItem; // Point to the new item - // nextItem.Save(); // Save Changes - // } - // // ToDo: Need change PartInfo in PartInfoList - // newItemInfo = ItemInfo.Get(newItem.ItemID); - // newItemInfo.ResetOrdinal(); - // } - // } - // return newItemInfo; - //} - //public ItemInfo InsertChildOld(E_FromType fromType, int type, string text) - //{ - // return InsertChild(fromType, type, text, null); - //} - //public ItemInfo InsertChildOld(E_FromType fromType, int type, string text, string number) - //{ - // ItemInfo newItemInfo = null; - // using (Item thisItem = Get()) // Get the Current Item - // { - // using (Item newItem = Item.MakeItem(null, Content.MakeContent(number, text, type, null, null))) // Create the new Item - // { - // PartInfo partInfo = MyContent.ContentParts == null ? null : MyContent.ContentParts.Find(fromType); - // if (partInfo != null) - // { - // //this could be equivalent to adding a sibling with a specific type - // using (Part part = partInfo.Get()) - // { - // part.MyItem.MyPrevious = newItem; - // part.MyItem.Save(); - // part.MyItem = newItem; - // part.Save(); - // } - // } - // else - // { - // // This means that a part needs to be added to point to the new item - // //using (Part part = Part.MakePart(thisItem.MyContent, )) - // //{ ;} - // thisItem.MyContent.ContentParts.Add((int)fromType, newItem); - // thisItem.Save(); - // } - // newItemInfo = ItemInfo.Get(newItem.ItemID); - // } - // } - // ResetParts(); - // return newItemInfo; - //} - #endregion #region Events public event ItemInfoEvent BeforeDelete; public void OnBeforeDelete() @@ -209,16 +90,6 @@ namespace VEPROMS.CSLA.Library } } } - //if (ItemPartCount > 0) - //{ - // foreach (PartInfo pi in ItemParts) - // { - // foreach (ItemInfo ii in pi.MyItems) - // { - // ii.OnBeforeDelete(); - // } - // } - //} } private void OnBeforeDelete(int ItemID) @@ -227,58 +98,38 @@ namespace VEPROMS.CSLA.Library { List itmlst = _CacheByPrimaryKey[ItemID.ToString()]; foreach (ItemInfo itm in itmlst) - if (itm.BeforeDelete != null) - { - itm.BeforeDelete(itm); - } - } + itm.BeforeDelete?.Invoke(itm); + } } public static event ItemInfoEvent ItemDeleted; public event ItemInfoEvent Deleted; internal void OnDeleted(object sender) { - if (Deleted != null) Deleted(sender); - if (ItemDeleted != null) ItemDeleted(sender); - if (MyParent != null) + Deleted?.Invoke(sender); + ItemDeleted?.Invoke(sender); + if (MyParent != null) { MyParent.OnChildrenDeleted(sender); MyParent.MyContent.RefreshContentParts(); } } - //internal void OnDeleted(object sender, Volian.Base.Library.VlnTimer tmr) - //{ - //tmr.ActiveProcess = "Deleted"; - //if (Deleted != null) Deleted(sender); - //tmr.ActiveProcess = "ItemDeleted"; - //if (ItemDeleted != null) ItemDeleted(sender); - //if (MyParent != null) - //{ - //tmr.ActiveProcess = "OnChildrenDeleted"; - //MyParent.OnChildrenDeleted(sender); - //tmr.ActiveProcess = "RefreshContentParts"; - //MyParent.MyContent.RefreshContentParts(); - //} - //} public event ItemInfoEvent ChildrenDeleted; - internal void OnChildrenDeleted(object sender) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping sender for possible future use / debugging")] + internal void OnChildrenDeleted(object sender) { if (_CacheByPrimaryKey.ContainsKey(ItemID.ToString())) { List itmlst = _CacheByPrimaryKey[ItemID.ToString()]; foreach (ItemInfo itm in itmlst) - if (itm.ChildrenDeleted != null) - { - itm.ChildrenDeleted(itm); - } - } + itm.ChildrenDeleted?.Invoke(itm); + } } public event ItemInfoInsertEvent NewSiblingAfter; internal void OnNewSiblingAfter(object sender, ItemInfoInsertEventArgs args) { - if (NewSiblingAfter != null) NewSiblingAfter(sender,args); - if (MyParent != null) - MyParent.MyContent.RefreshContentParts(); + NewSiblingAfter?.Invoke(sender, args); + MyParent?.MyContent.RefreshContentParts(); } internal void OnNewSiblingAfter(ItemInfoInsertEventArgs args) { @@ -295,9 +146,8 @@ namespace VEPROMS.CSLA.Library public event ItemInfoInsertEvent NewSiblingBefore; internal void OnNewSiblingBefore(object sender, ItemInfoInsertEventArgs args) { - if (NewSiblingBefore != null) NewSiblingBefore(sender,args); - if (MyParent != null) - MyParent.MyContent.RefreshContentParts(); + NewSiblingBefore?.Invoke(sender, args); + MyParent?.MyContent.RefreshContentParts(); } internal void OnNewSiblingBefore(ItemInfoInsertEventArgs args) { @@ -314,8 +164,8 @@ namespace VEPROMS.CSLA.Library public event ItemInfoInsertEvent NewChild; internal void OnNewChild(object sender, ItemInfoInsertEventArgs args) { - if (NewChild != null) NewChild(sender, args); - MyContent.RefreshContentParts(); + NewChild?.Invoke(sender, args); + MyContent.RefreshContentParts(); } internal void OnNewChild(ItemInfoInsertEventArgs args) { @@ -329,17 +179,11 @@ namespace VEPROMS.CSLA.Library } } } - #endregion - #region Insert Before - public ItemInfo InsertSiblingBefore(string text) - { - return InsertSiblingBefore(text, null); - } - public ItemInfo InsertSiblingBefore(string text, string number) - { - return InsertSiblingBefore(text, number, null); - } - public ItemInfo InsertSiblingBefore(string text, string number,int? type) + #endregion + #region Insert Before + public ItemInfo InsertSiblingBefore(string text) => InsertSiblingBefore(text, null); + public ItemInfo InsertSiblingBefore(string text, string number) => InsertSiblingBefore(text, number, null); + public ItemInfo InsertSiblingBefore(string text, string number,int? type) { ItemInfo tmp = null; if (!IsSection && (FormatStepData.UseSmartTemplate || (MyHLS != null && MyHLS.FormatStepData.UseSmartTemplate) || FormatStepData.UseOldTemplate)) @@ -521,7 +365,7 @@ namespace VEPROMS.CSLA.Library : (cpItem.IsSection ? E_FromType.Section : E_FromType.Step))); try { - ItemInfo tmp = CopyPasteItemInfoFetch(copyStartID, this.ItemID, type, fromtype, EAddpingPart.Child); + ItemInfo tmp = CopyPasteItemInfoFetch(copyStartID, ItemID, type, fromtype, EAddpingPart.Child); using (Item item = Get()) ItemInfo.Refresh(item); if (tmp.NextItem != null) using (Item item = tmp.NextItem.Get()) ItemInfo.Refresh(item); RefreshNextItems(); @@ -562,21 +406,13 @@ namespace VEPROMS.CSLA.Library ItemInfo cpyItem = ItemInfo.Get(copyStartID); return GetMaxSubStepLevel(cpyItem); } - // F2021-009 Find the number of defined sequential tabs. We use this to determin the number of defined sub-step levels - public int GetDefinedSubStepCount() - { - return GetDefinedSubStepCount(this); - } - // F2021-009 Find the number of defined sequential tabs. We use this to determin the number of defined sub-step levels - public static int GetDefinedSubStepCount(ItemInfo curStep) - { - int cnt = 0; - cnt = curStep.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SeqTabFmtList.Count; - return cnt-1; // -1 to account for the high level step level - } - // F2021-009 for PROMS Express, display a message if the Paste of a CopyStep will results in sub-step levels - // greater than what is defined in the format - public static bool PasteStepIsWithinDefinedSubStepLevels(int copyStartID, ItemInfo pasteTarget, bool doingReplace) + // F2021-009 Find the number of defined sequential tabs. We use this to determin the number of defined sub-step levels + public int GetDefinedSubStepCount() => GetDefinedSubStepCount(this); + // F2021-009 Find the number of defined sequential tabs. We use this to determin the number of defined sub-step levels + public static int GetDefinedSubStepCount(ItemInfo curStep) => curStep.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SeqTabFmtList.Count - 1; // -1 to account for the high level step level + // F2021-009 for PROMS Express, display a message if the Paste of a CopyStep will results in sub-step levels + // greater than what is defined in the format + public static bool PasteStepIsWithinDefinedSubStepLevels(int copyStartID, ItemInfo pasteTarget, bool doingReplace) { int largestSubStepLevel = GetCopyStepMaxLevels(copyStartID); int numDefinedSubstepLevels = GetDefinedSubStepCount(pasteTarget); @@ -601,8 +437,8 @@ namespace VEPROMS.CSLA.Library // B2023-049: crash when copied step is no longer available (may have been deleted in previous operation) if (cpyItem == null) { - DialogResult msgBoxResult = FlexibleMessageBox.Show("The step you are pasting no longer exists - it may have been deleted as part of a previous operation.", "Paste Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); - return false; + _ = FlexibleMessageBox.Show("The step you are pasting no longer exists - it may have been deleted as part of a previous operation.", "Paste Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return false; } // B2017-065 use MyContent instead of _Mycontent so that if null it will get the needed content int? SourceType = cpyItem.MyContent.Type; @@ -616,31 +452,16 @@ namespace VEPROMS.CSLA.Library } return true; } - // B2016-009 - added a message box explaining to the user that the copyed step will take on the destination type. 16-bit PROMS had also done this way. - // - this one is used for Insert Copyed step Before or After - // C2022-017 Added a Cancel button to the message box to allow the user to cancel the paste operation - private bool CheckSourceDestinationType(int? DestType, int? SourceType) - { - if (DestType >= 20000 && DestType != SourceType) - { - string msg = "The step you are copying TO is a different type than the step you are copying FROM.\n\nThe copied step will inherit the destination step type.\n\nOnce copied, the step type can be changed from the Tags tab on the Step Properties panel."; - DialogResult msgBoxResult = FlexibleMessageBox.Show(msg, "Different Step Types", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); - if (msgBoxResult == DialogResult.Cancel) - return false; - } - return true; - } public ItemInfo PasteSiblingBefore(int copyStartID, string chgid) { // To determine 'type' of pasted item, if it's a step (type >=20000), use the originating // item, i.e. item inserting after. If it's a section or procedure, use the copied item's type. ItemInfo cpItem = ItemInfo.Get(copyStartID); // B2016-009 check source and desintation types and display message box if needed - // C2022-017 moved the CheckSourceDestinationType call to btnPasteReplace_Click in StepTabRibbon int? type = MyContent.Type >= 20000 ? MyContent.Type : cpItem.MyContent.Type; try { - ItemInfo tmp = CopyPasteItemInfoFetch(copyStartID, this.ItemID, type, type, EAddpingPart.Before); + ItemInfo tmp = CopyPasteItemInfoFetch(copyStartID, ItemID, type, type, EAddpingPart.Before); using (Item item = Get()) ItemInfo.Refresh(item); tmp.UpdateTransitionText(); tmp.UpdateROText(); @@ -663,11 +484,10 @@ namespace VEPROMS.CSLA.Library // item, i.e. item inserting after. If it's a section or procedure, use the copied item's type. ItemInfo cpItem = ItemInfo.Get(copyStartID); // B2016-009 check source and desintation types and display message box if needed - // C2022-017 moved the CheckSourceDestinationType call to btnPasteReplace_Click in StepTabRibbon int? type = MyContent.Type >= 20000 ? MyContent.Type : cpItem.MyContent.Type; try { - ItemInfo tmp = CopyPasteItemInfoFetch(copyStartID, this.ItemID, type, type, EAddpingPart.After); + ItemInfo tmp = CopyPasteItemInfoFetch(copyStartID, ItemID, type, type, EAddpingPart.After); using (Item item = Get()) ItemInfo.Refresh(item); if (tmp.NextItem != null) using (Item item = tmp.NextItem.Get()) ItemInfo.Refresh(item); RefreshNextItems(); @@ -691,29 +511,29 @@ namespace VEPROMS.CSLA.Library } private bool HandleSqlExceptionOnCopy(Exception ex) { - if (ex.Message.Contains("Collection was modified;")) - { - _MyLog.WarnFormat(ex.Message); - return true; - } - if (ex.Message.Contains("This step has been deleted")) - { - FlexibleMessageBox.Show("The step being pasted has been deleted!", "Cannot Paste Deleted Step" - , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand); - return true; - } - if(ex.Message.Contains("This current step has been deleted in another session")) - { - FlexibleMessageBox.Show("The highlighted step has been deleted by another user!", "Cannot Paste Step" - , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand); - return true; - } - return false; + if (ex.Message.Contains("Collection was modified;")) + { + _MyLog.WarnFormat(ex.Message); + return true; + } + if (ex.Message.Contains("This step has been deleted")) + { + FlexibleMessageBox.Show("The step being pasted has been deleted!", "Cannot Paste Deleted Step" + , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand); + return true; + } + if(ex.Message.Contains("This current step has been deleted in another session")) + { + FlexibleMessageBox.Show("The highlighted step has been deleted by another user!", "Cannot Paste Step" + , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Hand); + return true; + } + return false; } private ItemInfo CopyPasteItemInfoFetch(int copyStartID, int itemID, int? type, int? fromType, EAddpingPart addType) { - ItemInfo tmp=null; - if (addType == EAddpingPart.Child) // has to add in child relationship - uses 'fromtype' + ItemInfo tmp; + if (addType == EAddpingPart.Child) // has to add in child relationship - uses 'fromtype' { // adding children. Type is based on 'fromType' switch ((E_FromType)fromType) @@ -742,17 +562,11 @@ namespace VEPROMS.CSLA.Library return tmp; } - #endregion - #region Insert After - public ItemInfo InsertSiblingAfter(string text) - { - return InsertSiblingAfter(text, null); - } - public ItemInfo InsertSiblingAfter(string text, string number) - { - return InsertSiblingAfter(text, number, MyContent.Type); - } - public ItemInfo InsertSiblingAfter(string text, string number, int? type) + #endregion + #region Insert After + public ItemInfo InsertSiblingAfter(string text) => InsertSiblingAfter(text, null); + public ItemInfo InsertSiblingAfter(string text, string number) => InsertSiblingAfter(text, number, MyContent.Type); + public ItemInfo InsertSiblingAfter(string text, string number, int? type) { ItemInfo tmp = null; // KBR need template code in tree view? if (!IsSection && (FormatStepData.UseSmartTemplate || (MyHLS != null && MyHLS.FormatStepData.UseSmartTemplate) || FormatStepData.UseOldTemplate)) @@ -807,10 +621,9 @@ namespace VEPROMS.CSLA.Library public void UpdateTransitionText() { // Update Ordinals from here down for Steps - //if (!IsStep) return; ResetOrdinal(); // This returns a list of all of the transitions that may have been affected - using(TransitionInfoList trans = TransitionInfoList.GetAffected(this.ItemID)) + using(TransitionInfoList trans = TransitionInfoList.GetAffected(ItemID)) { #region B2012-071 fix JCB foreach (TransitionInfo tran in trans) @@ -826,7 +639,7 @@ namespace VEPROMS.CSLA.Library { oldContent.DTS = DateTime.Now; #region B2012-079 fix JCB - oldContent.UserID = Volian.Base.Library.VlnSettings.UserID + " - Renumber"; + oldContent.UserID = $"{Volian.Base.Library.VlnSettings.UserID} - Renumber"; #endregion B2012-079 fix JCB oldContent.Save(); } @@ -840,7 +653,6 @@ namespace VEPROMS.CSLA.Library if (tran.MyItemToID.ActiveSection != null) { SectionConfig sc = tran.MyItemToID.ActiveSection.MyConfig as SectionConfig; - //SectionConfig sc = new SectionConfig(tran.MyItemToID.ActiveSection.MyConfig.ToString()); forceConvertToText = (sc.SubSection_Edit == "N" && tran.MyItemToID.IsStep); // Bug fix B2016-081 also check if transition is to a step element } if (!forceConvertToText) //check to see if external with internal format @@ -853,18 +665,13 @@ namespace VEPROMS.CSLA.Library forceConvertToText = true; } oldContent.FixTransitionText(tran, forceConvertToText); - //if (content.IsDirty) - //{ - // content.DTS = DateTime.Now; - // content.Save(); - //} if (oldContent != null) { if (oldContent.IsDirty) { oldContent.DTS = DateTime.Now; #region B2012-079 fix JCB - oldContent.UserID = Volian.Base.Library.VlnSettings.UserID + " - Renumber"; + oldContent.UserID = $"{Volian.Base.Library.VlnSettings.UserID} - Renumber"; #endregion B2012-079 fix JCB oldContent.Save(); } @@ -881,7 +688,7 @@ namespace VEPROMS.CSLA.Library { // Get a list of all of the transitions included in this step & its children. // Their transition text may have been affected, i.e. depending on the format, etc - using (TransitionInfoList trans = TransitionInfoList.GetPastedAffected(this.ItemID)) + using (TransitionInfoList trans = TransitionInfoList.GetPastedAffected(ItemID)) { foreach (TransitionInfo tran in trans) { @@ -892,7 +699,6 @@ namespace VEPROMS.CSLA.Library if (tran.MyItemToID.ActiveSection != null) { SectionConfig sc = tran.MyItemToID.ActiveSection.MyConfig as SectionConfig; - //SectionConfig sc = new SectionConfig(tran.MyItemToID.ActiveSection.MyConfig.ToString()); forceConvertToText = (sc.SubSection_Edit == "N" && tran.MyItemToID.IsStep); // Bug fix B2016-081 also check if transition is to a step element } if (!forceConvertToText) //check to see if external with internal format @@ -923,7 +729,7 @@ namespace VEPROMS.CSLA.Library if (!dvsLinked) { string destProcNumber = tran.MyItemToID.MyProcedure.DisplayNumber; - foreach (ProcedureInfo prci in tran.MyContent.ContentItems[0].MyDocVersion.Procedures) + foreach (ProcedureInfo prci in tran.MyContent.ContentItems[0].MyDocVersion.Procedures.OfType()) { if (prci.DisplayNumber == destProcNumber) { @@ -984,17 +790,13 @@ namespace VEPROMS.CSLA.Library foreach (EnhancedDocument ed in seleds) pasteItem.DoUnlinkEnhanced(pasteItem, ed.Type, true); } } - #endregion - #region Insert Child - public ItemInfo InsertChild(E_FromType fromType, int type, string text) - { - return InsertChild(fromType, type, text, null); - } - public ItemInfo InsertChild(E_FromType fromType, int type, string text, string number) + #endregion + #region Insert Child + public ItemInfo InsertChild(E_FromType fromType, int type, string text) => InsertChild(fromType, type, text, null); + public ItemInfo InsertChild(E_FromType fromType, int type, string text, string number) { ItemInfo tmp = null; tmp = InsertSmartTemplateSubStep(text, number, tmp, EAddpingPart.Child, type, fromType); - //tmp = InsertSmartTemplateSubStep(text, number, tmp, EAddpingPart.After, type); if (tmp == null) tmp = NewItemInfoFetch(ItemID, EAddpingPart.Child, number, text, type, (int?)fromType, null, null, DateTime.Now, Volian.Base.Library.VlnSettings.UserID); // if next exists, it is updated in SQL so we have to manually force the iteminfo updates @@ -1016,7 +818,7 @@ namespace VEPROMS.CSLA.Library // its children can be done: ItemInfo existingEnhancedItemInfo = ItemInfo.Get(enhItemID); int type = GetEnhancedTypeForAdd(); // B2018-115: use the correct step type for the add. - ItemInfo newEnhancedItemInfo = existingEnhancedItemInfo.InsertEnhancedSteps(MyContent.Text, null, addpart, type, enhType, ItemID); + ItemInfo newEnhancedItemInfo = existingEnhancedItemInfo.InsertEnhancedSteps(MyContent.Text, null, addpart, type, ItemID); if (newEnhancedItemInfo == null) return null; StepConfig sc = new StepConfig(MyContent.Config); sc.AddEnhancedDocument(enhType, newEnhancedItemInfo.ItemID); @@ -1026,31 +828,29 @@ namespace VEPROMS.CSLA.Library // this method handles inserting new procedures & sections for enhanced documents. // It also handles the case of inserting a step within an EMPTY section. In this case, the template steps - public ItemInfo InsertEnhancedItems(string text, string number, EAddpingPart addType, int? type, int eDocType, int newSourceID) + public ItemInfo InsertEnhancedItems(string text, string number, EAddpingPart addType, int? type, int newSourceID) { - ItemInfo tmp = null; - if (this.IsProcedure && addType == EAddpingPart.Child) // Created a section off a procedure + ItemInfo tmp; + if (IsProcedure && addType == EAddpingPart.Child) // Created a section off a procedure { - string scng = null; - ProcedureConfig pc = new ProcedureConfig(""); + ProcedureConfig pc = new ProcedureConfig(""); pc.AddEnhancedDocument(0, newSourceID); - scng = pc.ToString(); - tmp = InsertChild(E_FromType.Section, 10000, "New Section", null); + string scng = pc.ToString(); + tmp = InsertChild(E_FromType.Section, 10000, "New Section", null); tmp.SaveConfig(scng); } - else if (this.IsSection && addType == EAddpingPart.Child) // Created a HLS off a section, note that the template gets added for the HLS + else if (IsSection && addType == EAddpingPart.Child) // Created a HLS off a section, note that the template gets added for the HLS { - string scng = null; - StepConfig sc = new StepConfig(""); + StepConfig sc = new StepConfig(""); sc.AddEnhancedDocument(0, newSourceID); - scng = sc.ToString(); - tmp = InsertChild(E_FromType.Step, 20002, "New Step", null); + string scng = sc.ToString(); + tmp = InsertChild(E_FromType.Step, 20002, "New Step", null); tmp.SaveConfig(scng); } else // the following code is used for inserting before/after. { - string scng = null; - if (IsSection) + string scng; + if (IsSection) { SectionConfig sc = new SectionConfig(); sc.AddEnhancedDocument(0, newSourceID); @@ -1066,7 +866,7 @@ namespace VEPROMS.CSLA.Library // B2017-083: first child - adjust the docversion itemid to point to this new one: if (IsProcedure && tmp != null && tmp.MyPrevious == null) { - if (this.MyDocVersion != null) + if (MyDocVersion != null) { using (DocVersion parentItemDV = MyDocVersion.Get()) { @@ -1092,13 +892,13 @@ namespace VEPROMS.CSLA.Library OnNewSiblingBefore(new ItemInfoInsertEventArgs(tmp, EAddpingPart.Before)); return tmp; } - public ItemInfo InsertEnhancedSteps(string text, string number, EAddpingPart addType, int? type, int eDocType, int newSourceID) + public ItemInfo InsertEnhancedSteps(string text, string number, EAddpingPart addType, int? type, int newSourceID) { - ItemInfo tmp = null; - if (addType == EAddpingPart.Child) + ItemInfo tmp; + if (addType == EAddpingPart.Child) { E_FromType fromType = E_FromType.Caution; - if (this.IsSection) fromType = E_FromType.Step; + if (IsSection) fromType = E_FromType.Step; else if (ActiveFormat.PlantFormat.FormatData.StepDataList[(int)type - 20000].Type.ToUpper() == "NOTE") fromType = E_FromType.Note; tmp = InsertEnhancedSmartTemplateSubStep(text, number, this, addType, (int)type, fromType, newSourceID); } @@ -1277,7 +1077,7 @@ namespace VEPROMS.CSLA.Library // The ed.Type & ed.itemid show what type of enhanced document (use to create new // config Type). ItemInfo exEnh = ItemInfo.Get(edSource.ItemID); - newEnh = exEnh.InsertEnhancedSteps(tmpCopyStartSourceItem.MyContent.Text, null, addType, MyContent.Type, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedSteps(tmpCopyStartSourceItem.MyContent.Text, null, addType, MyContent.Type, ItemID); if (newEnh == null) return null; StepConfig sc = new StepConfig(MyContent.Config); sc.AddEnhancedDocument(edSource.Type, newEnh.ItemID); @@ -1325,25 +1125,22 @@ namespace VEPROMS.CSLA.Library string cfgEnhStr = null; if (newEnhancedItemInfo.IsStep) { - StepConfig scnewenh = newEnhancedItemInfo.MyConfig as StepConfig; - if (scnewenh == null) break; //error here, i.e. should have a related enhanced step - scnewenh.MyEnhancedDocuments[0].ItemID = newItemInfo.ItemID; + if (!(newEnhancedItemInfo.MyConfig is StepConfig scnewenh)) break; //error here, i.e. should have a related enhanced step + scnewenh.MyEnhancedDocuments[0].ItemID = newItemInfo.ItemID; scnewenh.SaveEnhancedDocuments(); cfgEnhStr = scnewenh.ToString(); } else if (newEnhancedItemInfo.IsSection) { - SectionConfig secnewenh = newEnhancedItemInfo.MyConfig as SectionConfig; - if (secnewenh == null) break; //error here, i.e. should have a related enhanced step - secnewenh.MyEnhancedDocuments[0].ItemID = newItemInfo.ItemID; + if (!(newEnhancedItemInfo.MyConfig is SectionConfig secnewenh)) break; //error here, i.e. should have a related enhanced step + secnewenh.MyEnhancedDocuments[0].ItemID = newItemInfo.ItemID; secnewenh.SaveEnhancedDocuments(); cfgEnhStr = secnewenh.ToString(); } else if (newEnhancedItemInfo.IsProcedure) { - ProcedureConfig pnewenh = newEnhancedItemInfo.MyConfig as ProcedureConfig; - if (pnewenh == null) break; //error here, i.e. should have a related enhanced step - pnewenh.MyEnhancedDocuments[0].ItemID = newItemInfo.ItemID; + if (!(newEnhancedItemInfo.MyConfig is ProcedureConfig pnewenh)) break; //error here, i.e. should have a related enhanced step + pnewenh.MyEnhancedDocuments[0].ItemID = newItemInfo.ItemID; pnewenh.SaveEnhancedDocuments(); cfgEnhStr = pnewenh.ToString(); } @@ -1546,18 +1343,17 @@ namespace VEPROMS.CSLA.Library #region HandleEnhancedStepConfigLinks private void EnhancedSetStepLinks(ItemInfo newSourceSectionInfo, int enhType) { - //for the input source section, link all HLS to enhanced HLS (and any associated cautions/notes). Note that - // this assumes that all source steps are linked, but there may be 'deleted' steps in enhanced that may not be linked back. - ItemInfo newEnhSectionInfo = null; - ItemInfo enhStep = null; // in enhanced document, find first step that has links (there may be enhanced steps that don't have links) + ItemInfo enhStep = null; // in enhanced document, find first step that has links (there may be enhanced steps that don't have links) SectionConfig newSectCfg = newSourceSectionInfo.MyConfig as SectionConfig; foreach (EnhancedDocument ed in newSectCfg.MyEnhancedDocuments) { if (ed.Type == enhType) { - newEnhSectionInfo = ItemInfo.Get(ed.ItemID); - // B2020-009 if section does not have steps (empty step section) then skip it. - if (newEnhSectionInfo.Steps != null) + //for the input source section, link all HLS to enhanced HLS (and any associated cautions/notes). Note that + // this assumes that all source steps are linked, but there may be 'deleted' steps in enhanced that may not be linked back. + ItemInfo newEnhSectionInfo = ItemInfo.Get(ed.ItemID); + // B2020-009 if section does not have steps (empty step section) then skip it. + if (newEnhSectionInfo.Steps != null) { StepConfig cfg = newEnhSectionInfo.Steps[0].MyConfig as StepConfig; if (cfg.MyEnhancedDocuments.Count > 0) enhStep = newEnhSectionInfo.Steps[0]; @@ -1629,7 +1425,7 @@ namespace VEPROMS.CSLA.Library // the following pastes each type of enhanced procedure, including its sections/steps EnhancedPasteItem(copyStartID, pasteFromItem, addType, chgid); // for each enhanced type for this procedure, adjust the config data for its sections/steps: - ProcedureConfig sourceProcConfig = this.MyConfig as ProcedureConfig; + ProcedureConfig sourceProcConfig = MyConfig as ProcedureConfig; foreach (EnhancedDocument enhProc in sourceProcConfig.MyEnhancedDocuments) { if (enhProc.Type != 0) @@ -1646,28 +1442,27 @@ namespace VEPROMS.CSLA.Library { foreach (ItemInfo sourceSect in Sections) { - SectionConfig srcCfg = sourceSect.MyConfig as SectionConfig; - if (srcCfg != null && (srcCfg.Section_LnkEnh != "N") && srcCfg.MyEnhancedDocuments != null && srcCfg.MyEnhancedDocuments.Count > 0) - { - // use pastedEnhancedCurrentSection to link to: - foreach (EnhancedDocument ed in srcCfg.MyEnhancedDocuments) - { - if (ed.Type == enhProc.Type) - { - ed.ItemID = pastedEnhancedCurrentSection.ItemID; - srcCfg.SaveEnhancedDocuments(); - sourceSect.SaveConfig(srcCfg.ToString()); - break; - } - } - SectionConfig enhSectCfg = pastedEnhancedCurrentSection.MyConfig as SectionConfig; - enhSectCfg.MyEnhancedDocuments[0].ItemID = sourceSect.ItemID; - enhSectCfg.SaveEnhancedDocuments(); - pastedEnhancedCurrentSection.SaveConfig(enhSectCfg.ToString()); - if (srcCfg.Section_LnkEnh != "T") EnhancedSetStepLinks(sourceSect, enhProc.Type); //if steps, do them for this type - pastedEnhancedCurrentSection = GetNextEnhancedSection(pastedEnhancedCurrentSection); - } - } + if (sourceSect.MyConfig is SectionConfig srcCfg && (srcCfg.Section_LnkEnh != "N") && srcCfg.MyEnhancedDocuments != null && srcCfg.MyEnhancedDocuments.Count > 0) + { + // use pastedEnhancedCurrentSection to link to: + foreach (EnhancedDocument ed in srcCfg.MyEnhancedDocuments) + { + if (ed.Type == enhProc.Type) + { + ed.ItemID = pastedEnhancedCurrentSection.ItemID; + srcCfg.SaveEnhancedDocuments(); + sourceSect.SaveConfig(srcCfg.ToString()); + break; + } + } + SectionConfig enhSectCfg = pastedEnhancedCurrentSection.MyConfig as SectionConfig; + enhSectCfg.MyEnhancedDocuments[0].ItemID = sourceSect.ItemID; + enhSectCfg.SaveEnhancedDocuments(); + pastedEnhancedCurrentSection.SaveConfig(enhSectCfg.ToString()); + if (srcCfg.Section_LnkEnh != "T") EnhancedSetStepLinks(sourceSect, enhProc.Type); //if steps, do them for this type + pastedEnhancedCurrentSection = GetNextEnhancedSection(pastedEnhancedCurrentSection); + } + } } } } @@ -1676,7 +1471,7 @@ namespace VEPROMS.CSLA.Library else if (IsSection) { ItemInfo pastedSect = EnhancedPasteItem(copyStartID, pasteFromItem, addType, chgid); - SectionConfig sourceSectConfig = this.MyConfig as SectionConfig; + SectionConfig sourceSectConfig = MyConfig as SectionConfig; foreach (EnhancedDocument enhSect in sourceSectConfig.MyEnhancedDocuments) if (enhSect.Type != 0) EnhancedSetStepLinks(this, enhSect.Type); retItem = pastedSect; @@ -1704,7 +1499,7 @@ namespace VEPROMS.CSLA.Library // go to parent ItemInfo newEnh = null; // look through pervious first: - ItemInfo iiCur = this.MyPrevious; + ItemInfo iiCur = MyPrevious; EAddpingPart addtype = EAddpingPart.After; // C2019-045: For enhanced procedures, allow modifications of number & text. When a procedure is inserted, if allowing updates, the number/text doesn't @@ -1726,22 +1521,20 @@ namespace VEPROMS.CSLA.Library { ItemInfo exEnh = ItemInfo.Get(edSource.ItemID); int enhType = (int)MyContent.Type; - // B2017-272 did not need the if-check to set the enhanced type (commented it out) - //if (iiCur.MyContent.Type == MyContent.Type) // B2017-134 the enhanced section was being created with the wrong document type creating new enhanced section from EOP (bryon data) - enhType = (int)exEnh.MyContent.Type; + enhType = (int)exEnh.MyContent.Type; if (exEnh.IsStep) { // B2018-115: use the correct step type for the add. // if coming from a HLS, note or caution, the enhanced type should be the base hls/note/caution type (from GetEnhancedTypeForAdd) enhType = GetEnhancedTypeForAdd(); - newEnh = exEnh.InsertEnhancedSteps(MyContent.Text, null, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedSteps(MyContent.Text, null, addtype, enhType, ItemID); } else { if (!IsProcedure || !exEnh.MyDocVersion.DocVersionConfig.Enhanced_AllowMods) - newEnh = exEnh.InsertEnhancedItems(MyContent.Text, MyContent.Number, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedItems(MyContent.Text, MyContent.Number, addtype, enhType, ItemID); else - newEnh = exEnh.InsertEnhancedItems(ptext, pnum, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedItems(ptext, pnum, addtype, enhType, ItemID); } } } @@ -1749,7 +1542,7 @@ namespace VEPROMS.CSLA.Library } // no previous have enhanced links. now go through next: - ItemInfo iiNxt = this.NextItem; + ItemInfo iiNxt = NextItem; addtype = EAddpingPart.Before; while (iiNxt != null && newEnh == null) { @@ -1759,22 +1552,20 @@ namespace VEPROMS.CSLA.Library { ItemInfo exEnh = ItemInfo.Get(edSource.ItemID); int enhType = (int)MyContent.Type; - // B2017-272 did not need the if-check to set the enhanced type (commented it out) - //if (iiNxt != null && iiNxt.MyContent.Type == MyContent.Type) // B2017-134 the enhanced section was being created with the wrong document type creating new enhanced section from EOP (byron data) (B2017-174: added null check) enhType = (int)exEnh.MyContent.Type; if (exEnh.IsStep) { // B2018-115: use the correct step type for the add. // if coming from a HLS, note or caution, the enhanced type should be the base hls/note/caution type (from GetEnhancedTypeForAdd) enhType = GetEnhancedTypeForAdd(); - newEnh = exEnh.InsertEnhancedSteps(MyContent.Text, null, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedSteps(MyContent.Text, null, addtype, enhType, ItemID); } else { if (!IsProcedure || !exEnh.MyDocVersion.DocVersionConfig.Enhanced_AllowMods) - newEnh = exEnh.InsertEnhancedItems(MyContent.Text, MyContent.Number, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedItems(MyContent.Text, MyContent.Number, addtype, enhType, ItemID); else - newEnh = exEnh.InsertEnhancedItems(ptext, pnum, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedItems(ptext, pnum, addtype, enhType, ItemID); } } } @@ -1782,13 +1573,14 @@ namespace VEPROMS.CSLA.Library } // no next either, try the parent. - if (this.IsProcedure && newEnh == null) // procedure is a special case since it has to be added from the doc version: + if (IsProcedure && newEnh == null) // procedure is a special case since it has to be added from the doc version: { - // need to make a new procedure off working draft of enhanced set: - DocVersionConfig dvc = this.MyDocVersion.MyConfig as DocVersionConfig; - ProcedureInfo pi = ProcedureInfo.Get(this.ItemID); - ProcedureConfig sourcecfg = pi.ProcedureConfig; - if (dvc != null) + // need to make a new procedure off working draft of enhanced set: + ProcedureInfo pi = ProcedureInfo.Get(ItemID); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Keeping for Debugging / Side Effect + ProcedureConfig sourcecfg = pi.ProcedureConfig; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + if (MyDocVersion.MyConfig is DocVersionConfig dvc) { foreach (DVEnhancedDocument ded in dvc.MyEnhancedDocuments) { @@ -1817,7 +1609,7 @@ namespace VEPROMS.CSLA.Library } else { - ItemInfo iiPar = this.MyParent; + ItemInfo iiPar = MyParent; addtype = EAddpingPart.Child; while (iiPar != null && newEnh == null) { @@ -1831,10 +1623,10 @@ namespace VEPROMS.CSLA.Library // B2018-115: use the correct step type for the add. // if coming from a HLS, note or caution, the enhanced type should be the base hls/note/caution type (from GetEnhancedTypeForAdd) int enhType = GetEnhancedTypeForAdd(); - newEnh = exEnh.InsertEnhancedSteps(MyContent.Text, null, addtype, enhType, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedSteps(MyContent.Text, null, addtype, enhType, ItemID); } else - newEnh = exEnh.InsertEnhancedItems(MyContent.Text, MyContent.Number, addtype, MyContent.Type, edSource.Type, this.ItemID); + newEnh = exEnh.InsertEnhancedItems(MyContent.Text, MyContent.Number, addtype, MyContent.Type, ItemID); break; } } @@ -1852,7 +1644,7 @@ namespace VEPROMS.CSLA.Library } else if (IsSection) { - SectionConfig sc = new SectionConfig(SectionInfo.Get(this.ItemID)); + SectionConfig sc = new SectionConfig(SectionInfo.Get(ItemID)); sc.AddEnhancedDocument(enhtype, newEnh.ItemID); sc.Section_LnkEnh = "Y"; SaveConfig(sc.ToString()); @@ -1885,9 +1677,9 @@ namespace VEPROMS.CSLA.Library // Link the 2 items, srcII & enhii: if (IsStep) { - using (Item ii = this.Get()) + using (Item ii = Get()) { - StepConfig sc = this.MyConfig as StepConfig; + StepConfig sc = MyConfig as StepConfig; sc.AddEnhancedDocument(enhtype, enhii.ItemID); sc.SaveEnhancedDocuments(); ii.MyContent.Config = sc.ToString(); @@ -1899,7 +1691,7 @@ namespace VEPROMS.CSLA.Library StepConfig sc = enhii.MyConfig as StepConfig; if (!sc.MyEnhancedDocuments.Exists(x => x.Type == 0)) { - sc.AddEnhancedDocument(0, this.ItemID); + sc.AddEnhancedDocument(0, ItemID); sc.SaveEnhancedDocuments(); ei.MyContent.Text = DisplayText; ei.MyContent.Config = sc.ToString(); @@ -1910,9 +1702,9 @@ namespace VEPROMS.CSLA.Library } else if (IsSection) { - using (Item ii = this.Get()) + using (Item ii = Get()) { - SectionConfig sc = this.MyConfig as SectionConfig; + SectionConfig sc = MyConfig as SectionConfig; sc.AddEnhancedDocument(enhtype, enhii.ItemID); sc.SaveEnhancedDocuments(); sc.Section_LnkEnh = "Y"; @@ -1925,7 +1717,7 @@ namespace VEPROMS.CSLA.Library SectionConfig sc = enhii.MyConfig as SectionConfig; if (!sc.MyEnhancedDocuments.Exists(x => x.Type == 0)) { - sc.AddEnhancedDocument(0, this.ItemID); + sc.AddEnhancedDocument(0, ItemID); sc.SaveEnhancedDocuments(); ei.MyContent.Text = DisplayText; ei.MyContent.Config = sc.ToString(); @@ -1941,7 +1733,7 @@ namespace VEPROMS.CSLA.Library using (Item ei = Item.Get(enhii.ItemID)) { ProcedureConfig sc = enhii.MyConfig as ProcedureConfig; - sc.AddEnhancedDocument(0, this.ItemID); + sc.AddEnhancedDocument(0, ItemID); sc.SaveEnhancedDocuments(); ei.MyContent.Number = MyContent.Number; ei.MyContent.Text = DisplayText; @@ -1949,9 +1741,9 @@ namespace VEPROMS.CSLA.Library ei.Save(); enhii.RefreshConfig(); } - using (Item ii = this.Get()) + using (Item ii = Get()) { - ProcedureConfig sc = this.MyConfig as ProcedureConfig; + ProcedureConfig sc = MyConfig as ProcedureConfig; if (!sc.MyEnhancedDocuments.Exists(x => x.Type == 0)) { sc.AddEnhancedDocument(enhtype, enhii.ItemID); @@ -1982,9 +1774,11 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@Type", criteria.Type); cm.Parameters.AddWithValue("@DTS", criteria.DTS); cm.Parameters.AddWithValue("@UserID", criteria.UserID); - SqlParameter param_ContentID = new SqlParameter("@NewItemID", SqlDbType.Int); - param_ContentID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ContentID); + SqlParameter param_ContentID = new SqlParameter("@NewItemID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ContentID); cm.CommandText = "PasteItemEnhancedReplace"; cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) @@ -2027,10 +1821,12 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@ItemID", criteria.ItemID); //ABC After Before Child cm.Parameters.AddWithValue("@Type", criteria.Type); //ABC cm.Parameters.AddWithValue("@DTS", criteria.DTS); //ABC - cm.Parameters.AddWithValue("@UserID", criteria.UserID); //ABC - SqlParameter param_ContentID = new SqlParameter("@NewItemID", SqlDbType.Int); - param_ContentID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ContentID); + cm.Parameters.AddWithValue("@UserID", criteria.UserID); //ABC + SqlParameter param_ContentID = new SqlParameter("@NewItemID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ContentID); switch (criteria.AddType) { case EAddpingPart.Child: @@ -2092,10 +1888,12 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@Config", criteria.Config); //ABC cm.Parameters.AddWithValue("@Type", criteria.Type); //ABC cm.Parameters.AddWithValue("@DTS", criteria.DTS); //ABC - cm.Parameters.AddWithValue("@UserID", criteria.UserID); //ABC - SqlParameter param_ContentID = new SqlParameter("@newItemID", SqlDbType.Int); - param_ContentID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ContentID); + cm.Parameters.AddWithValue("@UserID", criteria.UserID); //ABC + SqlParameter param_ContentID = new SqlParameter("@newItemID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ContentID); switch (criteria.AddType) { case EAddpingPart.Child: @@ -2208,12 +2006,6 @@ namespace VEPROMS.CSLA.Library get { return _StartItemID; } set { _StartItemID = value; } } - //private int _CopyEndID; - //public int CopyEndID - //{ - // get { return _CopyEndID; } - // set { _CopyEndID = value; } - //} private int _ItemID; // paste relative to this itemid public int ItemID { @@ -2393,14 +2185,12 @@ namespace VEPROMS.CSLA.Library string key = itemID.ToString(); if(_CacheByPrimaryKey.ContainsKey(key)) { - ItemInfo [] items = _CacheByPrimaryKey[key].ToArray(); - ItemInfo parent = items[0].ActiveParent as ItemInfo; - //_MyTimer.ActiveProcess = "ResetParts"; - if (parent != null) - ItemInfo.ResetParts(parent.ItemID); - //Console.WriteLine("\r\n\r\n'Deleting Item {0}'\r\n{0}'Type ','ParentID','ParentUnique','ItemID','Unique'",itemID); - foreach (ItemInfo item in items) + //_MyTimer.ActiveProcess = "ResetParts"; + if (items[0].ActiveParent is ItemInfo parent) + ItemInfo.ResetParts(parent.ItemID); + //Console.WriteLine("\r\n\r\n'Deleting Item {0}'\r\n{0}'Type ','ParentID','ParentUnique','ItemID','Unique'",itemID); + foreach (ItemInfo item in items) { //_MyTimer.ActiveProcess = "IsDeleted"; item.IsDeleted = true; @@ -2441,21 +2231,15 @@ namespace VEPROMS.CSLA.Library foreach (ItemInfo itm in itemz) { //Console.WriteLine("'{0}cache ',{1},{2},{3},{4}", depth + depth, this.ItemID, this._MyItemInfoUnique, itm.ItemID, itm._MyItemInfoUnique); - //whereami = 2; itm.OnDeleted(itm); - //whereami = 4; itm.DeleteItemInfoAndChildren(depth + " "); - //whereami = 3; } } else { //Console.WriteLine("'{0}noncache',{1},{2},{3},{4}", depth + depth, this.ItemID, this._MyItemInfoUnique, item.ItemID, item._MyItemInfoUnique); - //whereami = 5; item.OnDeleted(item); - //whereami = 7; item.DeleteItemInfoAndChildren(depth + " "); - //whereami = 6; } } } @@ -2481,24 +2265,23 @@ namespace VEPROMS.CSLA.Library { if (_PreviousID != previousID) { - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value + MyPrevious?.RefreshNextItems(); // Update List for old value _PreviousID = previousID; // Update the value } _MyPrevious = null; // Reset list so that the next line gets a new list - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value + MyPrevious?.RefreshNextItems(); // Update List for new value } // C2017-031: Support for paste/replace an enhanced step internal static ItemInfo CopyPasteReplaceEnhancedItemInfoFetch(int copyStartID, ItemInfo itemInfo) { - ItemInfo tmp = null; - tmp = DataPortal.Fetch(new ItemInfo.PastingPartEnhancedCriteria(copyStartID, itemInfo.ItemID, ItemInfo.EAddpingPart.Replace, itemInfo.MyContent.Type, itemInfo.MyContent.Type, DateTime.Now, Volian.Base.Library.VlnSettings.UserID)); - AddToCache(tmp); + ItemInfo tmp = DataPortal.Fetch(new PastingPartEnhancedCriteria(copyStartID, itemInfo.ItemID, EAddpingPart.Replace, itemInfo.MyContent.Type, itemInfo.MyContent.Type, DateTime.Now, Volian.Base.Library.VlnSettings.UserID)); + AddToCache(tmp); return tmp; } internal static ItemInfo CopyPasteReplaceItemInfoFetch(int copyStartID, ItemInfo itemInfo) // int itemID, int? type, int? fromType) { - ItemInfo tmp = null; - if (itemInfo.GetType() == typeof(ProcedureInfo) || itemInfo.MyContent.Type < 10000) + ItemInfo tmp; + if (itemInfo.GetType() == typeof(ProcedureInfo) || itemInfo.MyContent.Type < 10000) tmp = DataPortal.Fetch(new ItemInfo.PastingPartCriteria(copyStartID, itemInfo.ItemID, ItemInfo.EAddpingPart.Replace, itemInfo.MyContent.Type, itemInfo.MyContent.Type, DateTime.Now, Volian.Base.Library.VlnSettings.UserID)); else if (itemInfo.GetType() == typeof(SectionInfo) || itemInfo.MyContent.Type < 20000) tmp = DataPortal.Fetch(new ItemInfo.PastingPartCriteria(copyStartID, itemInfo.ItemID, ItemInfo.EAddpingPart.Replace, itemInfo.MyContent.Type, itemInfo.MyContent.Type, DateTime.Now, Volian.Base.Library.VlnSettings.UserID)); @@ -2515,8 +2298,6 @@ namespace VEPROMS.CSLA.Library public static void DeleteItemAndChildren(ItemInfo item) { //Volian.Base.Library.VlnTimer _MyTimer = new Volian.Base.Library.VlnTimer(); - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Item"); try { ItemInfo nextItem = item.NextItem; @@ -2552,8 +2333,8 @@ namespace VEPROMS.CSLA.Library ItemInfo.DeleteItemInfoAndChildren(item.ItemID); // Dispose ItemInfo and Children if (prevItem != null) prevItem.UpdateTransitionText(); - else if (nextItem != null) // B2020-050 needed check for null nextItem - found when deleting empty equation sub-step - nextItem.ResetOrdinal(); // B2020-043: Fix transition text, code moved from above, so that DeleteItemInfoAndChildren is called first. + else // B2020-050 needed check for null nextItem - found when deleting empty equation sub-step + nextItem?.ResetOrdinal(); // B2020-043: Fix transition text, code moved from above, so that DeleteItemInfoAndChildren is called first. } catch (Exception ex) @@ -2593,10 +2374,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DeleteCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - private string _UserID; + private readonly int _ItemID; + public int ItemID => _ItemID; + private string _UserID; public string UserID { get { return _UserID; } @@ -2608,7 +2388,7 @@ namespace VEPROMS.CSLA.Library _UserID = userID; } } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(DeleteCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); @@ -2648,8 +2428,6 @@ namespace VEPROMS.CSLA.Library public static ItemInfo PasteReplace(ItemInfo itemInfo, int copyStartID, string chgid, ref bool firstTrans) { firstTrans = false; - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Item"); // B2016-009 check source and destination types and display message box if needed // C2022-017 moved the CheckSourceDestinationType call to btnPasteReplace_Click in StepTabRibbon // B2023-101 Handle Paste Replace when procedure to be replaced has Incoming Transitions, i.e. do a separate try/catch for this case @@ -2790,8 +2568,7 @@ namespace VEPROMS.CSLA.Library // B2024-045, 049 and 050: if not a single procedure replace, update user interface by using the 'OnNewChild'. Single // procedure's MyParent is null because its parent is a working draft (docversion) since MyParent's type is iteminfo. // For the single procedure case, the user interface code in vlntreeview will update the tree. - if (newItemInfo.MyParent != null) - newItemInfo.MyParent.OnNewChild(new ItemInfoInsertEventArgs(newItemInfo, ItemInfo.EAddpingPart.Child)); + newItemInfo.MyParent?.OnNewChild(new ItemInfoInsertEventArgs(newItemInfo, ItemInfo.EAddpingPart.Child)); } return newItemInfo; } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs index b56bc15a..7b831c1a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/MultiUserExt.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; -using System.Text.RegularExpressions; using Csla; using Csla.Data; using JR.Utils.GUI.Forms; @@ -23,13 +21,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] public class CanCheckOutItemCriteria { - private int _ObjectID; - public int ObjectID - { get { return _ObjectID; } } - private CheckOutType _ObjectType; - public CheckOutType ObjectType - { get { return _ObjectType; } } - public CanCheckOutItemCriteria(int objectID, CheckOutType objectType) + private readonly int _ObjectID; + public int ObjectID => _ObjectID; + private readonly CheckOutType _ObjectType; + public CheckOutType ObjectType => _ObjectType; + public CanCheckOutItemCriteria(int objectID, CheckOutType objectType) { _ObjectID = objectID; _ObjectType = objectType; @@ -37,7 +33,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(CanCheckOutItemCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -53,7 +49,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new SessionInfo(dr)); + while (dr.Read()) Add(new SessionInfo(dr)); IsReadOnly = true; } } @@ -64,7 +60,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("SessionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } #endregion @@ -72,8 +68,8 @@ namespace VEPROMS.CSLA.Library #region SessionInfo stuff public partial class SessionInfo { - private Int64 _LastContentChange; - public Int64 LastContentChange + private long _LastContentChange; + public long LastContentChange { get { return _LastContentChange; } set { _LastContentChange = value; } @@ -88,15 +84,9 @@ namespace VEPROMS.CSLA.Library } set { _LastChanged = value; } } - public string LastChangedString - { - get { return ContentInfo.FormatByteArray(_LastChanged); } - } - public Int64 LastChangedInt64 - { - get { return Convert.ToInt64(LastChangedString, 16); } - } - public static SessionInfo BeginSession(string machineName, int processID) + public string LastChangedString => ContentInfo.FormatByteArray(_LastChanged); + public long LastChangedInt64 => Convert.ToInt64(LastChangedString, 16); + public static SessionInfo BeginSession(string machineName, int processID) { try { @@ -113,14 +103,14 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on SessionInfo.BeginSession", ex); } } - private Dictionary _ChangedContents; - public Dictionary ChangedContents + private Dictionary _ChangedContents; + public Dictionary ChangedContents { get { return _ChangedContents; } set { _ChangedContents = value; } } - private Dictionary _ChangedItems; - public Dictionary ChangedItems + private Dictionary _ChangedItems; + public Dictionary ChangedItems { get { return _ChangedItems; } set { _ChangedItems = value; } @@ -131,10 +121,10 @@ namespace VEPROMS.CSLA.Library try { List myList = new List(); - SessionPing.Execute(this.SessionID); - ChangedContents = SessionChangedContents.Execute(this.LastContentChange); - ChangedItems = SessionChangedItems.Execute(this.LastContentChange); - OwnerInfoList oil = OwnerInfoList.GetBySessionID(this.SessionID); + SessionPing.Execute(SessionID); + ChangedContents = SessionChangedContents.Execute(LastContentChange); + ChangedItems = SessionChangedItems.Execute(LastContentChange); + OwnerInfoList oil = OwnerInfoList.GetBySessionID(SessionID); foreach (OwnerInfo oi in oil) myList.Add(oi.OwnerID); return myList; @@ -144,11 +134,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public void EndSession() - { - SessionEnd.Execute(this.SessionID); - } - public bool CanCheckOutItem(int objectID, CheckOutType objectType, ref string message) + public void EndSession() => SessionEnd.Execute(SessionID); + public bool CanCheckOutItem(int objectID, CheckOutType objectType, ref string message) { try { @@ -178,7 +165,7 @@ namespace VEPROMS.CSLA.Library // C2015-022 part of separate windows logic, check the processID instead of the sessionID foreach (SessionInfo si in sil) { - if (si.ProcessID != this.ProcessID && objectType == CheckOutType.Procedure) + if (si.ProcessID != ProcessID && objectType == CheckOutType.Procedure) { //B2024-074 If no Number for Procedure, Display Title ProcedureInfo tmpproc = ItemInfo.Get(objectID).MyProcedure; @@ -189,12 +176,12 @@ namespace VEPROMS.CSLA.Library message = string.Format("The procedure {0} is already checked out to {1}.\r\nWould You like to open the procedure in View Only Mode?", name, si.UserID); rv = rv && false; } - else if (si.ProcessID != this.ProcessID && objectType == CheckOutType.Document) + else if (si.ProcessID != ProcessID && objectType == CheckOutType.Document) { message = string.Format("The document {0} is already checked out to {1}", ItemInfo.ConvertToDisplayText(DocumentInfo.Get(objectID).DocumentEntries[0].MyContent.Text), si.UserID); rv = rv && false; } - else if (si.ProcessID != this.ProcessID && objectType == CheckOutType.DocVersion) + else if (si.ProcessID != ProcessID && objectType == CheckOutType.DocVersion) { // gets here if other session has working draft open & click on sam working draft. OwnerInfo oi = OwnerInfo.GetBySessionIDandVersionID(si.SessionID, objectID); @@ -213,10 +200,10 @@ namespace VEPROMS.CSLA.Library else if (oi.OwnerType == 1) message = message + string.Format("The document {0} is already checked out to {1}", ItemInfo.ConvertToDisplayText(DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text), si.UserID) + Environment.NewLine; else if (oi.OwnerType == 2) - message = message + string.Format("The working draft is already checked out to {0}", si.UserID); + message += string.Format("The working draft is already checked out to {0}", si.UserID); rv = rv && false; } - else if (si.ProcessID != this.ProcessID && objectType == CheckOutType.Folder) + else if (si.ProcessID != ProcessID && objectType == CheckOutType.Folder) { // gets here if other session has working draft open & click on folder above. Gets here // if other session has wd open and click on top folder - query returns empty. @@ -236,9 +223,9 @@ namespace VEPROMS.CSLA.Library else if (oi.OwnerType == 1) message = message + string.Format("The document {0} is already checked out to {1}", ItemInfo.ConvertToDisplayText(DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text), si.UserID) + Environment.NewLine; else if (oi.OwnerType == 2) - message = message + string.Format("The working draft is already checked out to {0}", si.UserID); + message += string.Format("The working draft is already checked out to {0}", si.UserID); else if (oi.OwnerType == 3) - message = message + string.Format("The folder is already checked out to {0}", si.UserID); + message += string.Format("The folder is already checked out to {0}", si.UserID); rv = rv && false; } } @@ -251,16 +238,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on SessionInfo.Get", ex); } } - public int CheckOutItem(int itemID, CheckOutType itemType) - { - int ownerID = SessionCheckOutItem.Execute(this.SessionID, itemID, itemType); - return ownerID; - } - public void CheckInItem(int ownerID) - { - SessionCheckInItem.Execute(ownerID); - } - private void DataPortal_Fetch(BeginSessionCriteria criteria) + public int CheckOutItem(int itemID, CheckOutType itemType) => SessionCheckOutItem.Execute(SessionID, itemID, itemType); + public void CheckInItem(int ownerID) => SessionCheckInItem.Execute(ownerID); + private void DataPortal_Fetch(BeginSessionCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfo.DataPortal_Fetch", GetHashCode()); try @@ -298,78 +278,22 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("SessionInfo.DataPortal_Fetch", ex); } } - //private void DataPortal_Fetch(CanCheckOutItemCriteria criteria) - //{ - // if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfo.DataPortal_Fetch", GetHashCode()); - // try - // { - // using (SqlConnection cn = Database.VEPROMS_SqlConnection) - // { - // ApplicationContext.LocalContext["cn"] = cn; - // using (SqlCommand cm = cn.CreateCommand()) - // { - // cm.CommandType = CommandType.StoredProcedure; - // cm.CommandText = "vesp_SessionCanCheckOutItem"; - // cm.Parameters.AddWithValue("@ObjectID", criteria.ObjectID); - // cm.Parameters.AddWithValue("@ObjectType", criteria.ObjectType); - // using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) - // { - // while(dr.Read()) - - // if (!dr.Read()) - // { - // _ErrorMessage = "No Record Found"; - // return; - // } - // ReadData(dr); - // } - // } - // // removing of item only needed for local data portal - // if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) - // ApplicationContext.LocalContext.Remove("cn"); - // } - // } - // catch (Exception ex) - // { - // if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfo.DataPortal_Fetch", ex); - // _ErrorMessage = ex.Message; - // throw new DbCslaException("SessionInfo.DataPortal_Fetch", ex); - // } - //} [Serializable()] protected class BeginSessionCriteria { - private string _UserID; - public string UserID - { get { return _UserID; } } - private string _MachineName; - public string MachineName - { get { return _MachineName; } } - private int _ProcessID; - public int ProcessID - { get { return _ProcessID; } } - public BeginSessionCriteria(string userID, string machineName, int processID) + private readonly string _UserID; + public string UserID => _UserID; + private readonly string _MachineName; + public string MachineName => _MachineName; + private readonly int _ProcessID; + public int ProcessID => _ProcessID; + public BeginSessionCriteria(string userID, string machineName, int processID) { _UserID = userID; _MachineName = machineName; _ProcessID = processID; } } - //[Serializable()] - //protected class CanCheckOutItemCriteria - //{ - // private int _ObjectID; - // public int ObjectID - // { get { return _ObjectID; } } - // private CheckOutType _ObjectType; - // public CheckOutType ObjectType - // { get { return _ObjectType; } } - // public CanCheckOutItemCriteria(int objectID, CheckOutType objectType) - // { - // _ObjectID = objectID; - // _ObjectType = objectType; - // } - //} } public class TurnChangeManagerOff : CommandBase { @@ -473,20 +397,18 @@ namespace VEPROMS.CSLA.Library public class SessionPing : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private int _SessionID; - public int SessionID - { - get { return _SessionID; } - set { _SessionID = value; } - } - #region Factory Methods - public static void Execute(int sessionID) + + public int SessionID { get; set; } + #region Factory Methods + public static void Execute(int sessionID) { try { - SessionPing cmd = new SessionPing(); - cmd.SessionID = sessionID; - DataPortal.Execute(cmd); + SessionPing cmd = new SessionPing + { + SessionID = sessionID + }; + DataPortal.Execute(cmd); } catch (Exception ex) { @@ -521,18 +443,16 @@ namespace VEPROMS.CSLA.Library public class SessionEnd : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private int _SessionID; - public int SessionID + + public int SessionID { get; set; } + #region Factory Methods + public static void Execute(int sessionID) { - get { return _SessionID; } - set { _SessionID = value; } - } - #region Factory Methods - public static void Execute(int sessionID) - { - SessionEnd cmd = new SessionEnd(); - cmd.SessionID = sessionID; - DataPortal.Execute(cmd); + SessionEnd cmd = new SessionEnd + { + SessionID = sessionID + }; + DataPortal.Execute(cmd); } #endregion #region Server-Side code @@ -562,38 +482,21 @@ namespace VEPROMS.CSLA.Library public class SessionCheckOutItem : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private int _SessionID; - public int SessionID + + public int SessionID { get; set; } + public int ItemID { get; set; } + public int ItemType { get; set; } + public int OwnerID { get; set; } + #region Factory Methods + public static int Execute(int sessionID, int itemID, CheckOutType itemType) { - get { return _SessionID; } - set { _SessionID = value; } - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - private int _ItemType; - public int ItemType - { - get { return _ItemType; } - set { _ItemType = value; } - } - private int _OwnerID; - public int OwnerID - { - get { return _OwnerID; } - set { _OwnerID = value; } - } - #region Factory Methods - public static int Execute(int sessionID, int itemID, CheckOutType itemType) - { - SessionCheckOutItem cmd = new SessionCheckOutItem(); - cmd.SessionID = sessionID; - cmd.ItemID = itemID; - cmd.ItemType = (int)itemType; - cmd = DataPortal.Execute(cmd); + SessionCheckOutItem cmd = new SessionCheckOutItem + { + SessionID = sessionID, + ItemID = itemID, + ItemType = (int)itemType + }; + cmd = DataPortal.Execute(cmd); return cmd.OwnerID; } #endregion @@ -629,19 +532,16 @@ namespace VEPROMS.CSLA.Library public class SessionCheckInItem : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private int _OwnerID; - public int OwnerID + + public int OwnerID { get; set; } + #region Factory Methods + public static void Execute(int ownerID) { - get { return _OwnerID; } - set { _OwnerID = value; } - } - private int _ItemID; - #region Factory Methods - public static void Execute(int ownerID) - { - SessionCheckInItem cmd = new SessionCheckInItem(); - cmd.OwnerID = ownerID; - DataPortal.Execute(cmd); + SessionCheckInItem cmd = new SessionCheckInItem + { + OwnerID = ownerID + }; + DataPortal.Execute(cmd); } #endregion #region Server-Side code @@ -671,24 +571,17 @@ namespace VEPROMS.CSLA.Library public class SessionChangedContents : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private Int64 _LastContentChange; - public Int64 LastContentChange + + public long LastContentChange { get; set; } + public Dictionary ChangedContents { get; set; } + #region Factory Methods + public static Dictionary Execute(long lastContentChanged) { - get { return _LastContentChange; } - set { _LastContentChange = value; } - } - private Dictionary _ChangedContents; - public Dictionary ChangedContents - { - get { return _ChangedContents; } - set { _ChangedContents = value; } - } - #region Factory Methods - public static Dictionary Execute(Int64 lastContentChanged) - { - SessionChangedContents cmd = new SessionChangedContents(); - cmd.LastContentChange = lastContentChanged; - cmd = DataPortal.Execute(cmd); + SessionChangedContents cmd = new SessionChangedContents + { + LastContentChange = lastContentChanged + }; + cmd = DataPortal.Execute(cmd); return cmd.ChangedContents; } #endregion @@ -706,9 +599,9 @@ namespace VEPROMS.CSLA.Library cmd.Parameters.AddWithValue("@LastChanged", LastContentChange); cmd.Parameters.AddWithValue("@UserID", Volian.Base.Library.VlnSettings.UserID); SqlDataReader dr = cmd.ExecuteReader(); - ChangedContents = new Dictionary(); + ChangedContents = new Dictionary(); while (dr.Read()) - ChangedContents.Add(dr.GetInt32(0), (Int64)dr.GetSqlInt64(1)); + ChangedContents.Add(dr.GetInt32(0), (long)dr.GetSqlInt64(1)); } } } @@ -723,24 +616,17 @@ namespace VEPROMS.CSLA.Library public class SessionChangedItems : CommandBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private Int64 _LastContentChange; - public Int64 LastContentChange + + public long LastContentChange { get; set; } + public Dictionary ChangedItems { get; set; } + #region Factory Methods + public static Dictionary Execute(long lastContentChanged) { - get { return _LastContentChange; } - set { _LastContentChange = value; } - } - private Dictionary _ChangedItems; - public Dictionary ChangedItems - { - get { return _ChangedItems; } - set { _ChangedItems = value; } - } - #region Factory Methods - public static Dictionary Execute(Int64 lastContentChanged) - { - SessionChangedItems cmd = new SessionChangedItems(); - cmd.LastContentChange = lastContentChanged; - cmd = DataPortal.Execute(cmd); + SessionChangedItems cmd = new SessionChangedItems + { + LastContentChange = lastContentChanged + }; + cmd = DataPortal.Execute(cmd); return cmd.ChangedItems; } #endregion @@ -758,9 +644,9 @@ namespace VEPROMS.CSLA.Library cmd.Parameters.AddWithValue("@LastChanged", LastContentChange); cmd.Parameters.AddWithValue("@UserID", Volian.Base.Library.VlnSettings.UserID); SqlDataReader dr = cmd.ExecuteReader(); - ChangedItems = new Dictionary(); + ChangedItems = new Dictionary(); while (dr.Read()) - ChangedItems.Add(dr.GetInt32(0), (Int64)dr.GetSqlInt64(1)); + ChangedItems.Add(dr.GetInt32(0), (long)dr.GetSqlInt64(1)); } } } @@ -777,24 +663,17 @@ namespace VEPROMS.CSLA.Library #region OwnerInfo stuff public partial class OwnerInfoList { - public static OwnerInfoList GetBySessionID(int sessionID) - { - OwnerInfoList tmp = DataPortal.Fetch(new GetBySessionIDCriteria(sessionID)); - return tmp; - } - [Serializable()] + public static OwnerInfoList GetBySessionID(int sessionID) => DataPortal.Fetch(new GetBySessionIDCriteria(sessionID)); + [Serializable()] protected class GetBySessionIDCriteria { - private int _SessionID; - public int SessionID { get { return _SessionID; } } - public GetBySessionIDCriteria(int sessionID) - { - _SessionID = sessionID; - } - } + private readonly int _SessionID; + public int SessionID => _SessionID; + public GetBySessionIDCriteria(int sessionID) => _SessionID = sessionID; + } private void DataPortal_Fetch(GetBySessionIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -809,7 +688,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new OwnerInfo(dr)); + while (dr.Read()) Add(new OwnerInfo(dr)); IsReadOnly = true; } } @@ -820,7 +699,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfoList.DataPortal_Fetch", ex); throw new DbCslaException("OwnerInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } public static OwnerInfoList GetByVersionID(int versionID) { @@ -839,16 +718,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class GetByVersionIDCriteria { - private int _VersionID; - public int VersionID { get { return _VersionID; } } - public GetByVersionIDCriteria(int versionID) - { - _VersionID = versionID; - } + private readonly int _VersionID; + public int VersionID => _VersionID; + public GetByVersionIDCriteria(int versionID) => _VersionID = versionID; } private void DataPortal_Fetch(GetByVersionIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] OwnerInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -863,7 +739,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new OwnerInfo(dr)); + while (dr.Read()) Add(new OwnerInfo(dr)); IsReadOnly = true; } } @@ -874,7 +750,7 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("OwnerInfoList.DataPortal_Fetch", ex); throw new DbCslaException("OwnerInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } public partial class OwnerInfo @@ -899,13 +775,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class GetBySessionIDandFolderIDCriteria { - private int _SessionID; - public int SessionID - { get { return _SessionID; } } - private int _FolderID; - public int FolderID - { get { return _FolderID; } } - public GetBySessionIDandFolderIDCriteria(int sessionID, int folderID) + private readonly int _SessionID; + public int SessionID => _SessionID; + private readonly int _FolderID; + public int FolderID => _FolderID; + public GetBySessionIDandFolderIDCriteria(int sessionID, int folderID) { _SessionID = sessionID; _FolderID = folderID; @@ -968,13 +842,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class GetBySessionIDandVersionIDCriteria { - private int _SessionID; - public int SessionID - { get { return _SessionID; } } - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - public GetBySessionIDandVersionIDCriteria(int sessionID, int versionID) + private readonly int _SessionID; + public int SessionID => _SessionID; + private readonly int _VersionID; + public int VersionID => _VersionID; + public GetBySessionIDandVersionIDCriteria(int sessionID, int versionID) { _SessionID = sessionID; _VersionID = versionID; @@ -1037,13 +909,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class GetByItemIDCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - private CheckOutType _ItemType; - public CheckOutType ItemType - { get { return _ItemType; } } - public GetByItemIDCriteria(int itemID, CheckOutType itemType) + private readonly int _ItemID; + public int ItemID => _ItemID; + private readonly CheckOutType _ItemType; + public CheckOutType ItemType => _ItemType; + public GetByItemIDCriteria(int itemID, CheckOutType itemType) { _ItemID = itemID; _ItemType = itemType; @@ -1090,7 +960,7 @@ namespace VEPROMS.CSLA.Library { get { - SessionInfo si = SessionInfo.Get(this.SessionID); + SessionInfo si = SessionInfo.Get(SessionID); return si.UserID; } } @@ -1101,32 +971,20 @@ namespace VEPROMS.CSLA.Library public partial class UserInfo { - public static bool CanEdit(UserInfo myUserInfo, DocVersionInfo myDVI) - { - return myUserInfo!=null && myDVI!=null && (myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsWriter(myDVI)); - } + public static bool CanEdit(UserInfo myUserInfo, DocVersionInfo myDVI) => myUserInfo != null && myDVI != null && (myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsWriter(myDVI)); - public static bool CanEditROs(UserInfo myUserInfo, DocVersionInfo myDVI) - { - return myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsROEditor(myDVI); - } + public static bool CanEditROs(UserInfo myUserInfo, DocVersionInfo myDVI) => myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI) || myUserInfo.IsROEditor(myDVI); - public static bool CanCreateFolders(UserInfo myUserInfo, DocVersionInfo myDVI) - { - return myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI); - } + public static bool CanCreateFolders(UserInfo myUserInfo, DocVersionInfo myDVI) => myUserInfo != null && myDVI != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(myDVI); - public static bool CanCreateFolders(UserInfo myUserInfo, FolderInfo fi) - { - return myUserInfo != null && fi != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(fi.MyParent); //B2020-111 allow if set amin controls parent - } + public static bool CanCreateFolders(UserInfo myUserInfo, FolderInfo fi) => myUserInfo != null && fi != null && myUserInfo.IsAdministrator() || myUserInfo.IsSetAdministrator(fi.MyParent); //B2020-111 allow if set amin controls parent - public bool IsAdministrator() + public bool IsAdministrator() { - if (this.UserMembershipCount == 0) + if (UserMembershipCount == 0) return false; - foreach (MembershipInfo mi in this.UserMemberships) + foreach (MembershipInfo mi in UserMemberships) { if (mi.EndDate == string.Empty && mi.MyGroup.GroupAssignments != null) //B2024-051 added null check - user assigned to non-existing procedure set { @@ -1145,10 +1003,10 @@ namespace VEPROMS.CSLA.Library // would then be skipped (from where is called) public bool IsSetAdministrator(FolderInfo fldinf) { - if (this.UserMembershipCount == 0 || fldinf == null) + if (UserMembershipCount == 0 || fldinf == null) return false; - foreach (MembershipInfo mi in this.UserMemberships) + foreach (MembershipInfo mi in UserMemberships) { if (mi.EndDate == string.Empty && mi.MyGroup.GroupAssignments != null) //B2024-051 added null check - user assigned to non-existing procedure set { @@ -1173,10 +1031,10 @@ namespace VEPROMS.CSLA.Library public bool IsSetAdministrator(DocVersionInfo dv) { - if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo + if (UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; - foreach (MembershipInfo mi in this.UserMemberships) + foreach (MembershipInfo mi in UserMemberships) { if (mi.EndDate == string.Empty && mi.MyGroup.GroupAssignments != null) //B2024-051 added null check - user assigned to non-existing procedure set { @@ -1200,10 +1058,10 @@ namespace VEPROMS.CSLA.Library public bool IsWriter(DocVersionInfo dv) { - if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo + if (UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; - foreach (MembershipInfo mi in this.UserMemberships) + foreach (MembershipInfo mi in UserMemberships) { if (mi.EndDate == string.Empty && mi.MyGroup.GroupAssignments != null) //B2024-051 added null check - user assigned to non-existing procedure set { @@ -1227,10 +1085,10 @@ namespace VEPROMS.CSLA.Library public bool IsReviewer(DocVersionInfo dv) { - if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo + if (UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; - foreach (MembershipInfo mi in this.UserMemberships) + foreach (MembershipInfo mi in UserMemberships) { if (mi.EndDate == string.Empty && mi.MyGroup.GroupAssignments != null) //B2024-051 added null check - user assigned to non-existing procedure set { @@ -1254,10 +1112,10 @@ namespace VEPROMS.CSLA.Library public bool IsROEditor(DocVersionInfo dv) { - if (this.UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo + if (UserMembershipCount == 0 || dv == null) // B2022-026 RO Memory reduction - check for null DocVersionInfo return false; - foreach (MembershipInfo mi in this.UserMemberships) + foreach (MembershipInfo mi in UserMemberships) { if (mi.EndDate == string.Empty && mi.MyGroup.GroupAssignments != null) //B2024-051 added null check - user assigned to non-existing procedure set { @@ -1279,12 +1137,9 @@ namespace VEPROMS.CSLA.Library return false; } - // B2018-112 added for easy check if user's PROMS Security allows making edits - used in StepTabRibbon - SetButtonAndMenuEnabling() - public bool IsAllowedToEdit(DocVersionInfo dvi) - { - return IsAdministrator() || IsSetAdministrator(dvi) || IsWriter(dvi); - } - public static UserInfo GetByUserID(string userID) + // B2018-112 added for easy check if user's PROMS Security allows making edits - used in StepTabRibbon - SetButtonAndMenuEnabling() + public bool IsAllowedToEdit(DocVersionInfo dvi) => IsAdministrator() || IsSetAdministrator(dvi) || IsWriter(dvi); + public static UserInfo GetByUserID(string userID) { try { @@ -1305,14 +1160,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class GetByUserIDCriteria { - private string _UserID; - public string UserID - { get { return _UserID; } } - public GetByUserIDCriteria(string userID) - { - _UserID = userID; - } - } + private readonly string _UserID; + public string UserID => _UserID; + public GetByUserIDCriteria(string userID) => _UserID = userID; + } private void DataPortal_Fetch(GetByUserIDCriteria criteria) { diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/OutlineRTFTable.cs b/PROMS/VEPROMS.CSLA.Library/Extension/OutlineRTFTable.cs index b2752318..24f0f0eb 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/OutlineRTFTable.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/OutlineRTFTable.cs @@ -12,19 +12,10 @@ namespace VEPROMS.CSLA.Library Rtf = rtf; WithBorder = withBorder; } - private string _Rtf; - public string Rtf - { - get { return _Rtf; } - set { _Rtf = value; } - } - private bool _WithBorder; - public bool WithBorder - { - get { return _WithBorder; } - set { _WithBorder = value; } - } - private RtfLines _Lines; + + public string Rtf { get; set; } + public bool WithBorder { get; set; } + private RtfLines _Lines; public RtfLines Lines { get @@ -43,11 +34,8 @@ namespace VEPROMS.CSLA.Library Lines.Add(new RtfLine(maxWidth, WithBorder ? @"\u9492?" : " ", WithBorder ? @"\u9472?" : " ", WithBorder ? @"\u9496?" : " ")); // Insert bottom line Lines.ReplaceLines(WithBorder); } - public override string ToString() - { - return Lines.ToString(); - } - } + public override string ToString() => Lines.ToString(); + } public class RtfLines : List { public static Regex _RegReplaceLine = new Regex(@"\\line((\\[^ \[\]\\\(\)]*) )"); @@ -58,7 +46,6 @@ namespace VEPROMS.CSLA.Library // split text into lines string[] breaks = { "\r\n" }; string[] lines = txt.Split(breaks, StringSplitOptions.None); - //string lastLine = lines[lines.Length - 1]; foreach (string line in lines) Add(new RtfLine(line.Replace("\\bullet","*"))); } @@ -89,19 +76,19 @@ namespace VEPROMS.CSLA.Library } return sb.ToString(); } - private static Regex _RegRightCheck = new Regex(@"-|\\u9472?|\\u8209\?"); - private static Regex _RegAboveCheck = new Regex(@"\||\\u9474\?|\\u9492\?|\\u9516\?|\\u9532\?|\\u9500\?|\\u9484\?|\\u9524\?|\\u9488\?|\\u9508\?"); - private static Regex _RegLeftCheck = new Regex(@"-|\\u9472\?|\\u9508\?|\\u9516\?|\\u9500\?|\\u9532\?|\\u9484\?|\\u9488\?|\\u9492\?|\\u8209\?"); - private static Regex _RegBelowCheck = new Regex(@"\||\\u9474\?"); + private static readonly Regex _RegRightCheck = new Regex(@"-|\\u9472?|\\u8209\?"); + private static readonly Regex _RegAboveCheck = new Regex(@"\||\\u9474\?|\\u9492\?|\\u9516\?|\\u9532\?|\\u9500\?|\\u9484\?|\\u9524\?|\\u9488\?|\\u9508\?"); + private static readonly Regex _RegLeftCheck = new Regex(@"-|\\u9472\?|\\u9508\?|\\u9516\?|\\u9500\?|\\u9532\?|\\u9484\?|\\u9488\?|\\u9492\?|\\u8209\?"); + private static readonly Regex _RegBelowCheck = new Regex(@"\||\\u9474\?"); - private static Regex _RegRightCheck1 = new Regex(@"\\u9474\?"); - private static Regex _RegAboveCheck1 = new Regex(@"\\u9472\?|\\u8209\?"); - private static Regex _RegLeftCheck1 = new Regex(@"\\u9474\?"); - private static Regex _RegBelowCheck1 = new Regex(@"\\u9472\?|\\u8209\?"); + private static readonly Regex _RegRightCheck1 = new Regex(@"\\u9474\?"); + private static readonly Regex _RegAboveCheck1 = new Regex(@"\\u9472\?|\\u8209\?"); + private static readonly Regex _RegLeftCheck1 = new Regex(@"\\u9474\?"); + private static readonly Regex _RegBelowCheck1 = new Regex(@"\\u9472\?|\\u8209\?"); - private static Regex _RegHorizontalCheck = new Regex(@"-|\\u9472\?|\\u8209\?"); - private static Regex _RegVerticalCheck = new Regex(@"\||\\u9474\?"); - static private string[] TableCharsU = { + private static readonly Regex _RegHorizontalCheck = new Regex(@"-|\\u9472\?|\\u8209\?"); + private static readonly Regex _RegVerticalCheck = new Regex(@"\||\\u9474\?"); + 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' @@ -159,24 +146,10 @@ namespace VEPROMS.CSLA.Library } } } - private void ListItems(string loc, string str) - { - StringBuilder sb = new StringBuilder(string.Format("{0} = @\"", loc)); - string sep = ""; - foreach (char c in str) - { - if (c < 127) - sb.Append(sep + c.ToString()); - else - sb.Append(sep + string.Format("\\u{0}?", (int)c)); - sep = "|"; - } - Console.WriteLine(sb.ToString()); - } } public class RtfLine : List { - private static Regex _RegRtfText = new Regex(@"((\\[^'u ]*|\\up[0-9]|\\ul|\\ulnone)+( |$|(?=\\['u])))?(|\\'[0-9a-fA-F]{2}|\\u[0-9]*\?|[^\\]{1}|$|)"); + private static readonly Regex _RegRtfText = new Regex(@"((\\[^'u ]*|\\up[0-9]|\\ul|\\ulnone)+( |$|(?=\\['u])))?(|\\'[0-9a-fA-F]{2}|\\u[0-9]*\?|[^\\]{1}|$|)"); public RtfLine(string text) { MatchCollection matches = _RegRtfText.Matches(text); @@ -192,15 +165,13 @@ namespace VEPROMS.CSLA.Library nextIndex = match.Index + match.Length; string rtfPart = match.Groups[1].ToString(); if (match.Groups[1].ToString().TrimEnd(" ".ToCharArray()).Length + match.Groups[4].ToString().Length > 0) - this.Add(new RtfPiece(match.Groups[1].ToString().TrimEnd(" ".ToCharArray()), match.Groups[4].ToString())); - //if (match.Groups[1].ToString().Length + match.Groups[4].ToString().Length > 0) - // this.Add(new RtfPiece(match.Groups[1].ToString(), match.Groups[4].ToString())); + Add(new RtfPiece(match.Groups[1].ToString().TrimEnd(" ".ToCharArray()), match.Groups[4].ToString())); } } public RtfLine(int width, string left, string fill, string right) { Add(new RtfPiece("", left)); - for (int i = 0; i < width; i++) this.Add(new RtfPiece("", fill)); // Pad + for (int i = 0; i < width; i++) Add(new RtfPiece("", fill)); // Pad Add(new RtfPiece("", right)); } public int MaximumWidth @@ -223,9 +194,9 @@ namespace VEPROMS.CSLA.Library internal void Pad(int maxWidth, string edge) { int pad = maxWidth - MaximumWidth; - this.Insert(0, new RtfPiece("", edge)); // Left Edge - for (int i = 0; i < pad; i++) this.Add(new RtfPiece("", " ")); // Pad - this.Add(new RtfPiece("", edge)); // Right Edge + Insert(0, new RtfPiece("", edge)); // Left Edge + for (int i = 0; i < pad; i++) Add(new RtfPiece("", " ")); // Pad + Add(new RtfPiece("", edge)); // Right Edge } public new RtfPiece this[int index] { @@ -246,61 +217,23 @@ namespace VEPROMS.CSLA.Library } public class RtfPiece { - private string _Rtf; - public string Rtf - { - get { return _Rtf; } - set { _Rtf = value; } - } - private string _Text = ""; - public string Text - { - get { return _Text; } - set { _Text = value; } - } - public int TextLength - { - get { return Text.Length; } - } - public int MaximumWidth - { - get { return Text == "" ? 0 : 1; } - } - private static Regex _RegStartLink = new Regex(@""); + public string Rtf { get; set; } + public string Text { get; set; } = ""; + public int TextLength => Text.Length; + public int MaximumWidth => Text == "" ? 0 : 1; + private static readonly Regex _RegStartLink = new Regex(@""); public RtfPiece(string rtf, string text) { - _Rtf = rtf; + Rtf = rtf; if (_RegStartLink.IsMatch(text) || _RegEndLink.IsMatch(text)) - _Rtf += (rtf == "" ? "" : " ") + text; + Rtf += (rtf == "" ? "" : " ") + text; else { - _Rtf += rtf == "" ? "" : " "; - _Text = text; + Rtf += rtf == "" ? "" : " "; + Text = text; } } - public override string ToString() - { - return _Rtf + _Text; - //string retval = _RegUnicode.Replace(_Text, new MatchEvaluator(RtfUnicodeCharacter)); - //retval = _RegHex.Replace(retval, new MatchEvaluator(RtfHexCharacter)); - //return retval; - } - //private static Regex _RegUnicode = new Regex(@"\\u([0-9ABCDEF]*)\?"); - //internal static string RtfUnicodeCharacter(Match myMatch) - //{ - // string hexStr = myMatch.Groups[1].ToString(); - // int i = int.Parse(hexStr); - // Char schar = Convert.ToChar(i); - // return schar.ToString(); - //} - //private static Regex _RegHex = new Regex(@"\\'([0-9A-Fa-f]{2})"); - //internal static string RtfHexCharacter(Match myMatch) - //{ - // string hexStr = myMatch.Groups[1].ToString(); - // int i = int.Parse(hexStr, System.Globalization.NumberStyles.HexNumber); - // Char schar = Convert.ToChar(i); - // return schar.ToString(); - //} - } + public override string ToString() => Rtf + Text; + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/PartExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/PartExt.cs index 19644a2b..331c5ea1 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/PartExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/PartExt.cs @@ -1,42 +1,27 @@ using System; -using System.Collections.Generic; -using System.Text; -using Csla; using Csla.Data; namespace VEPROMS.CSLA.Library { public partial class ContentPart { - public override string ToString() - { - return string.Format("{0} {1}", MyItem.MyContent.Number, MyItem.MyContent.Text); - } - } + public override string ToString() => string.Format("{0} {1}", MyItem.MyContent.Number, MyItem.MyContent.Text); + } public partial class ItemPart { - public override string ToString() - { - return string.Format("{0} {1}", _MyContent.Number, MyContent.Text); - } - } + public override string ToString() => string.Format("{0} {1}", _MyContent.Number, MyContent.Text); + } public partial class Part { - public override string ToString() - { - return string.Format("{0} {1}", MyItem.MyContent.Number, MyItem.MyContent.Text); - } - } + public override string ToString() => string.Format("{0} {1}", MyItem.MyContent.Number, MyItem.MyContent.Text); + } public partial class PartInfoList { - internal PartInfoList(SafeDataReader dr, ItemInfo itemInfo) - { - AddPartInfo(dr,itemInfo); - } - internal void AddPartInfo(SafeDataReader dr, ItemInfo itemInfo) + internal PartInfoList(SafeDataReader dr, ItemInfo itemInfo) => AddPartInfo(dr, itemInfo); + internal void AddPartInfo(SafeDataReader dr, ItemInfo itemInfo) { IsReadOnly = false; - this.Add(new PartInfo(dr, itemInfo)); + Add(new PartInfo(dr, itemInfo)); IsReadOnly = true; } public PartInfo Find(E_FromType fromType) @@ -124,9 +109,8 @@ namespace VEPROMS.CSLA.Library { if (_SearchDefaultSort == null) { - string partText = String.Empty; - - switch ((E_FromType)FromType) + string partText; + switch ((E_FromType)FromType) { case E_FromType.Caution: partText = ".Caution"; @@ -189,11 +173,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("PartInfo.ReadData", ex); } } - public E_FromType PartType - { get { return (E_FromType)_FromType; } } - public E_FromTypes PartTypes - { get { return (E_FromTypes)_FromType; } } - public override string ToString() + public E_FromType PartType => (E_FromType)_FromType; + public E_FromTypes PartTypes => (E_FromTypes)_FromType; + public override string ToString() { // if the parttype is table or figure, add the correct label: if (PartTypes == E_FromTypes.Tables) @@ -204,28 +186,12 @@ namespace VEPROMS.CSLA.Library } return string.Format("{0}", PartTypes); } - //public string ToString(string str, System.IFormatProvider ifp) - //{ - // return ToString(); - //} #region IVEDrillDownReadOnly public ItemInfoList _MyItems; - public ItemInfoList MyItems - { get { return (_MyItems != null ? _MyItems : _MyItems = ItemInfoList.GetList(_ItemID, _FromType)); } } - public System.Collections.IList GetChildren() - { - //return (_MyItems != null ? _MyItems : _MyItems = ItemInfoList.GetList(_ItemID, _FromType)); - return MyItems; - } - //public bool ChildrenAreLoaded - //{ - // get { return _MyItems == null; } - //} - public bool HasChildren - { - get { return this.MyContent.ContentPartCount > 0; } - } - public IVEDrillDownReadOnly ActiveParent + public ItemInfoList MyItems => _MyItems ?? (_MyItems = ItemInfoList.GetList(_ItemID, _FromType)); + public System.Collections.IList GetChildren() => MyItems; + public bool HasChildren => MyContent.ContentPartCount > 0; + public IVEDrillDownReadOnly ActiveParent { get { @@ -234,57 +200,16 @@ namespace VEPROMS.CSLA.Library return parentContent.ContentItems[0]; } } - public FormatInfo ActiveFormat - { - get { return ActiveParent.ActiveFormat; } - } - public FormatInfo LocalFormat - { - get { return null; } - } - public ConfigDynamicTypeDescriptor MyConfig - { - get { return null; } - } - public bool IsFolder - { - get - { - return false; - } - } - public bool IsDocVersion - { - get - { - return false; - } - } - public bool IsProcedure - { - get - { - return false; - } - } - public bool IsSection - { - get - { - return false; - } - } - public bool IsStep - { - get - { - return false; - } - } - //public bool HasStandardSteps() - //{ return false; } - #endregion - } + public FormatInfo ActiveFormat => ActiveParent.ActiveFormat; + public FormatInfo LocalFormat => null; + public ConfigDynamicTypeDescriptor MyConfig => null; + public bool IsFolder => false; + public bool IsDocVersion => false; + public bool IsProcedure => false; + public bool IsSection => false; + public bool IsStep => false; + #endregion + } // B2017-146 added the "Part" and "Parts" types of zero so that we have a valid node name when creating an export of a procedure with this FromType value public enum E_FromType : int diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs index cd0b2983..77ddb94f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/PdfExt.cs @@ -1,12 +1,7 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; using Csla; -using Csla.Data; -using Csla.Validation; -using System.Diagnostics; namespace VEPROMS.CSLA.Library { @@ -14,8 +9,6 @@ namespace VEPROMS.CSLA.Library { public static void DeleteAll(int docID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Pdf"); try { DataPortal.Delete(new DocIDCriteria(docID)); @@ -28,15 +21,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DocIDCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - public DocIDCriteria(int docID) - { - _DocID = docID; - } - } - [Transactional(TransactionalTypes.TransactionScope)] + private readonly int _DocID; + public int DocID => _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + } + private void DataPortal_Delete(DocIDCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Delete", GetHashCode()); @@ -66,8 +55,6 @@ namespace VEPROMS.CSLA.Library // used to remove word section PDFs to force ROs to be updated when printed or saved public static void DeleteDocVersionPDFsWithNewROs(int versionID, int origfstid, int newfstid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Pdf"); try { DeleteWithNewROs(versionID, origfstid, newfstid); @@ -111,11 +98,10 @@ namespace VEPROMS.CSLA.Library { if (sect.MyContent.MyEntry == null) return; // B2023-030 not a word section so just jump out DocStyle myDocStyle = sect.ActiveSection.MyDocStyle; - SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; - int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; + int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; - if (sc != null && sc.Section_WordMargin == "Y") + if (sect.ActiveSection.MyConfig is SectionConfig sc && sc.Section_WordMargin == "Y") { RemoveFromCachedByPrimaryKey(sect.MyContent.MyEntry.DocID, ss * 10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0); } @@ -132,23 +118,21 @@ namespace VEPROMS.CSLA.Library while (count < 2) { DocStyle myDocStyle = sect.ActiveSection.MyDocStyle; - SectionConfig sc = sect.ActiveSection.MyConfig as SectionConfig; - PdfInfo myPdf = null; + int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; - int ss = sect.MyDocVersion.DocVersionConfig.SelectedSlave; + PdfInfo myPdf; + if (sect.ActiveSection.MyConfig is SectionConfig sc && sc.Section_WordMargin == "Y") + { + myPdf = Get(sect.MyContent.MyEntry.DocID, ss * 10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0); + } + else + { + myPdf = Get(sect.MyContent.MyEntry.DocID, ss * 10 + MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, + (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth); + } - if (sc != null && sc.Section_WordMargin == "Y") - { - myPdf = Get(sect.MyContent.MyEntry.DocID, ss*10 + MSWordToPDF.DebugStatus, 0, 0, 0, 0); - } - else - { - myPdf = Get(sect.MyContent.MyEntry.DocID, ss*10 + MSWordToPDF.DebugStatus, (int)myDocStyle.Layout.TopMargin, (int)myDocStyle.Layout.PageLength, - (int)myDocStyle.Layout.LeftMargin, (int)myDocStyle.Layout.PageWidth); - } - - // override forces the printing of the word section, which creates a word file with resolved ROs, which is saved for an approved export - if (!ovrride || (ovrride && count == 1)) + // override forces the printing of the word section, which creates a word file with resolved ROs, which is saved for an approved export + if (!ovrride || (ovrride && count == 1)) { if (myPdf != null) return myPdf; if (count > 0) return null; // Could not find or create a pdf diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/PropertyDescriptors.cs b/PROMS/VEPROMS.CSLA.Library/Extension/PropertyDescriptors.cs index a4293a5c..3a70c972 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/PropertyDescriptors.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/PropertyDescriptors.cs @@ -8,13 +8,6 @@ // $History: $ // ======================================================================== -using System; -using System.Data; -using System.Data.SqlClient; -using Csla; -using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Collections; @@ -23,22 +16,16 @@ namespace VEPROMS.CSLA.Library { public partial class ChildFoldersPropertyDescriptor { - public override string DisplayName - { get { return Item.Name; } } - public override string Description - { get { return Item.Title; } } - public override string Name - { get { return Item.Name; } } - } + public override string DisplayName => Item.Name; + public override string Description => Item.Title; + public override string Name => Item.Name; + } public partial class FolderDocVersionsPropertyDescriptor { - public override string DisplayName - { get { return Item.Name; } } - public override string Description - { get { return Item.Name; } } - public override string Name - { get { return Item.Name; } } - } + public override string DisplayName => Item.Name; + public override string Description => Item.Name; + public override string Name => Item.Name; + } public class FormatList : System.ComponentModel.StringConverter { private static SortedList _MyFormatInfoList; @@ -64,19 +51,10 @@ namespace VEPROMS.CSLA.Library _MyFormatInfoList.Add("", null); } } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - return new StandardValuesCollection((ICollection)MyFormatInfoList.Values); - } - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) - { - return true; - } - public static int? ToInt(string formatName) + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection((ICollection)MyFormatInfoList.Values); + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true; + public static int? ToInt(string formatName) { if (formatName == null || formatName == string.Empty) return null; foreach (FormatInfo formatInfo in MyFormatInfoList.Values) @@ -136,31 +114,12 @@ namespace VEPROMS.CSLA.Library if (!ds.Inactive)_MyDocStyleList.Add(ds.Name,10000 + (int) ds.Index); } } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) - { - return new StandardValuesCollection((ICollection)MyDocStyleList.Keys); - } - public override bool GetStandardValuesSupported(ITypeDescriptorContext context) - { - return true; - } - public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) - { - return true; - } - public static int? ToInt(string docStyleName) - { - return MyDocStyleList[docStyleName]; - } - public static string ToString(int? sectionType) - { - if (sectionType == null) return null; - return MyDocStyleList.Keys[MyDocStyleList.IndexOfValue((int)sectionType)]; - } - public static int ToSectionType(string docStyleName) - { - return MyDocStyleList[docStyleName]; - } - } + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection((ICollection)MyDocStyleList.Keys); + public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true; + public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true; + public static int? ToInt(string docStyleName) => MyDocStyleList[docStyleName]; + public static string ToString(int? sectionType) => sectionType == null ? null : MyDocStyleList.Keys[MyDocStyleList.IndexOfValue((int)sectionType)]; + public static int ToSectionType(string docStyleName) => MyDocStyleList[docStyleName]; + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/RODbExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/RODbExt.cs index 1fdecf06..5c5c0cc3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/RODbExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/RODbExt.cs @@ -9,13 +9,6 @@ // ======================================================================== using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Text; -using System.IO; -using System.Xml.Serialization; -using System.Xml; -using System.Xml.XPath; using Csla; using Csla.Data; using System.Data.SqlClient; @@ -28,17 +21,10 @@ namespace VEPROMS.CSLA.Library #region RODb Config [NonSerialized] private RODbConfig _RODbConfig; - public RODbConfig RODbConfig - { get { return (_RODbConfig != null ? _RODbConfig : _RODbConfig = new RODbConfig(this)); } } - private void RODbConfigRefresh() - { - _RODbConfig = null; - } + public RODbConfig RODbConfig => _RODbConfig ?? (_RODbConfig = new RODbConfig(this)); #endregion public static RODbInfo GetJustRODB(int rODbID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a RODb"); try { RODbInfo tmp = GetCachedByPrimaryKey(rODbID); @@ -62,14 +48,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteriaJustRODB { - private int _RODbID; - public int RODbID - { get { return _RODbID; } } - public PKCriteriaJustRODB(int rODbID) - { - _RODbID = rODbID; - } - } + private readonly int _RODbID; + public int RODbID => _RODbID; + public PKCriteriaJustRODB(int rODbID) => _RODbID = rODbID; + } private void DataPortal_Fetch(PKCriteriaJustRODB criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODbInfo.DataPortal_Fetch", GetHashCode()); @@ -112,8 +94,6 @@ namespace VEPROMS.CSLA.Library { public static RODb GetJustRoDb(int rODbID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a RODb"); try { RODb tmp = DataPortal.Fetch(new PKCriteriaJustRoDb(rODbID)); @@ -151,15 +131,6 @@ namespace VEPROMS.CSLA.Library return; } ReadData(dr); - // Don't load child objects - //dr.NextResult(); - //_RODbROFsts = RODbROFsts.Get(dr); - // load child objects - //dr.NextResult(); - //_RODbROImages = RODbROImages.Get(dr); - // load child objects - //dr.NextResult(); - //_RODbRoUsages = RODbRoUsages.Get(dr); } } // removing of item only needed for local data portal @@ -177,18 +148,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteriaJustRoDb { - private int _RODbID; - public int RODbID - { get { return _RODbID; } } - public PKCriteriaJustRoDb(int rODbID) - { - _RODbID = rODbID; - } - } - - #region Log4Net - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion + private readonly int _RODbID; + public int RODbID => _RODbID; + public PKCriteriaJustRoDb(int rODbID) => _RODbID = rODbID; + } #region RODb Config [NonSerialized] @@ -205,10 +168,7 @@ namespace VEPROMS.CSLA.Library return _RODbConfig; } } - private void _RODbConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) - { - Config = _RODbConfig.ToString(); - } - #endregion - } + private void _RODbConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) => Config = _RODbConfig.ToString(); + #endregion + } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs index 50ff8877..a98f6d69 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ROFSTExt.cs @@ -10,12 +10,8 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; using System.Text; using System.IO; -using System.Xml.Serialization; -using System.Xml; -using System.Xml.XPath; using System.Text.RegularExpressions; using System.Data; using System.Data.SqlClient; @@ -30,9 +26,6 @@ namespace VEPROMS.CSLA.Library { public static ROFst GetJustROFst(int rOFstID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ROFst"); - try { ROFst tmp = GetCachedByPrimaryKey(rOFstID); @@ -59,14 +52,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteriaJustROFst { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - public PKCriteriaJustROFst(int rOFstID) - { - _ROFstID = rOFstID; - } - } + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + public PKCriteriaJustROFst(int rOFstID) => _ROFstID = rOFstID; + } private void DataPortal_Fetch(PKCriteriaJustROFst criteria) { @@ -111,30 +100,22 @@ namespace VEPROMS.CSLA.Library public partial class ROFstInfo { - #region Log4Net - - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - - #endregion [Serializable()] protected class PKCriteriaJustROFst { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - public PKCriteriaJustROFst(int rOFstID) - { - _ROFstID = rOFstID; - } - } + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + public PKCriteriaJustROFst(int rOFstID) => _ROFstID = rOFstID; + } #region Fields // this is used by the frmBatchRefresh which is the Adim Tools so that one message is display for a group of procedure sets processed public static StringBuilder MessageList = null; - private static List DocVersionsNeedingROUpdate = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List DocVersionsNeedingROUpdate = new List(); #endregion @@ -142,23 +123,19 @@ namespace VEPROMS.CSLA.Library public event ROFstInfoROTableUpdateEvent ROTableUpdate; - #endregion + #endregion - #region Public Methods + #region Public Methods + // B2022-107: Display Progress Bar Messages/Statuses when a new ROFST binary file is loaded into the database + public ROFSTLookup GetROFSTLookup(DocVersionInfo dvi, string ovrrideChild = null, bool showLoadingStatus = true) => new ROFSTLookup(this.ROFstID, dvi, ovrrideChild, showLoadingStatus); - public ROFSTLookup GetROFSTLookup(DocVersionInfo dvi, string ovrrideChild = null, bool showLoadingStatus = true) - { - // B2022-107: Display Progress Bar Messages/Statuses when a new ROFST binary file is loaded into the database - return new ROFSTLookup(this.ROFstID, dvi, ovrrideChild, showLoadingStatus); - } - - /// - /// Adds an ro.fst into a sql database. - /// - /// - /// ROFst: Returns the created rofst object - public static ROFst AddRoFst(RODbInfo rdi, DocVersion docver, ROFstInfoProgressBarRefresh myProgressBarRefresh) + /// + /// Adds an ro.fst into a sql database. + /// + /// + /// ROFst: Returns the created rofst object + public static ROFst AddRoFst(RODbInfo rdi, DocVersion docver, ROFstInfoProgressBarRefresh myProgressBarRefresh) { string rofstfilepath = rdi.FolderPath + @"\ro.fst"; DirectoryInfo di = new DirectoryInfo(rdi.FolderPath); @@ -218,9 +195,11 @@ namespace VEPROMS.CSLA.Library } if (myUnChangedROImages.Count > 0) - using (FigureInfoList fil = FigureInfoList.AddByROFstIDImageIDs(rofst.ROFstID, buildImageIDString(myUnChangedROImages))) ; +#pragma warning disable CS0642 // Possible mistaken empty statement - valid - keeps scope of add + using (FigureInfoList fil = FigureInfoList.AddByROFstIDImageIDs(rofst.ROFstID, buildImageIDString(myUnChangedROImages))) ; +#pragma warning restore CS0642 // Possible mistaken empty statement - return rofst; + return rofst; } } } @@ -252,8 +231,7 @@ namespace VEPROMS.CSLA.Library TimeSpan ts = DateTime.Now - start; - if (tbStatus != null) - tbStatus.AppendText(string.Format("Procedure: {1}{0}, Checked {2} Referenced Objects{0}, Fixed {3} Referenced Objects{0}, Elapsed Seconds:{4}{0}{0}", Environment.NewLine, itm.MyProcedure.DisplayNumber, ItemInfo.ROCheckCount, ItemInfo.ROFixCount, ts.TotalSeconds)); + tbStatus?.AppendText(string.Format("Procedure: {1}{0}, Checked {2} Referenced Objects{0}, Fixed {3} Referenced Objects{0}, Elapsed Seconds:{4}{0}{0}", Environment.NewLine, itm.MyProcedure.DisplayNumber, ItemInfo.ROCheckCount, ItemInfo.ROFixCount, ts.TotalSeconds)); } //Update the DocVersion Associations to link to the new RO FST id and current date/time @@ -288,8 +266,7 @@ namespace VEPROMS.CSLA.Library DocVersionInfo dvi = DocVersionInfo.Get(proc.MyDocVersion.VersionID); if (dvi.DocVersionConfig.SelectedSlave <= 0) { - int i = 0; - DateTime start = DateTime.Now; + DateTime start = DateTime.Now; ProcedureInfo.ResetCheckROLinkCounters(); ProcedureInfo.CheckReferenceObjectsLinks(proc); @@ -297,8 +274,7 @@ namespace VEPROMS.CSLA.Library TimeSpan ts = DateTime.Now - start; - if (tbStatus != null) - tbStatus.AppendText(string.Format("Procedure: {1}{0}, Checked {2} Referenced Objects Links{0}, Found {3} Bad RO Links{0} Elapsed Seconds:{5}{0}{0}", Environment.NewLine, proc.DisplayNumber, ProcedureInfo.CheckROLinksCount, ProcedureInfo.BadROLinksCount, ProcedureInfo.FixedROLinksCount, ts.TotalSeconds)); + tbStatus?.AppendText(string.Format("Procedure: {1}{0}, Checked {2} Referenced Objects Links{0}, Found {3} Bad RO Links{0} Elapsed Seconds:{5}{0}{0}", Environment.NewLine, proc.DisplayNumber, ProcedureInfo.CheckROLinksCount, ProcedureInfo.BadROLinksCount, ProcedureInfo.FixedROLinksCount, ts.TotalSeconds)); /*** keep for now - incase we decide to fix RO links later on, this will show the number of RO Links that we fixed //tbStatus.AppendText(string.Format("Procedure: {1}{0}, Checked {2} Referenced Objects Links{0}, Found {3} Bad RO Links{0}, Fixed {4} Bad RO Links{0} Elapsed Seconds:{5}{0}{0}", Environment.NewLine, proc.DisplayNumber, ProcedureInfo.CheckROLinksCount, ProcedureInfo.BadROLinksCount, ProcedureInfo.FixedROLinksCount, ts.TotalSeconds)); ***/ @@ -330,9 +306,9 @@ namespace VEPROMS.CSLA.Library { ROWorkingDraftAsk.ClearWorkingDrafts(); - if (myProgressBarRefresh != null) myProgressBarRefresh(0, 100, "Starting Update"); + myProgressBarRefresh?.Invoke(0, 100, "Starting Update"); - int origFSTid = origROFst.ROFstID; + int origFSTid = origROFst.ROFstID; DirectoryInfo di = new DirectoryInfo(rdi.FolderPath); string rofstfilepath = rdi.FolderPath + @"\ro.fst"; @@ -346,16 +322,15 @@ namespace VEPROMS.CSLA.Library if (rofst != null) { // Get a list of figures which have changed content (DTS) - List MyChangedFigureROIDs = null; if (docver.ROfstLoadingFigures) // B2017-125 see if loading figures was completed { ROFSTLookup myLookup = new ROFSTLookup(rofst.ROFstID, DocVersionInfo.Get(docver.VersionID)); - MyChangedFigureROIDs = UpdateROFigures(rdi, myProgressBarRefresh, rofst, RODb.GetJustRoDb(rdi.RODbID), myLookup, docver); + _ = UpdateROFigures(rdi, myProgressBarRefresh, rofst, RODb.GetJustRoDb(rdi.RODbID), myLookup, docver); } else { - MyChangedFigureROIDs = GetChangedFigureROIDs(origROFst, ROFstInfo.GetJustROFst(rofst.ROFstID), DocVersionInfo.Get(docver.VersionID), myProgressBarRefresh); + _ = GetChangedFigureROIDs(origROFst, ROFstInfo.GetJustROFst(rofst.ROFstID), DocVersionInfo.Get(docver.VersionID), myProgressBarRefresh); } docver.DocVersionAssociations[0].MyROFst = rofst; @@ -404,18 +379,11 @@ namespace VEPROMS.CSLA.Library return false; } - public ROFst GetJustROFst() - { - return ROFst.GetJustROFst(ROFstID); - } + public ROFst GetJustROFst() => ROFst.GetJustROFst(ROFstID); - public List OnROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) - { - if (ROTableUpdate != null) return ROTableUpdate(sender, args); - return null; - } + public List OnROTableUpdate(object sender, ROFstInfoROTableUpdateEventArgs args) => ROTableUpdate != null ? ROTableUpdate(sender, args) : null; - public static ROFstInfo GetJustROFst(int rOFstID) + public static ROFstInfo GetJustROFst(int rOFstID) { try { @@ -433,11 +401,6 @@ namespace VEPROMS.CSLA.Library tmp = null; } - if (tmp != null) - { - tmp.ClearROLookupBytes(); - } - return tmp; } catch (Exception ex) @@ -481,9 +444,11 @@ namespace VEPROMS.CSLA.Library { string cfg = docver.DocVersionAssociations[0].Config; - AssociationConfig ac = new AssociationConfig((cfg == null || cfg.Length == 0) ? "" : cfg); - ac.ROUpdate_LastCompleted = value; - docver.DocVersionAssociations[0].Config = ac.ToString(); + AssociationConfig ac = new AssociationConfig((cfg == null || cfg.Length == 0) ? "" : cfg) + { + ROUpdate_LastCompleted = value + }; + docver.DocVersionAssociations[0].Config = ac.ToString(); docver.Save(); } @@ -494,9 +459,11 @@ namespace VEPROMS.CSLA.Library if (docver.DocVersionAssociations[0]?.MyROFst != null && value != -1) { string cfg = docver.DocVersionAssociations[0].Config; - AssociationConfig ac = new AssociationConfig((cfg == null || cfg.Length == 0) ? "" : cfg); - ac.ROUpdate_PrevROFSTID = value.ToString(); - docver.DocVersionAssociations[0].Config = ac.ToString(); + AssociationConfig ac = new AssociationConfig((cfg == null || cfg.Length == 0) ? "" : cfg) + { + ROUpdate_PrevROFSTID = value.ToString() + }; + docver.DocVersionAssociations[0].Config = ac.ToString(); docver.Save(); } } @@ -506,9 +473,11 @@ namespace VEPROMS.CSLA.Library { string cfg = docver.DocVersionAssociations[0].Config; - AssociationConfig ac = new AssociationConfig((cfg == null || cfg.Length == 0) ? "" : cfg); - ac.ROUpdate_LoadingFigures = value; - docver.DocVersionAssociations[0].Config = ac.ToString(); + AssociationConfig ac = new AssociationConfig((cfg == null || cfg.Length == 0) ? "" : cfg) + { + ROUpdate_LoadingFigures = value + }; + docver.DocVersionAssociations[0].Config = ac.ToString(); docver.Save(); } @@ -539,8 +508,10 @@ namespace VEPROMS.CSLA.Library // Add references for existing RO Images to the Figure table (Figure table relates ro.fst with its images) if (myUnChangedROImages.Count > 0) - using (FigureInfoList fil = FigureInfoList.AddByROFstIDImageIDs(rofst.ROFstID, buildImageIDString(myUnChangedROImages))) ; - } +#pragma warning disable CS0642 // Possible mistaken empty statement - valid keeps scope of add + using (FigureInfoList fil = FigureInfoList.AddByROFstIDImageIDs(rofst.ROFstID, buildImageIDString(myUnChangedROImages))) ; +#pragma warning restore CS0642 // Possible mistaken empty statement + } SetAssociationROFiguresLoading(docVer, string.Empty); // B2017-125 loading RO Figures is completed @@ -662,12 +633,9 @@ namespace VEPROMS.CSLA.Library return myRoImagesList; } - private static string ROImageKey(string fileName, DateTime dts) - { - return string.Format("{0}:{1}", fileName, dts); - } + private static string ROImageKey(string fileName, DateTime dts) => string.Format("{0}:{1}", fileName, dts); - private static string buildImageIDString(List myROImageIDs) + private static string buildImageIDString(List myROImageIDs) { StringBuilder sb = new StringBuilder(); @@ -687,61 +655,6 @@ namespace VEPROMS.CSLA.Library return sb.ToString(); } - private static DateTime ShowDuration(DateTime dtLast, string message) - { - DateTime dtNext = DateTime.Now; - Console.WriteLine("{0,10:#####0.00},'{1}'", TimeSpan.FromTicks(dtNext.Ticks - dtLast.Ticks).TotalSeconds, message); - return dtNext; - } - - private static List BuildActiveROIDsForRoUsages12(string RoidList, string versions) - { - List activeRoids = new List(); - - using (RoUsageInfoList activeList = RoUsageInfoList.GetROUSagesByROIDsAndVersions(RoidList, versions)) - { - foreach (RoUsageInfo roui in activeList) - { - string roid = roui.ROID.ToUpper().Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - - return activeRoids; - } - - private static List BuildActiveROIDsForDRoUsages12(string RoidList, string versions) - { - List activeRoids = new List(); - - using (DROUsageInfoList activeList = DROUsageInfoList.GetDROUsagesByROIDsAndVersions(RoidList, versions)) - { - foreach (DROUsageInfo roui in activeList) - { - string roid = roui.ROID.Substring(0, 12); - if (!activeRoids.Contains(roid)) - activeRoids.Add(roid); - } - } - - return activeRoids; - } - - private static string GetRoidList(int dbid, List chgList) - { - StringBuilder sb = new StringBuilder(string.Format("{0}", dbid)); - string sep = ":"; - - foreach (string roid in chgList) - { - sb.Append(sep + roid); - sep = ","; - } - - return sb.ToString(); - } - // B2022-026 RO Memory Reduction code - all rochild types passed in are of type image (graphics) private void MigrateRoFstGraphics(RODbInfo rdi, ROFSTLookup.rochild[] rochild, RODb rodb, ROFst rofst, Dictionary myExistingROImages, List myUnChangedROImages, List myAddedROImages, List MyChangedFigureROIDs, ROFstInfoProgressBarRefresh myProgressBarRefresh, int cnt, ref int curCnt) { @@ -771,64 +684,65 @@ namespace VEPROMS.CSLA.Library } string imgfile = rdi.FolderPath + @"\" + fname; + if (File.Exists(imgfile)) + { + FileInfo fi = new FileInfo(imgfile); - ROImage roImg = null; + // if the roimage record exists, don't create a new one... + string key = ROImageKey(imgname, fi.LastWriteTimeUtc); - if (File.Exists(imgfile)) - { - FileInfo fi = new FileInfo(imgfile); + if (myExistingROImages.ContainsKey(key)) + { + int imageID = myExistingROImages[key]; + if (!myUnChangedROImages.Contains(imageID)) + myUnChangedROImages.Add(imageID); + } + else + { + if (!myAddedROImages.Contains(key)) + { + myProgressBarRefresh(curCnt, cnt, "Loading " + imgname); // show progress of loading images - // if the roimage record exists, don't create a new one... - string key = ROImageKey(imgname, fi.LastWriteTimeUtc); + FileStream fsIn = new FileStream(imgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + BinaryReader r = new BinaryReader(fsIn); + byte[] ab = r.ReadBytes((int)fsIn.Length); + r.Close(); + fsIn.Close(); - if (myExistingROImages.ContainsKey(key)) - { - int imageID = myExistingROImages[key]; - if (!myUnChangedROImages.Contains(imageID)) - myUnChangedROImages.Add(imageID); - } - else - { - if (!myAddedROImages.Contains(key)) - { - myProgressBarRefresh(curCnt, cnt, "Loading " + imgname); // show progress of loading images + byte[] cmp = ROImageInfo.Compress(ab); + int existingImageID = FindExisting(myExistingROImages, imgname, imgfile, cmp, ab); - FileStream fsIn = new FileStream(imgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - BinaryReader r = new BinaryReader(fsIn); - byte[] ab = r.ReadBytes((int)fsIn.Length); - r.Close(); - fsIn.Close(); + if (existingImageID != 0) + { + if (!myUnChangedROImages.Contains(existingImageID)) + { + myUnChangedROImages.Add(existingImageID); + } - byte[] cmp = ROImageInfo.Compress(ab); - int existingImageID = FindExisting(myExistingROImages, imgname, imgfile, cmp, ab); + return; + } - if (existingImageID != 0) - { - if (!myUnChangedROImages.Contains(existingImageID)) - { - myUnChangedROImages.Add(existingImageID); - } + ROImageConfig rc = new ROImageConfig + { + Image_Size = ab.Length.ToString() + }; - return; - } - ROImageConfig rc = new ROImageConfig(); - rc.Image_Size = ab.Length.ToString(); - - using (roImg = ROImage.MakeROImage(rodb, imgname, ROImageInfo.Compress(ab), rc.ToString(), fi.LastWriteTimeUtc, "Migration")) - { - using (Figure figure = Figure.GetByROFstID_ImageID(this.ROFstID, roImg.ImageID)) - { - if (figure != null) return; - Figure.MakeFigure(rofst, roImg, null).Dispose(); - myAddedROImages.Add(key); - MyChangedFigureROIDs.Add(myRO.roid); // Save the roid so that the related documents will be refeshed. (PDF will be deleted) - } - } - } - } - } - } + ROImage roImg; + using (roImg = ROImage.MakeROImage(rodb, imgname, ROImageInfo.Compress(ab), rc.ToString(), fi.LastWriteTimeUtc, "Migration")) + { + using (Figure figure = Figure.GetByROFstID_ImageID(this.ROFstID, roImg.ImageID)) + { + if (figure != null) return; + Figure.MakeFigure(rofst, roImg, null).Dispose(); + myAddedROImages.Add(key); + MyChangedFigureROIDs.Add(myRO.roid); // Save the roid so that the related documents will be refeshed. (PDF will be deleted) + } + } + } + } + } + } private int FindExisting(Dictionary myExistingROImages, string imgname, string imgfile, byte[] cmpFileContents, byte[] fileContents) { @@ -940,22 +854,12 @@ namespace VEPROMS.CSLA.Library public class ROFstInfoROTableUpdateEventArgs { - private string _ROText; - public string ROText + public string ROText { get; set; } + public string OldGridXml { get; set; } + public ROFstInfoROTableUpdateEventArgs(string rotext, string oldgridxml) { - get { return _ROText; } - set { _ROText = value; } - } - private string _OldGridXml; - public string OldGridXml - { - get { return _OldGridXml; } - set { _OldGridXml = value; } - } - public ROFstInfoROTableUpdateEventArgs(string rotext, string oldgridxml) - { - _ROText = rotext; - _OldGridXml = oldgridxml; + ROText = rotext; + OldGridXml = oldgridxml; } } @@ -1045,7 +949,6 @@ namespace VEPROMS.CSLA.Library } } - //GC.Collect(); return isDifferent; } catch (Exception ex) diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ROImageExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ROImageExt.cs index dda8780d..8bea8308 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ROImageExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ROImageExt.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; using Csla; @@ -14,63 +13,30 @@ namespace VEPROMS.CSLA.Library public delegate void ROImageInfoCompressionEvent(object sender, ROImageInfoCompressionEventArgs args); public class ROImageInfoCompressionEventArgs { - private int _Total; - public int Total + public int Total { get; set; } + public int Current { get; set; } + public string FileName { get; set; } + public ROImageCompressionEventType Type { get; set; } + public ROImageInfoCompressionEventArgs(ROImageCompressionEventType type) => Type = type; + public ROImageInfoCompressionEventArgs(int current, string fileName) { - get { return _Total; } - set { _Total = value; } - } - private int _Current; - public int Current - { - get { return _Current; } - set { _Current = value; } - } - private string _FileName; - public string FileName - { - get { return _FileName; } - set { _FileName = value; } - } - private ROImageCompressionEventType _Type; - public ROImageCompressionEventType Type - { - get { return _Type; } - set { _Type = value; } - } - public ROImageInfoCompressionEventArgs(ROImageCompressionEventType type) - { - _Type = type; - } - public ROImageInfoCompressionEventArgs(int current, string fileName) - { - _Current = current; - _FileName = fileName; - _Type = ROImageCompressionEventType.Update; + Current = current; + FileName = fileName; + Type = ROImageCompressionEventType.Update; } public ROImageInfoCompressionEventArgs(int total) { - _Type = ROImageCompressionEventType.Initialize; - _Total = total; + Type = ROImageCompressionEventType.Initialize; + Total = total; } } public enum ROImageCompressionEventType:int {Initialize, Update, Complete}; public partial class ROImageInfo { public static event ROImageInfoCompressionEvent CompressAllExistingImages; - public static void OnCompressAllExistingImages(object sender, ROImageInfoCompressionEventArgs args) + public static void OnCompressAllExistingImages(object sender, ROImageInfoCompressionEventArgs args) => CompressAllExistingImages?.Invoke(sender, args); + public static ROImageInfo GetByROFstID_FileName(int rOFstID, string fileName) { - if (CompressAllExistingImages != null) CompressAllExistingImages(sender, args); - } - // put in for debug - //public static int CacheCountPrimaryKey - //{ get { return _CacheByPrimaryKey.Count; } } - //public static int CacheCountList - //{ get { return _CacheList.Count; } } - public static ROImageInfo GetByROFstID_FileName(int rOFstID, string fileName) - { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ROImage"); try { if (fileName.EndsWith("PCX")) fileName = fileName.Replace(".PCX", ".TIF"); @@ -95,7 +61,6 @@ namespace VEPROMS.CSLA.Library } public static byte[] Compress(byte[] blob) { - int size = blob.Length; using (MemoryStream Source = new MemoryStream(blob)) { using (MemoryStream Destination = new MemoryStream()) @@ -171,9 +136,11 @@ namespace VEPROMS.CSLA.Library { string nm = ro.FileName; OnCompressAllExistingImages(null, new ROImageInfoCompressionEventArgs(pcount++, nm)); - ROImageConfig rc = new ROImageConfig(); - rc.Image_Size = ro.Content.Length.ToString(); - ro.Content = ROImageInfo.Compress(ro.Content); + ROImageConfig rc = new ROImageConfig + { + Image_Size = ro.Content.Length.ToString() + }; + ro.Content = ROImageInfo.Compress(ro.Content); ro.Config = rc.ToString(); ro.Save(); } @@ -226,14 +193,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ROFstID_FileNameCriteria { - private int _ROFstID; - - public int ROFstID - { get { return _ROFstID; } } - private string _FileName; - public string FileName - { get { return _FileName; } } - public ROFstID_FileNameCriteria(int rOFstID, string fileName) + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + private readonly string _FileName; + public string FileName => _FileName; + public ROFstID_FileNameCriteria(int rOFstID, string fileName) { _ROFstID = rOFstID; _FileName = fileName; @@ -245,7 +209,6 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region Fields private bool _IsDisposed; - //private static string _TemporaryFolder = null; #endregion #region Properties private ROImageInfo _MyROImage = null; @@ -260,19 +223,12 @@ namespace VEPROMS.CSLA.Library } } private FileInfo _MyFile = null; - public FileInfo MyFile - { - get { return _MyFile; } - } - private string _Extension = "TIF"; - public string Extension - { - get { return _Extension; } - set { _Extension = value; } - } - #endregion - #region Private Methods - private void TryDelete() + public FileInfo MyFile => _MyFile; + + public string Extension { get; set; } = "TIF"; + #endregion + #region Private Methods + private void TryDelete() { if (_MyROImage == null) return; if (_MyFile == null) return; @@ -356,15 +312,12 @@ namespace VEPROMS.CSLA.Library roImage.DTS = _MyFile.LastWriteTimeUtc; roImage.Save(); } - #endregion - #region Constructors - public ROImageFile(ROImageInfo myROImage) - { - MyROImage = myROImage; - } - #endregion - #region Destructor - ~ROImageFile() + #endregion + #region Constructors + public ROImageFile(ROImageInfo myROImage) => MyROImage = myROImage; + #endregion + #region Destructor + ~ROImageFile() { Dispose(false); } @@ -374,7 +327,8 @@ namespace VEPROMS.CSLA.Library GC.SuppressFinalize(this); } - protected void Dispose(bool disposing) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping disposing to match different signature")] + protected void Dispose(bool disposing) { if (!_IsDisposed) { @@ -402,17 +356,10 @@ namespace VEPROMS.CSLA.Library } private class RODbIDNoDataCriteria { - public RODbIDNoDataCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; - public int RODbID - { - get { return _RODbID; } - set { _RODbID = value; } - } - } + public RODbIDNoDataCriteria(int rODbID) => RODbID = rODbID; + + public int RODbID { get; set; } + } private void DataPortal_Fetch(RODbIDNoDataCriteria criteria) { this.RaiseListChangedEvents = false; @@ -448,7 +395,6 @@ namespace VEPROMS.CSLA.Library try { ROImageInfoList tmp = DataPortal.Fetch(new RODbIDFilenameCriteria(rODbID,filename)); - //ROImageInfo.AddList(tmp); tmp.AddEvents(); return tmp; } @@ -461,22 +407,13 @@ namespace VEPROMS.CSLA.Library { public RODbIDFilenameCriteria(int rODbID,string filename) { - _RODbID = rODbID; - _Filename = filename; + RODbID = rODbID; + Filename = filename; } - private int _RODbID; - public int RODbID - { - get { return _RODbID; } - set { _RODbID = value; } - } - private string _Filename; - public string Filename - { - get { return _Filename; } - set { _Filename = value; } - } - } + + public int RODbID { get; set; } + public string Filename { get; set; } + } private void DataPortal_Fetch(RODbIDFilenameCriteria criteria) { this.RaiseListChangedEvents = false; diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/ROUsagesExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/ROUsagesExt.cs index 2994613f..916a1886 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/ROUsagesExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/ROUsagesExt.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Data; using System.Data.SqlClient; using Csla; @@ -118,11 +116,8 @@ namespace VEPROMS.CSLA.Library [Serializable] private class GetROUsagesByROIDsCriteria { - public GetROUsagesByROIDsCriteria(string roids) - { - _ROIDS = roids; - } - private string _ROIDS; + public GetROUsagesByROIDsCriteria(string roids) => _ROIDS = roids; + private string _ROIDS; public string ROIDS { get { return _ROIDS; } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/RevisionInfoExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/RevisionInfoExt.cs index 50b3b2d7..d8505017 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/RevisionInfoExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/RevisionInfoExt.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Text; using Csla; using Csla.Data; -using Csla.Validation; using System.Data.SqlClient; using System.Data; using Volian.Base.Library; @@ -143,35 +142,20 @@ namespace VEPROMS.CSLA.Library public delegate void ItemInfoListCCEvent(object sender, ItemInfoListCCEventArgs args); public class ItemInfoListCCEventArgs : EventArgs { - private ProcedureInfo _MyProcedure; + public ProcedureInfo MyProcedure { get; set; } - public ProcedureInfo MyProcedure + public int MyCount { get; set; } + public ItemInfoListCCEventArgs(ProcedureInfo myProcedure, int myCount) { - get { return _MyProcedure; } - set { _MyProcedure = value; } - } - private int _MyCount; - - public int MyCount - { - get { return _MyCount; } - set { _MyCount = value; } - } - public ItemInfoListCCEventArgs(ProcedureInfo myProcedure, int myCount) - { - _MyProcedure = myProcedure; - _MyCount = myCount; + MyProcedure = myProcedure; + MyCount = myCount; } } public partial class ItemInfoList { public static event ItemInfoListCCEvent ConsistencyCheckUpdated; - private static void OnConsistencyCheckUpdated(object sender, ItemInfoListCCEventArgs args) - { - if (ConsistencyCheckUpdated != null) - ConsistencyCheckUpdated(sender, args); - } - public static ItemInfoList GetMoreProcedures(List procs) + private static void OnConsistencyCheckUpdated(object sender, ItemInfoListCCEventArgs args) => ConsistencyCheckUpdated?.Invoke(sender, args); + public static ItemInfoList GetMoreProcedures(List procs) { StringBuilder sb = new StringBuilder(""); int count = 1; @@ -290,11 +274,8 @@ namespace VEPROMS.CSLA.Library get { return _DocVersionID; } set { _DocVersionID = value; } } - public ItemListAllInConsistenciesCriteria(int docVersionID) - { - _DocVersionID = docVersionID; - } - } + public ItemListAllInConsistenciesCriteria(int docVersionID) => _DocVersionID = docVersionID; + } private void DataPortal_Fetch(ItemListAllInConsistenciesCriteria criteria) { this.RaiseListChangedEvents = false; @@ -359,16 +340,9 @@ namespace VEPROMS.CSLA.Library } public static Revision GetByItemIDAndRevisionNumber(int itemID, string revisionNumber) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Revision"); try { - //Revision tmp = GetCachedByPrimaryKey(revisionID); - //if (tmp == null) - //{ - Revision tmp = DataPortal.Fetch(new ItemRevisionNumberCriteria(itemID, revisionNumber)); - // AddToCache(tmp); - //} + Revision tmp = DataPortal.Fetch(new ItemRevisionNumberCriteria(itemID, revisionNumber)); if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Revision @@ -384,13 +358,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemRevisionNumberCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - private string _RevisionNumber; - public string RevisionNumber - { get { return _RevisionNumber; } } - public ItemRevisionNumberCriteria(int itemID, string revisionNumber) + private readonly int _ItemID; + public int ItemID => _ItemID; + private readonly string _RevisionNumber; + public string RevisionNumber => _RevisionNumber; + public ItemRevisionNumberCriteria(int itemID, string revisionNumber) { _ItemID = itemID; _RevisionNumber = revisionNumber; @@ -442,16 +414,9 @@ namespace VEPROMS.CSLA.Library //jcb 20120625 public static Revision GetByItemIDAndRevisionNumberAndUnitID(int itemID, string revisionNumber, int unitID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Revision"); try { - //Revision tmp = GetCachedByPrimaryKey(revisionID); - //if (tmp == null) - //{ Revision tmp = DataPortal.Fetch(new UnitItemRevisionNumberCriteria(itemID, revisionNumber, unitID)); - // AddToCache(tmp); - //} if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Revision @@ -467,16 +432,13 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class UnitItemRevisionNumberCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - private string _RevisionNumber; - public string RevisionNumber - { get { return _RevisionNumber; } } - private int _UnitID; - public int UnitID - { get { return _UnitID; } } - public UnitItemRevisionNumberCriteria(int itemID, string revisionNumber, int unitID) + private readonly int _ItemID; + public int ItemID => _ItemID; + private readonly string _RevisionNumber; + public string RevisionNumber => _RevisionNumber; + private readonly int _UnitID; + public int UnitID => _UnitID; + public UnitItemRevisionNumberCriteria(int itemID, string revisionNumber, int unitID) { _ItemID = itemID; _RevisionNumber = revisionNumber; @@ -535,12 +497,9 @@ namespace VEPROMS.CSLA.Library { try { - //if (_RevisionInfoList != null) - // return _RevisionInfoList; RevisionInfoList tmp = DataPortal.Fetch(new ItemCriteria(itemID)); RevisionInfo.AddList(tmp); tmp.AddEvents(); - //_RevisionInfoList = tmp; return tmp; } catch (Exception ex) @@ -551,14 +510,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public ItemCriteria(int itemID) - { - _ItemID = itemID; - } - } + private readonly int _ItemID; + public int ItemID => _ItemID; + public ItemCriteria(int itemID) => _ItemID = itemID; + } private void DataPortal_Fetch(ItemCriteria criteria) { this.RaiseListChangedEvents = false; @@ -594,12 +549,9 @@ namespace VEPROMS.CSLA.Library { try { - //if (_RevisionInfoList != null) - // return _RevisionInfoList; RevisionInfoList tmp = DataPortal.Fetch(new ItemUnitCriteria(itemID, unitID)); RevisionInfo.AddList(tmp); tmp.AddEvents(); - //_RevisionInfoList = tmp; return tmp; } catch (Exception ex) @@ -610,13 +562,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemUnitCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - private int _UnitID; - public int UnitID - { get { return _UnitID; } } - public ItemUnitCriteria(int itemID, int unitID) + private readonly int _ItemID; + public int ItemID => _ItemID; + private readonly int _UnitID; + public int UnitID => _UnitID; + public ItemUnitCriteria(int itemID, int unitID) { _ItemID = itemID; _UnitID = unitID; @@ -671,14 +621,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class ItemCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public ItemCriteria(int itemID) - { - _ItemID = itemID; - } - private int _UnitID = 0; + private readonly int _ItemID; + public int ItemID => _ItemID; + public ItemCriteria(int itemID) => _ItemID = itemID; + private int _UnitID = 0; public int UnitID { get{return _UnitID;} @@ -696,12 +642,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class CurrentItemUnitCriteria : ItemCriteria { - public CurrentItemUnitCriteria(int itemID, int unitID) - : base(itemID) - { - UnitID = unitID; - } - } + public CurrentItemUnitCriteria(int itemID, int unitID) + : base(itemID) => UnitID = unitID; + } [Serializable()] protected class PreviousItemCriteria : ItemCriteria { @@ -714,12 +657,6 @@ namespace VEPROMS.CSLA.Library { try { - //RevisionInfo tmp = GetCachedByPrimaryKey(revisionID); - //if (tmp == null) - //{ - // tmp = DataPortal.Fetch(new PKCriteria(revisionID)); - // AddToCache(tmp); - //} RevisionInfo tmp = DataPortal.Fetch(new CurrentItemCriteria(itemID)); if (tmp.ErrorMessage == "No Record Found") { @@ -754,12 +691,6 @@ namespace VEPROMS.CSLA.Library { try { - //RevisionInfo tmp = GetCachedByPrimaryKey(revisionID); - //if (tmp == null) - //{ - // tmp = DataPortal.Fetch(new PKCriteria(revisionID)); - // AddToCache(tmp); - //} RevisionInfo tmp = DataPortal.Fetch(new PreviousItemCriteria(itemID)); if (tmp.ErrorMessage == "No Record Found") { @@ -906,9 +837,11 @@ namespace VEPROMS.CSLA.Library } public static string BuildRevisionChecks(ProcedureInfo proc) { - ConsistencyChecks cc = new ConsistencyChecks(); - cc.ItemID = proc.ItemID; - BuildROChecks(cc, proc); + ConsistencyChecks cc = new ConsistencyChecks + { + ItemID = proc.ItemID + }; + BuildROChecks(cc, proc); BuildTransitionFromChecks(cc, proc); BuildTransitionToChecks(cc, proc); BuildLibDocChecks(cc, proc); @@ -933,13 +866,11 @@ namespace VEPROMS.CSLA.Library //create checkro record for each roid //_MyTimer.ActiveProcess = "Get DocVersionInfo"; -// DocVersionInfo dbi = proc.ActiveParent as DocVersionInfo; DocVersionInfo dvi = proc.MyDocVersion; //_MyTimer.ActiveProcess = "Get MyROFst"; if (dvi.DocVersionAssociations == null || dvi.DocVersionAssociations.Count == 0) return; // B2020-124: don't crash if docversion doesn't have rofst ROFstInfo rofst = ROFstInfo.GetJustROFst(dvi.DocVersionAssociations[0].ROFstID); //_MyTimer.ActiveProcess = "Get ROFst Lookup"; - //rofst.docVer = dvi; ROFSTLookup lookup = rofst.GetROFSTLookup(dvi); //_MyTimer.ActiveProcess = "Populating RevisionChecksXML table"; cc.ROConsistency.ROFstDate = rofst.DTS; @@ -957,27 +888,21 @@ namespace VEPROMS.CSLA.Library using (TransitionInfoList myList = TransitionInfoList.GetAllForProcedure(proc, true)) foreach (TransitionInfo myTI in myList) { - //\v \v0 - string lookFor = string.Format(@"", myTI.TranType, myTI.TransitionID); - //string lookFor = string.Format(@"", myTI.TranType, myTI.TransitionID); - //string lookFor = string.Format(@"", tran.TranType, tran.TransitionID); + string lookFor = string.Format(@"", myTI.TranType, myTI.TransitionID); Match m = Regex.Match(myTI.ContentText, lookFor); if (m != null && m.Groups.Count > 1) { - int myIndex = m.Groups[4].Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index; - myLength += m.Groups[3].Length; - } - string gg = myTI.ContentText.Substring(myIndex, myLength); - cc.AddTransitionFromCheck(myTI.TransitionID, gg); -// System.Text.RegularExpressions.Group g = m.Groups[3]; -// cc.AddTransitionFromCheck(myTI.TransitionID, g.ToString()); + int myIndex = m.Groups[4].Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index; + myLength += m.Groups[3].Length; + } + string gg = myTI.ContentText.Substring(myIndex, myLength); + cc.AddTransitionFromCheck(myTI.TransitionID, gg); } //_MyTimer.ActiveProcess = "get from path"; - //string myPath = myTI.MyItemToID.ShortPath; } } private static void BuildTransitionToChecks(ConsistencyChecks cc, ProcedureInfo proc) @@ -985,24 +910,20 @@ namespace VEPROMS.CSLA.Library using (TransitionInfoList myList = TransitionInfoList.GetAllForProcedure(proc, false)) foreach (TransitionInfo myTI in myList) { - string lookFor = string.Format(@"", myTI.TranType, myTI.TransitionID); - //string lookFor = string.Format(@"", myTI.TranType, myTI.TransitionID); - //string lookFor = string.Format(@"", tran.TranType, tran.TransitionID); + string lookFor = string.Format(@"", myTI.TranType, myTI.TransitionID); Match m = Regex.Match(myTI.ContentText, lookFor); if (m != null && m.Groups.Count > 1) { - int myIndex = m.Groups[4].Index; - int myLength = m.Groups[4].Length; - if (m.Groups[3].Value != " ") - { - myIndex = m.Groups[3].Index; - myLength += m.Groups[3].Length; - } - string gg = myTI.ContentText.Substring(myIndex, myLength); - gg = gg.Replace("{", @"\{").Replace("}", @"\}"); - cc.AddTransitionToCheck(myTI.TransitionID, gg); -// System.Text.RegularExpressions.Group g = m.Groups[3]; -// cc.AddTransitionToCheck(myTI.TransitionID, g.ToString()); + int myIndex = m.Groups[4].Index; + int myLength = m.Groups[4].Length; + if (m.Groups[3].Value != " ") + { + myIndex = m.Groups[3].Index; + myLength += m.Groups[3].Length; + } + string gg = myTI.ContentText.Substring(myIndex, myLength); + gg = gg.Replace("{", @"\{").Replace("}", @"\}"); + cc.AddTransitionToCheck(myTI.TransitionID, gg); } } } @@ -1013,25 +934,16 @@ namespace VEPROMS.CSLA.Library cc.AddLibDocCheck(myDI.DocID, myDI.DTS); } private static Volian.Base.Library.VlnTimer _MyTimer; - public static void SetupTimer() - { - _MyTimer = new Volian.Base.Library.VlnTimer(); - } - public static void ShowTimer() - { - _MyTimer.ShowElapsedTimes("BuildROChecks"); - } - } + public static void SetupTimer() => _MyTimer = new Volian.Base.Library.VlnTimer(); + public static void ShowTimer() => _MyTimer.ShowElapsedTimes("BuildROChecks"); + } public partial class RoUsageInfoList { [Serializable()] private class AllForProcedureCriteria { - public AllForProcedureCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public AllForProcedureCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -1090,11 +1002,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class AllForProcedureCriteria { - public AllForProcedureCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public AllForProcedureCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -1217,9 +1126,11 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - TransitionInfo ti = new TransitionInfo(dr); - ti.ContentText = dr.GetString("ContentText"); - this.Add(ti); + TransitionInfo ti = new TransitionInfo(dr) + { + ContentText = dr.GetString("ContentText") + }; + this.Add(ti); } IsReadOnly = true; } @@ -1239,11 +1150,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class AllForProcedureCriteria { - public AllForProcedureCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public AllForProcedureCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -1301,15 +1209,9 @@ namespace VEPROMS.CSLA.Library [XmlRoot("ConsistencyChecks")] public class ConsistencyChecks { - public static ConsistencyChecks Get(string xml) - { - return GenericSerializer.StringDeserialize(xml); - } - public override string ToString() - { - return GenericSerializer.StringSerialize(this); - } - private int _ItemID; + public static ConsistencyChecks Get(string xml) => GenericSerializer.StringDeserialize(xml); + public override string ToString() => GenericSerializer.StringSerialize(this); + private int _ItemID; [XmlAttribute("ItemID")] public int ItemID { @@ -1326,12 +1228,9 @@ namespace VEPROMS.CSLA.Library get { return _ROConsistency; } set { _ROConsistency = value; } } - public void AddROCheck(string roid, string roValue) - { - ROConsistency.AddROCheck(roid, roValue); - } + public void AddROCheck(string roid, string roValue) => ROConsistency.AddROCheck(roid, roValue); - private TransitionConsistency _TransitionFromConsistency = new TransitionConsistency(); + private TransitionConsistency _TransitionFromConsistency = new TransitionConsistency(); [XmlElement("TransitionFromChecks")] [Category("Transitions")] [Description("Transition From Consistency Data")] @@ -1341,11 +1240,8 @@ namespace VEPROMS.CSLA.Library get { return _TransitionFromConsistency; } set { _TransitionFromConsistency = value; } } - public void AddTransitionFromCheck(int transitionid, string transitionValue) - { - TransitionFromConsistency.AddTransitionCheck(transitionid, transitionValue); - } - private TransitionConsistency _TransitionToConsistency = new TransitionConsistency(); + public void AddTransitionFromCheck(int transitionid, string transitionValue) => TransitionFromConsistency.AddTransitionCheck(transitionid, transitionValue); + private TransitionConsistency _TransitionToConsistency = new TransitionConsistency(); [XmlElement("TransitionToChecks")] [Category("Transitions")] [Description("Transition To Consistency Data")] @@ -1355,11 +1251,8 @@ namespace VEPROMS.CSLA.Library get { return _TransitionToConsistency; } set { _TransitionToConsistency = value; } } - public void AddTransitionToCheck(int transitionid, string transitionValue) - { - TransitionToConsistency.AddTransitionCheck(transitionid, transitionValue); - } - private TransitionConsistency _TransitionConsistency = new TransitionConsistency(); + public void AddTransitionToCheck(int transitionid, string transitionValue) => TransitionToConsistency.AddTransitionCheck(transitionid, transitionValue); + private TransitionConsistency _TransitionConsistency = new TransitionConsistency(); [XmlElement("TransitionChecks")] [Category("Transitions")] [Description("Transition Consistency Data")] @@ -1380,11 +1273,8 @@ namespace VEPROMS.CSLA.Library get { return _LibDocConsistency; } set { _LibDocConsistency = value; } } - public void AddLibDocCheck(int docid, DateTime docdate) - { - LibDocConsistency.AddLibDocCheck(docid, docdate); - } - } + public void AddLibDocCheck(int docid, DateTime docdate) => LibDocConsistency.AddLibDocCheck(docid, docdate); + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class ROConsistency @@ -1422,11 +1312,8 @@ namespace VEPROMS.CSLA.Library if (!_ROCheckList.ContainsKey(roid)) _ROCheckList.Add(roid, new ROCheck(roid, roValue)); } - public override string ToString() - { - return string.Format("{0} ROs", _ROCheckList.Count); - } - } + public override string ToString() => string.Format("{0} ROs", _ROCheckList.Count); + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class ROCheck @@ -1463,11 +1350,8 @@ namespace VEPROMS.CSLA.Library public ROCheck() { } - public override string ToString() - { - return string.Format("{0} - '{1}'", ROID, ROValue); - } - } + public override string ToString() => string.Format("{0} - '{1}'", ROID, ROValue); + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] @@ -1497,11 +1381,8 @@ namespace VEPROMS.CSLA.Library if (!_TransitionCheckList.ContainsKey(transitionid)) _TransitionCheckList.Add(transitionid, new TransitionCheck(transitionid, transitionValue)); } - public override string ToString() - { - return string.Format("{0} Transitions", _TransitionCheckList.Count); - } - } + public override string ToString() => string.Format("{0} Transitions", _TransitionCheckList.Count); + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class TransitionCheck @@ -1538,11 +1419,8 @@ namespace VEPROMS.CSLA.Library public TransitionCheck() { } - public override string ToString() - { - return string.Format("{0} - '{1}'", TransitionID, TransitionValue); - } - } + public override string ToString() => string.Format("{0} - '{1}'", TransitionID, TransitionValue); + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] @@ -1572,11 +1450,8 @@ namespace VEPROMS.CSLA.Library if (!_LibDocCheckList.ContainsKey(docid)) _LibDocCheckList.Add(docid, new LibDocCheck(docid, docDate)); } - public override string ToString() - { - return string.Format("{0} LibDocs", _LibDocCheckList.Count); - } - } + public override string ToString() => string.Format("{0} LibDocs", _LibDocCheckList.Count); + } [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class LibDocCheck @@ -1604,16 +1479,10 @@ namespace VEPROMS.CSLA.Library { get { - //if (_OldDocDate == DateTime.MinValue) - // return null; return _OldDocDate; } set { - //if (value == null) - // _OldDocDate = DateTime.MinValue; - //else - // _OldDocDate = value.Value; _OldDocDate = value; } } @@ -1625,11 +1494,8 @@ namespace VEPROMS.CSLA.Library public LibDocCheck() { } - public override string ToString() - { - return string.Format("{0} - '{1}'", DocID, DocDate); - } - } + public override string ToString() => string.Format("{0} - '{1}'", DocID, DocDate); + } public enum Rev_Types : int { Revision = 1, TempMod = 2 diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/StageExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/StageExt.cs index b51e543e..a06db1d1 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/StageExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/StageExt.cs @@ -9,13 +9,6 @@ // ======================================================================== using System; -//using System.Collections.Generic; -//using System.Collections.Specialized; -//using System.Text; -//using System.IO; -//using System.Xml.Serialization; -//using System.Xml; -//using System.Xml.XPath; using Csla; using Csla.Data; using System.Data.SqlClient; @@ -50,14 +43,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteriaJustStage { - private int _StageID; - public int StageID - { get { return _StageID; } } - public PKCriteriaJustStage(int stageID) - { - _StageID = stageID; - } - } + private readonly int _StageID; + public int StageID => _StageID; + public PKCriteriaJustStage(int stageID) => _StageID = stageID; + } private void DataPortal_Fetch(PKCriteriaJustStage criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageInfo.DataPortal_Fetch", GetHashCode()); @@ -99,8 +88,6 @@ namespace VEPROMS.CSLA.Library { public static Stage GetJustStage(int stageID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Stage"); try { Stage tmp = DataPortal.Fetch(new PKCriteriaJustStage(stageID)); @@ -138,12 +125,6 @@ namespace VEPROMS.CSLA.Library return; } ReadData(dr); - // Don't load child objects - //dr.NextResult(); - //_StageChecks = StageChecks.Get(dr); - // load child objects - //dr.NextResult(); - //_StageVersions = StageVersions.Get(dr); } } // removing of item only needed for local data portal @@ -161,17 +142,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteriaJustStage { - private int _StageID; - public int StageID - { get { return _StageID; } } - public PKCriteriaJustStage(int stageID) - { - _StageID = stageID; - } - } - - #region Log4Net - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion + private readonly int _StageID; + public int StageID => _StageID; + public PKCriteriaJustStage(int stageID) => _StageID = stageID; + } } } diff --git a/PROMS/VEPROMS.CSLA.Library/Extension/TransitionExt.cs b/PROMS/VEPROMS.CSLA.Library/Extension/TransitionExt.cs index 194d8b6f..bc6bd42a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Extension/TransitionExt.cs +++ b/PROMS/VEPROMS.CSLA.Library/Extension/TransitionExt.cs @@ -25,25 +25,10 @@ namespace VEPROMS.CSLA.Library get { return _NewTransToUnNumberedItem; } set { _NewTransToUnNumberedItem = value; } } - public string PathTo - { - get - { - return MyItemToID.Path; - } - } - public string PathFrom - { - get - { - return MyContent.ContentItems[0].Path; - } - } - public override string ToString() - { - return string.Format("ID: {0} From: {1} To: {2}", TransitionID, FromID, ToID); - } - [NonSerialized] + public string PathTo => MyItemToID.Path; + public string PathFrom => MyContent.ContentItems[0].Path; + public override string ToString() => $"ID: {TransitionID} From: {FromID} To: {ToID}"; + [NonSerialized] private TransitionConfig _TransitionConfig; public TransitionConfig TransitionConfig { @@ -56,27 +41,7 @@ namespace VEPROMS.CSLA.Library return _TransitionConfig; } } - public bool HasPageNum - { - get - { - return TransitionConfig.Transition_Formatted.ToUpper() == "TRUE"; - } - } - public string ResolvePathTo(FormatInfo fi, ItemInfo itminfo, int tranType, ItemInfo toitem, ItemInfo rangeitem, bool hasPageNum) - { - try - { - return TransitionText.GetResolvedText(fi, itminfo, tranType, toitem, rangeitem, HasPageNum); - } - catch (Exception ex) - { - if (tranType == 2 && ex.Message == "Cannot find Next Item") - return TransitionText.GetResolvedText(fi, itminfo, tranType, toitem, toitem, HasPageNum); - _MyLog.Error("Error Processing Transition Text", ex); - return "(Resolved Transition Text)"; - } - } + public bool HasPageNum => TransitionConfig.Transition_Formatted.ToUpper() == "TRUE"; public string ResolvePathTo(FormatInfo fi, ItemInfo itminfo, int tranType, ItemInfo toitem, ItemInfo rangeitem) { try @@ -108,13 +73,6 @@ namespace VEPROMS.CSLA.Library ItemInfo item = MyContent.ContentItems[0]; ItemInfo myItemToID = MyItemToID; if (tranLookup.ContainsKey(item.ItemID)) item = tranLookup[item.ItemID]; - bool hasPageNum = false; - if (item.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier || - item.ActiveFormat.PlantFormat.FormatData.TransData.UseSpecificTransitionModifier) - { - TransitionConfig tc = new TransitionConfig(Config); - if (tc != null && tc.Transition_Formatted.ToUpper() == "TRUE") hasPageNum = true; - } if (tranLookup.ContainsKey(ToID)) { myItemToID = tranLookup[ToID]; @@ -150,7 +108,7 @@ namespace VEPROMS.CSLA.Library //Console.WriteLine("MyItemToID = {0}", MyItemToID); //Console.WriteLine("MyItemRangeID = {0}", MyItemRangeID); } - return ResolvePathTo(item.ActiveFormat, item, TranType, myItemToID, myItemRangeID, hasPageNum); + return ResolvePathTo(item.ActiveFormat, item, TranType, myItemToID, myItemRangeID); } } #region AffectedTransitons @@ -172,17 +130,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class TransitionReportDataCriteria { - private int _VersionID; - public int VersionID - { - get { return _VersionID; } - } - private int _ProcedureID; - public int ProcedureID - { - get { return _ProcedureID; } - } - public TransitionReportDataCriteria(int versionID, int procedureID) + private readonly int _VersionID; + public int VersionID => _VersionID; + private readonly int _ProcedureID; + public int ProcedureID => _ProcedureID; + public TransitionReportDataCriteria(int versionID, int procedureID) { _VersionID = versionID; _ProcedureID = procedureID; @@ -208,9 +160,11 @@ namespace VEPROMS.CSLA.Library IsReadOnly = false; while (dr.Read()) { - TransitionInfo ti = new TransitionInfo(dr); - ti.Level = dr.GetInt32("level"); - this.Add(ti); + TransitionInfo ti = new TransitionInfo(dr) + { + Level = dr.GetInt32("level") + }; + this.Add(ti); } IsReadOnly = true; } @@ -228,11 +182,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class AffectedTransitonsCriteria { - public AffectedTransitonsCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public AffectedTransitonsCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -287,24 +238,17 @@ namespace VEPROMS.CSLA.Library { StringBuilder sb = new StringBuilder(""); foreach (TransitionInfo trans in this) - sb.Append("\r\n" + trans.PathFrom); + sb.Append($"\r\n{trans.PathFrom}"); return sb.ToString(); } #endregion #region ExternalTransitionsToChildren private class ExternalTransitionsToChildrenCriteria { - public ExternalTransitionsToChildrenCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - } + public ExternalTransitionsToChildrenCriteria(int itemID) => ItemID = itemID; + + public int ItemID { get; set; } + } public static TransitionInfoList GetExternalTransitionsToChildren(int itemID) { try @@ -354,17 +298,10 @@ namespace VEPROMS.CSLA.Library #region ExternalTransitions private class ExternalTransitionsCriteria { - public ExternalTransitionsCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - } + public ExternalTransitionsCriteria(int itemID) => ItemID = itemID; + + public int ItemID { get; set; } + } public static TransitionInfoList GetExternalTransitions(int itemID) { try @@ -413,17 +350,10 @@ namespace VEPROMS.CSLA.Library #region PastedAffectedTransitions private class PastedAffectedTransitonsCriteria { - public PastedAffectedTransitonsCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - } + public PastedAffectedTransitonsCriteria(int itemID) => ItemID = itemID; + + public int ItemID { get; set; } + } internal static TransitionInfoList GetPastedAffected(int itemID) { try @@ -472,17 +402,10 @@ namespace VEPROMS.CSLA.Library #region TransitionsToDisconnected private class TransitionsToDisconnectedCriteria { - public TransitionsToDisconnectedCriteria(string docVersionList) - { - _DocVersionList = docVersionList; - } - private string _DocVersionList; - public string DocVersionList - { - get { return _DocVersionList; } - set { _DocVersionList = value; } - } - } + public TransitionsToDisconnectedCriteria(string docVersionList) => DocVersionList = docVersionList; + + public string DocVersionList { get; set; } + } public static TransitionInfoList GetTransitionsToDisconnected(string docVersionList) { try @@ -531,17 +454,10 @@ namespace VEPROMS.CSLA.Library #region TransitionsToNonEditable private class TransitionsToNonEditableCriteria { - public TransitionsToNonEditableCriteria(string docVersionList) - { - _DocVersionList = docVersionList; - } - private string _DocVersionList; - public string DocVersionList - { - get { return _DocVersionList; } - set { _DocVersionList = value; } - } - } + public TransitionsToNonEditableCriteria(string docVersionList) => DocVersionList = docVersionList; + + public string DocVersionList { get; set; } + } public static TransitionInfoList GetTransitionsToNonEditable(string docVersionList) { try @@ -590,7 +506,7 @@ namespace VEPROMS.CSLA.Library } public class TransitionBuilder { - private StringBuilder _Results = new StringBuilder(); + private readonly StringBuilder _Results = new StringBuilder(); public FormatData _FormatData; public string _TransFormat; public E_TransUI _TransUI; @@ -599,53 +515,25 @@ namespace VEPROMS.CSLA.Library public ItemInfo _ToItem; public ItemInfo _RangeItem; public bool _UsedRangeAncestor; - private string _Token; - public string _UnitProcSetString; + public string _UnitProcSetString; public bool SectNumWithStepNum; - private int _SectionNumberLength = 0; - public int SectionNumberLength - { - get { return _SectionNumberLength; } - set { _SectionNumberLength = value; } - } - private string _StepPrefix = ""; - public string StepPrefix - { - get { return _StepPrefix; } - set { _StepPrefix = value; } - } - private List _SectionsUsed = new List(); - public List SectionsUsed - { - get { return _SectionsUsed; } - } - public string Token - { - get { return _Token; } - set { _Token = value; } - } - private string _Prefix; + + public int SectionNumberLength { get; set; } = 0; + public string StepPrefix { get; set; } = ""; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List _SectionsUsed = new List(); + public List SectionsUsed => _SectionsUsed; + public string Token { get; set; } + private string _Prefix; public string Prefix { get { return _Prefix; } set { if(_Prefix==null)_Prefix = value; } } - public void ResetPrefix(string str) - { - _Prefix = str; - } - public bool HasText - { - get - { - return _Results.Length > 0; - } - } - public StringBuilder Append(string str) - { - return _Results.Append(str); - } - public StringBuilder ReplaceToken(string str) + public void ResetPrefix(string str) => _Prefix = str; + public bool HasText => _Results.Length > 0; + public StringBuilder Append(string str) => _Results.Append(str); + public StringBuilder ReplaceToken(string str) { if (str == null || str == "") return _Results; if (_FormatData.TransData.XchngTranSpForHard && str[0]!=',' && str[0] != ' ') @@ -662,19 +550,10 @@ namespace VEPROMS.CSLA.Library else return _Results.Append(str.TrimEnd(" :".ToCharArray())); } - public override string ToString() - { - return _Results.ToString(); - } - public StringBuilder Remove(int startIndex, int length) - { - return _Results.Remove(startIndex, length); - } - public int Length - { - get { return _Results.Length; } - } - public void AppendPrefix() + public override string ToString() => _Results.ToString(); + public StringBuilder Remove(int startIndex, int length) => _Results.Remove(startIndex, length); + public int Length => _Results.Length; + public void AppendPrefix() { if (Prefix == null) return; // no Prefix text to add if (HasText) @@ -741,47 +620,43 @@ namespace VEPROMS.CSLA.Library private static Dictionary _AppendMethods; private static void SetupMethods() { - _AppendMethods = new Dictionary(); - _AppendMethods.Add("{Proc Num}", AddTransitionProcNum); - _AppendMethods.Add("{?.Proc Num}", AddOptionalTransitionProcNum); - _AppendMethods.Add("{Proc Title}", AddTransitionProcTitle); - _AppendMethods.Add("{?.Proc Title}", AddOptionalTransitionProcTitle); - _AppendMethods.Add("{First Step}", AddStepNumber); - _AppendMethods.Add("{Step Number}", AddStepNumber); // WCN2, tran type 6 - _AppendMethods.Add("{Last Step}", AddRangeStepNumber); - _AppendMethods.Add("{.}", AddIncludedStepNumber); - _AppendMethods.Add("{Sect Hdr}", AddTranGetSectionHdr); - _AppendMethods.Add("{?.Sect Hdr}", AddOptionalTranGetSectionHdr); - _AppendMethods.Add("{Sect Title}", AddTranGetSectionTitle); - _AppendMethods.Add("{?.Sect Title}", AddOptionalTranGetSectionTitle); - _AppendMethods.Add("{?.Sect Num}", AddOptionalTranGetSectionNum); - _AppendMethods.Add("{Sect Num}", AddTranGetSectionNumber); - _AppendMethods.Add("{Sect Num All}", AddTranGetAllSectionNumber); - _AppendMethods.Add("{Sect Number}", AddTranGetSectionNumber); // WCN2, tran type 6 - _AppendMethods.Add("{Page Num}", AddPageNumber); - _AppendMethods.Add("{Step Text}", AddStepText); + _AppendMethods = new Dictionary + { + { "{Proc Num}", AddTransitionProcNum }, + { "{?.Proc Num}", AddOptionalTransitionProcNum }, + { "{Proc Title}", AddTransitionProcTitle }, + { "{?.Proc Title}", AddOptionalTransitionProcTitle }, + { "{First Step}", AddStepNumber }, + { "{Step Number}", AddStepNumber }, // WCN2, tran type 6 + { "{Last Step}", AddRangeStepNumber }, + { "{.}", AddIncludedStepNumber }, + { "{Sect Hdr}", AddTranGetSectionHdr }, + { "{?.Sect Hdr}", AddOptionalTranGetSectionHdr }, + { "{Sect Title}", AddTranGetSectionTitle }, + { "{?.Sect Title}", AddOptionalTranGetSectionTitle }, + { "{?.Sect Num}", AddOptionalTranGetSectionNum }, + { "{Sect Num}", AddTranGetSectionNumber }, + { "{Sect Num All}", AddTranGetAllSectionNumber }, + { "{Sect Number}", AddTranGetSectionNumber }, // WCN2, tran type 6 + { "{Page Num}", AddPageNumber }, + { "{Step Text}", AddStepText } + }; } - public static string GetResolvedText(ItemInfo fromInfo, int tranType, ItemInfo toItem, ItemInfo rangeItem, bool hasPageNum) - { - return GetResolvedText(fromInfo.ActiveFormat, fromInfo, tranType, toItem, rangeItem, hasPageNum); - } - private static Regex RegFixVCS = new Regex(@"Section ([0-9.]+)(.0)? Step \1"); // Find Section xxx followed by Step xxx + public static string GetResolvedText(ItemInfo fromInfo, int tranType, ItemInfo toItem, ItemInfo rangeItem, bool hasPageNum) => GetResolvedText(fromInfo.ActiveFormat, fromInfo, tranType, toItem, rangeItem, hasPageNum); + private static readonly Regex RegFixVCS = new Regex(@"Section ([0-9.]+)(.0)? Step \1"); // Find Section xxx followed by Step xxx public static string GetResolvedText(FormatInfo formatInfo, ItemInfo fromInfo, int tranType, ItemInfo toItem, ItemInfo rangeItem, bool pagenum) { if (!pagenum) { TransitionInfo ct = fromInfo.MyContent.ContentTransitionCount > 0 ? fromInfo.MyContent.ContentTransitions[0] : null; - int trIU = -1; - string cfg = string.Empty; - if (ct != null) + if (ct != null) { - trIU = fromInfo.MyContent.ContentTransitions[0].MyTransitionInfoUnique; - cfg = fromInfo.MyContent.ContentTransitions[0].Config; - } + _ = fromInfo.MyContent.ContentTransitions[0].MyTransitionInfoUnique; + _ = fromInfo.MyContent.ContentTransitions[0].Config; + } else { - string pattern = string.Format(@"( [0-9]*){{1,2}}\[END>"); - //string pattern = string.Format(@".*\\v ( [0-9]*){{1,2}}\[END>"); + string pattern = string.Format(@"( [0-9]*){{1,2}}\[END>"); Match m = Regex.Match(fromInfo.MyContent.Text, pattern); if (m.Groups.Count > 1 && m.Groups[1].Value.ToUpper().Contains("(PAGE ~)")) // B2020-089, check for upper case Page ~ in case step was upper cased pagenum = true; @@ -805,7 +680,7 @@ namespace VEPROMS.CSLA.Library tb._TransFormat = tb._TransFormat.Insert(tb._TransFormat.IndexOf("{First Step}")+12, " {Page Num}"); } else - tb._TransFormat = tb._TransFormat + " {Page Num}"; + tb._TransFormat += " {Page Num}"; } } if(_AppendMethods==null) @@ -820,18 +695,7 @@ namespace VEPROMS.CSLA.Library retval = toItem.Ordinal.ToString(); fromInfo.NewTransToUnNumberedItem = true; //Volian.Base.Library.vlnStackTrace.ShowStackLocal("Setting Flag", 3, 10); - //using (Item itm = fromInfo.Get()) - //{ - // ItemAnnotation ia = itm.ItemAnnotations.Add(AnnotationType.GetByName("Verifcation Required")); - // ia.SearchText = "Transition to Un-Numbered Step"; - //itm.Save(); - //} } - //if (Regex.IsMatch(retval, @".*\[[BP][0-9]{4,4}\].*") - // && tb._ToItem.ActiveFormat != null - // && tb._ToItem.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert ) - // retval = Regex.Replace(retval, @" *(\[[BP][0-9]{4,4}\])+",""); - //return retval; if (Regex.IsMatch(retval, @".* *\[([A-Z0-9 ]|\\u160\?)+\] *.*") && tb._ToItem.ActiveFormat != null && tb._ToItem.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) @@ -844,11 +708,13 @@ namespace VEPROMS.CSLA.Library } private static TransitionBuilder SetupTransitionBuilder(FormatInfo formatInfo, ItemInfo fromInfo, int tranType, ItemInfo toItem, ItemInfo rangeItem) { - TransitionBuilder tb = new TransitionBuilder(); - tb._FormatData = formatInfo.PlantFormat.FormatData; - // get the format of the transition string based on this transition's index into the TransData part of - // format.... - if (tranType >= tb._FormatData.TransData.TransTypeList.MaxIndex) // found during fixing of B2016-176 B2016-197 fixes invalid index error during import of procedure + TransitionBuilder tb = new TransitionBuilder + { + _FormatData = formatInfo.PlantFormat.FormatData + }; + // get the format of the transition string based on this transition's index into the TransData part of + // format.... + if (tranType >= tb._FormatData.TransData.TransTypeList.MaxIndex) // found during fixing of B2016-176 B2016-197 fixes invalid index error during import of procedure tranType = 0; // Replace 3 tokens ", {.}, {.}, {.}" with a single token "{.}" tb._TransFormat = tb._FormatData.TransData.TransTypeList[tranType].TransFormat.Replace(", {.}, {.}, {.}", "{.}"); @@ -873,9 +739,7 @@ namespace VEPROMS.CSLA.Library tb._TranType = 4; } int startIndex = 0; - int index = -1; - int rexIndex = -1; - string prefix = null; + string prefix = null; string prevToken = null; bool lastAdded = false; MatchCollection mc = Regex.Matches(tb._TransFormat, @"{(Proc Num|\?\.Proc Num|Proc Title|\?\.Proc Title|" + @@ -885,8 +749,8 @@ namespace VEPROMS.CSLA.Library { string tmppref = prefix; prefix = null; - rexIndex = m.Index; - int rexEndToken = m.Index + m.Length - 1; + int rexIndex = m.Index; + int rexEndToken = m.Index + m.Length - 1; if (rexIndex > startIndex) prefix = tb._TransFormat.Substring(startIndex, rexIndex - startIndex); if (prefix == null) prevToken = null; // if the last token did not add anything to the buffer, still want to put the text prefix in: @@ -1007,9 +871,8 @@ namespace VEPROMS.CSLA.Library // as used by AEP is: UnitProcSetString ="{PSI:UNITCOM}-{SI:SETNAME}-{PSI:SETID}-" string findMatch = "{.*?}"; MatchCollection ms = Regex.Matches(tb._UnitProcSetString,findMatch); - string txt = tb._UnitProcSetString; - FolderConfig fc = tb._ToItem.MyDocVersion.MyFolder.FolderConfig as FolderConfig; - ProcedureConfig pc = new ProcedureConfig(tb._ToItem.MyProcedure.MyContent.Config); + _ = tb._ToItem.MyDocVersion.MyFolder.FolderConfig as FolderConfig; + ProcedureConfig pc = new ProcedureConfig(tb._ToItem.MyProcedure.MyContent.Config); // Use a dictionary to get all of the tokens from the format string, then // go through all dictionary entries to make the replacements. Dictionary repStr = new Dictionary(); @@ -1094,7 +957,7 @@ namespace VEPROMS.CSLA.Library { lretstr.Append(tb._FormatData.TransData.DelimiterForTransitionTitle); lretstr.Append(tb._FormatData.TransData.CapsTransitions ? parenstr.ToUpper().Replace(@"\U", @"\u") : - tb._FormatData.TransData.Cap1stCharTrans ? CapFirstLetterOnly(parenstr, 0) : + tb._FormatData.TransData.Cap1stCharTrans ? CapFirstLetterOnly(parenstr) : parenstr); lretstr.Append(tb._FormatData.TransData.DelimiterForTransitionTitle); } @@ -1170,7 +1033,7 @@ namespace VEPROMS.CSLA.Library if (thisTab != null && thisTab != "") { thisTab = thisTab.Trim(" ".ToCharArray()); - if (hasDelim && !thisTab.EndsWith(".") && !thisTab.EndsWith(")")) thisTab = thisTab + "."; + if (hasDelim && !thisTab.EndsWith(".") && !thisTab.EndsWith(")")) thisTab += "."; if (hasDotZero && thisTab.EndsWith(".0.")) thisTab = thisTab.Substring(0, thisTab.Length - 2); } // RHM 20130326 2039 - I added the logic to limit the addition of the section tab to @@ -1197,7 +1060,7 @@ namespace VEPROMS.CSLA.Library if (!hasDelim) foreach (string rmvDelim in DelimList) hlsTab = hlsTab.Replace(rmvDelim, ""); hlsTab = hlsTab.Trim(" ".ToCharArray()); - if (hasDelim && !hlsTab.EndsWith(".") && !hlsTab.EndsWith(")")) hlsTab = hlsTab + "."; + if (hasDelim && !hlsTab.EndsWith(".") && !hlsTab.EndsWith(")")) hlsTab += "."; if (hasDotZero) { if (item.IsHigh) @@ -1218,9 +1081,6 @@ namespace VEPROMS.CSLA.Library } private static bool AddPageNumber(TransitionBuilder tb) { - //At some point, add a property off a section 'IsFoldout' and use the next two lines: - //if ((myProcedure.ActiveFormat.PlantFormat.FormatData.PrintData.SectionLevelFoldouts && mySection.MyContent.Number.ToUpper() == "FOLDOUT") - //|| (myProcedure.ActiveFormat.PlantFormat.FormatData.PrintData.AlternateFloatingFoldout && mySection.MyContent.Text.ToUpper().Contains("FOLDOUT"))) if (tb._ToItem.PageNumber != -1 && (tb._FromItem.PageNumber != -1 || (tb._FromItem.ActiveSection.MyConfig as SectionConfig).Section_IsFoldout == "Y")) //C2019-042 Section_IsFoldout checks Section Number, Section Title, and use of check box { int pgoffset = tb._ToItem.PageNumber - tb._FromItem.PageNumber; @@ -1255,9 +1115,11 @@ namespace VEPROMS.CSLA.Library } private static bool AddStepNumber(TransitionBuilder tb) { - // If we're on a step put out the step number. - ItemInfo secitm = TranGetSectionItem(tb._ToItem); - if ((!((tb._TransUI & E_TransUI.StepAllowNone) == E_TransUI.StepAllowNone)) || tb._ToItem.MyContent.Type > 20000) + // If we're on a step put out the step number. +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Kept for Debugging + ItemInfo secitm = TranGetSectionItem(tb._ToItem); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + if ((!((tb._TransUI & E_TransUI.StepAllowNone) == E_TransUI.StepAllowNone)) || tb._ToItem.MyContent.Type > 20000) { if (tb._FormatData.PrintData.SpecialCaseCalvertAlarm && tb._ToItem.IsHigh && tb._ToItem.FormatStepData.StepEditData.TypeMenu.MenuItem.ToUpper().Contains("WINDOW")) { @@ -1281,7 +1143,6 @@ namespace VEPROMS.CSLA.Library tb.Remove(tb.Length - 7, 7); // 7 is length of ", Step " tb.AppendPrefix(); } - //else if (tb._TranType == 4 && tb._ToItem.MoreThanOneStepSection()) else if (tb._TranType == 4 && tb._ToItem.MoreThanOneStepSection() || tb._TranType == 5) { tb.AppendPrefix(); @@ -1333,14 +1194,14 @@ namespace VEPROMS.CSLA.Library bool usedRangeAncestor = false; // Refresh Next Items tb._ToItem.RefreshNextItems(); - ItemInfo next = GetNextItem(tb._ToItem, rangeAncestors, ref usedRangeAncestor); + ItemInfo next = GetNextItem(tb._ToItem, rangeAncestors); string lastTab = Tab(tb._RangeItem, tb._RangeItem.ActiveFormat.PlantFormat.FormatData.TransData.TStepNoFlag); while (next.ItemID != tb._RangeItem.ItemID) { string thisTab = Tab(next, tb._RangeItem.ActiveFormat.PlantFormat.FormatData.TransData.TStepNoFlag); if (lastTab == thisTab) break; tb.ReplaceToken(", " + thisTab); - next = GetNextItem(next, rangeAncestors, ref usedRangeAncestor); + next = GetNextItem(next, rangeAncestors); } tb._UsedRangeAncestor = usedRangeAncestor; return true; @@ -1363,7 +1224,7 @@ namespace VEPROMS.CSLA.Library } return retval; } - private static ItemInfo GetNextItem(ItemInfo next, Dictionary rangeAncestors, ref bool usedRangeAncestor) + private static ItemInfo GetNextItem(ItemInfo next, Dictionary rangeAncestors) { if (rangeAncestors.ContainsKey(next.ItemID)) return rangeAncestors[next.ItemID]; @@ -1473,15 +1334,9 @@ namespace VEPROMS.CSLA.Library } return false; } - private static bool AddTranGetSectionNumber(TransitionBuilder tb) - { - return AddTranGetSectionNumber(tb, false); - } - private static bool AddTranGetAllSectionNumber(TransitionBuilder tb) - { - return AddTranGetSectionNumber(tb, true); - } - private static bool AddTranGetSectionNumber(TransitionBuilder tb, bool allLevels) + private static bool AddTranGetSectionNumber(TransitionBuilder tb) => AddTranGetSectionNumber(tb, false); + private static bool AddTranGetAllSectionNumber(TransitionBuilder tb) => AddTranGetSectionNumber(tb, true); + private static bool AddTranGetSectionNumber(TransitionBuilder tb, bool allLevels) { if (tb._TranType == 1 && tb._ToItem.ActiveSection.ItemID == tb._FromItem.ActiveSection.ItemID) return false; if (tb.SectNumWithStepNum) return false; @@ -1514,13 +1369,9 @@ namespace VEPROMS.CSLA.Library tb.ReplaceToken(retstr); return (retstr != null && retstr != ""); } - //B2016-003 Transitions to sections whose number has a leading space was causing errors in transition text - private static string TrimSectNumber(string str) - { - if (str == null) return str; - return str.TrimStart(); - } - private static string FixTitleCase(Match m) + //B2016-003 Transitions to sections whose number has a leading space was causing errors in transition text + private static string TrimSectNumber(string str) => str == null ? str : str.TrimStart(); + private static string FixTitleCase(Match m) { if (Regex.IsMatch(m.Value, @"^[A-Za-z]+\.?$")) { @@ -1533,12 +1384,11 @@ namespace VEPROMS.CSLA.Library } return m.Value; } - private static string CapFirstLetterOnly(string retstr, int p) + private static string CapFirstLetterOnly(string retstr) { - // LATER: write code to capitalize first letter (active plants) - // F2021-037: Support title case include '/' as separator (added '/' to regex replace) - string lretstr = Regex.Replace(retstr, @"([^ ,/]+)", new MatchEvaluator(FixTitleCase)); - return lretstr; + // LATER: write code to capitalize first letter (active plants) + // F2021-037: Support title case include '/' as separator (added '/' to regex replace) + return Regex.Replace(retstr, @"([^ ,/]+)", new MatchEvaluator(FixTitleCase)); } // TODO: Section methods are not complete.... private static ItemInfo TranGetSectionItem(ItemInfo itminfo) @@ -1564,7 +1414,7 @@ namespace VEPROMS.CSLA.Library string str1 = TranGetSectionNumber(tb._ToItem); // F2024-008 added flag to title case the section number in transitions if (tb._FormatData.TransData.Cap1stCharTransSectionNumber) - str1 = CapFirstLetterOnly(str1, 0); + str1 = CapFirstLetterOnly(str1); if(!tb._ToItem.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) return str1; List FromSections = GetSections(tb._FromItem.ActiveSection); List ToSections = GetSections(tb._ToItem.ActiveSection); @@ -1578,11 +1428,9 @@ namespace VEPROMS.CSLA.Library break; } } - //string str = tmpitm.MyContent.Number; string str = BuildSectionPath(ToSections); // B2024-025 - process all of the applicability token (, , ) str = VEPROMS.CSLA.Library.DisplayText.ResolveUnitSpecific(tb._ToItem.MyDocVersion, str); - //if (!str.EndsWith(".") && tb._ToItem.ItemID != tb._ToItem.ActiveSection.ItemID) tb.StepPrefix = "."; tb.SectionNumberLength = str.Length; return (str); @@ -1611,11 +1459,8 @@ namespace VEPROMS.CSLA.Library sb.Append(sep + lastPart.TrimEnd(" ".ToCharArray())); return sb.ToString(); } - private static bool IsRoman(string number) - { - return Regex.IsMatch(number,@"[IVXLCDM]+\.?"); - } - private static List GetSections(ItemInfo myItemInfo) + private static bool IsRoman(string number) => Regex.IsMatch(number, @"[IVXLCDM]+\.?"); + private static List GetSections(ItemInfo myItemInfo) { List retval = new List(); while (myItemInfo != null && myItemInfo.IsSection) @@ -1633,7 +1478,7 @@ namespace VEPROMS.CSLA.Library ItemInfo tmpitm = TranGetSectionItem(itminfo); string sectionTitle = tmpitm.MyContent.Text; sectionTitle = (tb._FormatData.TransData.CapsTransitionsSection ? sectionTitle.ToUpper().Replace(@"\U", @"\u") : - tb._FormatData.TransData.Cap1stCharTransSection ? CapFirstLetterOnly(sectionTitle, 0) : + tb._FormatData.TransData.Cap1stCharTransSection ? CapFirstLetterOnly(sectionTitle) : sectionTitle); // F2024-008 Added flag to surround the section title with parenthesis in transitions if (tb._FormatData.TransData.ParensAroundSectionTitle) @@ -1658,7 +1503,7 @@ namespace VEPROMS.CSLA.Library ItemInfo tmpitm = TranGetSectionItem(itminfo); string sectionTitle = tmpitm.MyContent.Text; sectionTitle = (tb._FormatData.TransData.CapsTransitionsSection ? sectionTitle.ToUpper().Replace(@"\U", @"\u") : - tb._FormatData.TransData.Cap1stCharTransSection ? CapFirstLetterOnly(sectionTitle, 0) : + tb._FormatData.TransData.Cap1stCharTransSection ? CapFirstLetterOnly(sectionTitle) : sectionTitle); // B2017-236 Replace embedded returns with spaces and trim the spaces from the end of the section title. return TrimSectionTitle(sectionTitle); diff --git a/PROMS/VEPROMS.CSLA.Library/Format/Comparator.cs b/PROMS/VEPROMS.CSLA.Library/Format/Comparator.cs index 14e7fc87..e6ff1820 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/Comparator.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/Comparator.cs @@ -1,40 +1,23 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Xml; -using System.Windows.Forms; namespace VEPROMS.CSLA.Library { public class Comparator { - private XmlDocument _ResultsDoc; - public XmlDocument ResultsDoc - { - get { return _ResultsDoc; } - set { _ResultsDoc = value; } - } - private XmlDocument _XDoc1; - public XmlDocument XDoc1 - { - get { return _XDoc1; } - set { _XDoc1 = value; } - } - private XmlDocument _XDoc2; - public XmlDocument XDoc2 - { - get { return _XDoc2; } - set { _XDoc2 = value; } - } - public Comparator(XmlDocument xdoc1, XmlDocument xdoc2) + public XmlDocument ResultsDoc { get; set; } + public XmlDocument XDoc1 { get; set; } + public XmlDocument XDoc2 { get; set; } + public Comparator(XmlDocument xdoc1, XmlDocument xdoc2) { XDoc1 = xdoc1; XDoc2 = xdoc2; ResultsDoc = new XmlDocument(); ResultsDoc.LoadXml(@""); } - public Comparator(string existingFC, string importedFC) //string fName1, string fName2) + public Comparator(string existingFC, string importedFC) { XDoc1 = new XmlDocument(); XDoc1.LoadXml(existingFC); @@ -104,12 +87,12 @@ namespace VEPROMS.CSLA.Library xnss1.Add(GetKey(xc1), xc1); foreach (XmlNode xc2 in xns2.Values) if (xnss1.ContainsKey(GetKey(xc2))) - Compare(xnss1[GetKey(xc2)], xc2, path + "/" + GetKey(xc2)); + Compare(xnss1[GetKey(xc2)], xc2, $"{path}/{GetKey(xc2)}"); else xnss2.Add(GetKey(xc2), xc2); // element differences, if counts are different. xns1 elements are not found in xns2 and xns2 elements are not found in xns1 if (xns1.Count == 0 && xns2.Count == 0) return; - Console.WriteLine(" {0} {1} {2}", path + "/" + xn1.Name, xns1.Count, xns2.Count); + Console.WriteLine($" {path}/{xn1.Name} {xns1.Count} {xns2.Count}"); foreach (string key in xnss1.Keys) { if (xnss1[key].Attributes.Count > 0 || xnss1[key].ChildNodes.Count > 0) @@ -210,18 +193,14 @@ namespace VEPROMS.CSLA.Library public string GetKey1(XmlNode xn) { if (xn.Attributes == null) return xn.Name; - XmlAttribute xi = xn.Attributes.GetNamedItem("Index") as XmlAttribute; - if (xi != null) - { - XmlAttribute xa = xn.Attributes.GetNamedItem("Name") as XmlAttribute; - if (xa != null) return string.Format("{0}[{1}]", xn.Name, xa.Value); - return string.Format("{0}[{1}]", xn.Name, xi.Value); - } - XmlAttribute xt = xn.Attributes.GetNamedItem("Token") as XmlAttribute; - if(xt != null) return string.Format("{0}[{1}]", xn.Name, xt.Value); - XmlAttribute xw = xn.Attributes.GetNamedItem("ReplaceWord") as XmlAttribute; - if(xw != null) return string.Format("{0}[{1}]", xn.Name, xw.Value); - return xn.Name; + if (xn.Attributes.GetNamedItem("Index") is XmlAttribute xi) + { + if (xn.Attributes.GetNamedItem("Name") is XmlAttribute xa) return string.Format("{0}[{1}]", xn.Name, xa.Value); + return string.Format("{0}[{1}]", xn.Name, xi.Value); + } + if (xn.Attributes.GetNamedItem("Token") is XmlAttribute xt) return string.Format("{0}[{1}]", xn.Name, xt.Value); + if (xn.Attributes.GetNamedItem("ReplaceWord") is XmlAttribute xw) return string.Format("{0}[{1}]", xn.Name, xw.Value); + return xn.Name; } static private XmlNode makeXPath(XmlDocument doc, string xpath) { @@ -252,7 +231,6 @@ namespace VEPROMS.CSLA.Library string name = nextNodeInXPath.Substring(indx, nextNodeInXPath.IndexOf("=",indx)-indx); XmlAttribute xKeyd = doc.CreateAttribute(name); indx = nextNodeInXPath.IndexOf("='",indx)+2; - string value = nextNodeInXPath.Substring(indx,nextNodeInXPath.IndexOf("'", indx) - indx); xKeyd.Value = nextNodeInXPath.Substring(indx,nextNodeInXPath.IndexOf("'",indx)-indx); node.Attributes.Append(xKeyd); } @@ -277,58 +255,56 @@ namespace VEPROMS.CSLA.Library // go through attributes in first xml document, see if they exist in the 2nd xml document & are identical attribute foreach (XmlAttribute xa1 in atts1) { - XmlAttribute xa2 = atts2.GetNamedItem(xa1.Name) as XmlAttribute; - if (xa2 == null) - { - XmlNode xnr = MakeXPathFormat(path); - if (xnr != null) - { - XmlAttribute xKey = ResultsDoc.CreateAttribute(xa1.Name+"Old"); - xKey.Value = xa1.Value; - xnr.Attributes.Append(xKey); - xKey = ResultsDoc.CreateAttribute("OldKey"); - xKey.Value = GetKey(atts1Par); - if (xKey.Value != null) xnr.Attributes.Append(xKey); - } - } - else if (xa2.Value != xa1.Value) - { - XmlNode xnr = MakeXPathFormat(path); - if (xnr != null) - { - XmlAttribute xKey = ResultsDoc.CreateAttribute(xa1.Name + "Old"); - xKey.Value = xa1.Value; - xnr.Attributes.Append(xKey); - XmlAttribute xKey2 = ResultsDoc.CreateAttribute(xa2.Name + "New"); - xKey2.Value = xa2.Value; - xnr.Attributes.Append(xKey2); - xKey = ResultsDoc.CreateAttribute("OldKey"); - xKey.Value = GetKey(atts1Par); - if (xKey.Value != null) xnr.Attributes.Append(xKey); - xKey = ResultsDoc.CreateAttribute("NewKey"); - xKey.Value = GetKey(atts2Par); - if (xKey.Value != null) xnr.Attributes.Append(xKey); - } - } - } + if (!(atts2.GetNamedItem(xa1.Name) is XmlAttribute xa2)) + { + XmlNode xnr = MakeXPathFormat(path); + if (xnr != null) + { + XmlAttribute xKey = ResultsDoc.CreateAttribute(xa1.Name + "Old"); + xKey.Value = xa1.Value; + xnr.Attributes.Append(xKey); + xKey = ResultsDoc.CreateAttribute("OldKey"); + xKey.Value = GetKey(atts1Par); + if (xKey.Value != null) xnr.Attributes.Append(xKey); + } + } + else if (xa2.Value != xa1.Value) + { + XmlNode xnr = MakeXPathFormat(path); + if (xnr != null) + { + XmlAttribute xKey = ResultsDoc.CreateAttribute(xa1.Name + "Old"); + xKey.Value = xa1.Value; + xnr.Attributes.Append(xKey); + XmlAttribute xKey2 = ResultsDoc.CreateAttribute(xa2.Name + "New"); + xKey2.Value = xa2.Value; + xnr.Attributes.Append(xKey2); + xKey = ResultsDoc.CreateAttribute("OldKey"); + xKey.Value = GetKey(atts1Par); + if (xKey.Value != null) xnr.Attributes.Append(xKey); + xKey = ResultsDoc.CreateAttribute("NewKey"); + xKey.Value = GetKey(atts2Par); + if (xKey.Value != null) xnr.Attributes.Append(xKey); + } + } + } // go through attributes in 2nd xml document to see if they exist in the first xml document & are identical foreach (XmlAttribute xa2 in atts2) { - XmlAttribute xa1 = atts1.GetNamedItem(xa2.Name) as XmlAttribute; - if (xa1 == null) - { - XmlNode xnr = MakeXPathFormat(path); - if (xnr != null) - { - XmlAttribute xKey = ResultsDoc.CreateAttribute(xa2.Name+"New"); - xKey.Value = xa2.Value; - xnr.Attributes.Append(xKey); - xKey = ResultsDoc.CreateAttribute("NewKey"); - xKey.Value = GetKey(atts2Par); - if (xKey.Value != null) xnr.Attributes.Append(xKey); - } - } - } + if (!(atts1.GetNamedItem(xa2.Name) is XmlAttribute)) + { + XmlNode xnr = MakeXPathFormat(path); + if (xnr != null) + { + XmlAttribute xKey = ResultsDoc.CreateAttribute(xa2.Name + "New"); + xKey.Value = xa2.Value; + xnr.Attributes.Append(xKey); + xKey = ResultsDoc.CreateAttribute("NewKey"); + xKey.Value = GetKey(atts2Par); + if (xKey.Value != null) xnr.Attributes.Append(xKey); + } + } + } } #endregion } diff --git a/PROMS/VEPROMS.CSLA.Library/Format/DocStyles.cs b/PROMS/VEPROMS.CSLA.Library/Format/DocStyles.cs index de3187f2..02ab8036 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/DocStyles.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/DocStyles.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; using System.Xml; @@ -13,14 +11,8 @@ namespace VEPROMS.CSLA.Library [Description("Document Styles Name")] //Not used in the PROMS code. Only used as a title for the DocStyles grouping private LazyLoad _Name; - public string Name - { - get - { - return LazyLoad(ref _Name, "@Name"); - } - } - private DocStyleList _DocStyleList; + public string Name => LazyLoad(ref _Name, "@Name"); + private DocStyleList _DocStyleList; public DocStyleList DocStyleList { get @@ -68,38 +60,20 @@ namespace VEPROMS.CSLA.Library #region IndexName // a unuque number that is use in the SQL record to referenced the DocStyle for a seciton private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } - [Description("Document Styles Name")] + public int? Index => LazyLoad(ref _Index, "@Index"); + [Description("Document Styles Name")] // Use in the lists that display the name of a seciton format style (Section Properties) private LazyLoad _Name; - public string Name - { - get - { - return LazyLoad(ref _Name, "@Name"); - } - } - #endregion - #region Font - // the font to use for the section - private VE_Font _Font; - [Category("Font")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return(_Font == null) ?_Font = new VE_Font(XmlNode): _Font; - } - } - #endregion + public string Name => LazyLoad(ref _Name, "@Name"); + #endregion + #region Font + // the font to use for the section + private VE_Font _Font; + [Category("Font")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + #endregion #region AdjustTopMarginOnStepContinuePages // B2017-267 Put in for Farley who uses the "PSOnlyFirst" in some of their pagelists so that a section title is printed only on the first page of the section. // This will adjust the top margin when the section title is not printed on the other pages. (CreateStepPDF() in PromsPrinter.cs) @@ -125,413 +99,245 @@ namespace VEPROMS.CSLA.Library // count just within this section, don't count, etc). // - see E_NumberingSequence in Enum.cs private LazyLoad _NumberingSequence; - public E_NumberingSequence? NumberingSequence - { - get - { - return LazyLoad(ref _NumberingSequence, "@NumberingSequence"); - } - } - #endregion numberingsequence + public E_NumberingSequence? NumberingSequence => LazyLoad(ref _NumberingSequence, "@NumberingSequence"); + #endregion numberingsequence - #region IndexOtherThanFirstPage - [Category("Miscellaneous")] + #region IndexOtherThanFirstPage + [Category("Miscellaneous")] [Description("IndexOtherThanFirstPage")] // references the DocStyle to use for pages two through the last page of the section. this is used along with the "Where" setting "UseOnFirstPage" private LazyLoad _IndexOtherThanFirstPage; - public int? IndexOtherThanFirstPage - { - get - { - return LazyLoad(ref _IndexOtherThanFirstPage, "@IndexOtherThanFirstPage"); - } - } - #endregion IndexOtherThanFirstPage + public int? IndexOtherThanFirstPage => LazyLoad(ref _IndexOtherThanFirstPage, "@IndexOtherThanFirstPage"); + #endregion IndexOtherThanFirstPage - #region SecOvrideSupInfoTabOff - // This overrides the tab position of the Supplemental Information steps at the section level - // This will also override the overall supplemental Information tab adjustment set at the format level (SupInfoTabOff) - [Category("Miscellaneous")] + #region SecOvrideSupInfoTabOff + // This overrides the tab position of the Supplemental Information steps at the section level + // This will also override the overall supplemental Information tab adjustment set at the format level (SupInfoTabOff) + [Category("Miscellaneous")] [Description("SecOvrideSupInfoTabOff")] private LazyLoad _SecOvrideSupInfoTabOff; - public int? SecOvrideSupInfoTabOff - { - get - { - return LazyLoad(ref _SecOvrideSupInfoTabOff, "@SecOvrideSupInfoTabOff"); - } - } - #endregion SecOvrideSupInfoTabOff + public int? SecOvrideSupInfoTabOff => LazyLoad(ref _SecOvrideSupInfoTabOff, "@SecOvrideSupInfoTabOff"); + #endregion SecOvrideSupInfoTabOff - #region IsStepSection - [Category("Miscellaneous")] + #region IsStepSection + [Category("Miscellaneous")] [Description("Is a Step Section")] // When set to True, the section uses the PROMS Step editor, when set to False, Word is used to edit the section contents private LazyLoad _IsStepSection; - public bool IsStepSection - { - get - { - return LazyLoad(ref _IsStepSection, "@IsStepSection"); - } - } - #endregion IsStepSection + public bool IsStepSection => LazyLoad(ref _IsStepSection, "@IsStepSection"); + #endregion IsStepSection - #region Inactive - [Category("Miscellaneous")] + #region Inactive + [Category("Miscellaneous")] [Description("Is Active Section Type")] // when set to True, the section type is hidden from the user // - but this section type could still be used "internally" by PROMS (i.e. when "Where" is set to "UseOnAllButFirstPage") // - is also used to keep un-used section types around for future use private LazyLoad _Inactive; - public bool Inactive - { - get - { - return LazyLoad(ref _Inactive, "@Inactive"); - } - } - #endregion Inactive + public bool Inactive => LazyLoad(ref _Inactive, "@Inactive"); + #endregion Inactive - #region SupplementalInfo - [Category("Miscellaneous")] + #region SupplementalInfo + [Category("Miscellaneous")] [Description("Supports Supplemental Information")] // Use in SAMG procedures, flag that tells PROMS this section type can have Supplemental Information. // This information is entered as an RNO off of a step but is printed on the backside of the previous page // (like a foldout page) so that it is visable along with the steps that it applies. private LazyLoad _SupplementalInformation; - public bool SupplementalInformation - { - get - { - return LazyLoad(ref _SupplementalInformation, "@SupplementalInformation"); - } - } + public bool SupplementalInformation => LazyLoad(ref _SupplementalInformation, "@SupplementalInformation"); - // B2023-060: Procedures with Supplemental Information will assume that all sections are printed separately. - // This flag will use the Section's properties/pagination (continuous or separate) - // rather than always setting to separate - [Category("Miscellaneous")] + // B2023-060: Procedures with Supplemental Information will assume that all sections are printed separately. + // This flag will use the Section's properties/pagination (continuous or separate) + // rather than always setting to separate + [Category("Miscellaneous")] [Description("Supports Supplemental Information Pagination")] private LazyLoad _SupInfoNoPaginOverride; - public bool SupInfoNoPaginOverride - { - get - { - return LazyLoad(ref _SupInfoNoPaginOverride, "@SupInfoNoPaginOverride"); - } - } + public bool SupInfoNoPaginOverride => LazyLoad(ref _SupInfoNoPaginOverride, "@SupInfoNoPaginOverride"); - // F2023-035: WCN - allow for change in left margin for supplemental information pages by - // setting a value in the DocStyle for the adjustment. This is used when importing the vlnParagraph page - // page & when doing pagelist items - // summary: adjustment to the left margin for the associated supplemental information pages - private LazyLoad _SupInfoMargAdj; - public float? SupInfoMargAdj - { - get - { - return LazyLoad(ref _SupInfoMargAdj, "@SupInfoMargAdj"); - } - } + // F2023-035: WCN - allow for change in left margin for supplemental information pages by + // setting a value in the DocStyle for the adjustment. This is used when importing the vlnParagraph page + // page & when doing pagelist items + // summary: adjustment to the left margin for the associated supplemental information pages + private LazyLoad _SupInfoMargAdj; + public float? SupInfoMargAdj => LazyLoad(ref _SupInfoMargAdj, "@SupInfoMargAdj"); - #endregion SupplementalInfo + #endregion SupplementalInfo - #region LandscapePageList - [Category("Miscellaneous")] + #region LandscapePageList + [Category("Miscellaneous")] [Description("Should PageList be landscape")] // this will rotate the associated PageStyle information 180 degrees to the left private LazyLoad _LandscapePageList; - public bool LandscapePageList - { - get - { - return LazyLoad(ref _LandscapePageList, "@LandscapePageList"); - } - } - #endregion LandscapePageList - - #region ShowSectionTitles - [Category("Miscellaneous")] + public bool LandscapePageList => LazyLoad(ref _LandscapePageList, "@LandscapePageList"); + #endregion LandscapePageList + + #region ShowSectionTitles + [Category("Miscellaneous")] [Description("Should Section Titles be shown")] private LazyLoad _ShowSectionTitles; - // like the ShowSectionTitles at the StepSectionLayData level - turns on printing the section number and title on the first page of the section. This allows it to be controled based on which section type was selected, so long as it's set to false at the StepSectionLayData level. - public bool ShowSectionTitles - { - get - { - return LazyLoad(ref _ShowSectionTitles, "@ShowSectionTitles"); - } - } - #endregion ShowSectionTitles + // like the ShowSectionTitles at the StepSectionLayData level - turns on printing the section number and title on the first page of the section. This allows it to be controled based on which section type was selected, so long as it's set to false at the StepSectionLayData level. + public bool ShowSectionTitles => LazyLoad(ref _ShowSectionTitles, "@ShowSectionTitles"); + #endregion ShowSectionTitles - #region ResetFirstPageOnSection - [Category("Miscellaneous")] + #region ResetFirstPageOnSection + [Category("Miscellaneous")] [Description("Reset first page of section on Separate pagination section")] // put in for V.C. Summer private LazyLoad _ResetFirstPageOnSection; - public bool ResetFirstPageOnSection - { - get - { - return LazyLoad(ref _ResetFirstPageOnSection, "@ResetFirstPageOnSection"); - } - } - #endregion ResetFirstPageOnSection + public bool ResetFirstPageOnSection => LazyLoad(ref _ResetFirstPageOnSection, "@ResetFirstPageOnSection"); + #endregion ResetFirstPageOnSection - #region IncludeInTOC - [Category("Miscellaneous")] + #region IncludeInTOC + [Category("Miscellaneous")] [Description("Include in Auto Table Of Contents")] // this will include the section in the Automatic Table Of Contents by default (unless it's turned off in Section Properties) private LazyLoad _IncludeInTOC; - public bool IncludeInTOC - { - get - { - return LazyLoad(ref _IncludeInTOC, "@IncludeInTOC"); - } - } - #endregion IncludeInTOC + public bool IncludeInTOC => LazyLoad(ref _IncludeInTOC, "@IncludeInTOC"); + #endregion IncludeInTOC - #region UseCheckOffs - [Category("Miscellaneous")] + #region UseCheckOffs + [Category("Miscellaneous")] [Description("Section Uses Checkoffs")] // turns on the ability for a step editor section to have checkoffs private LazyLoad _UseCheckOffs; - public bool UseCheckOffs - { - get - { - return LazyLoad(ref _UseCheckOffs, "@UseCheckOffs"); - } - } - #endregion UseCheckOffs + public bool UseCheckOffs => LazyLoad(ref _UseCheckOffs, "@UseCheckOffs"); + #endregion UseCheckOffs - #region UseCheckOffs - [Category("Miscellaneous")] + #region UseCheckOffs + [Category("Miscellaneous")] [Description("Section Uses MetaSection ColSByLevel")] // the section uses the MetaSection ColSByLevel setting (based on step text level) to position the step on the page private LazyLoad _UseColSByLevel; - public bool UseColSByLevel - { - get - { - return LazyLoad(ref _UseColSByLevel, "@UseColSByLevel"); - } - } - #endregion UseCheckOffs + public bool UseColSByLevel => LazyLoad(ref _UseColSByLevel, "@UseColSByLevel"); + #endregion UseCheckOffs - #region CancelSectTitle - [Category("Miscellaneous")] + #region CancelSectTitle + [Category("Miscellaneous")] [Description("Section Cancel Section Title")] // this will prevent the section number and title from printing at the beginning of the section. This is set to false when the section number and/or title is printed from the PageStyle instead private LazyLoad _CancelSectTitle; - public bool CancelSectTitle - { - get - { - return LazyLoad(ref _CancelSectTitle, "@CancelSectTitle"); - } - } - #endregion CancelSectTitle + public bool CancelSectTitle => LazyLoad(ref _CancelSectTitle, "@CancelSectTitle"); + #endregion CancelSectTitle - #region DontInsertBlankPages - [Category("Miscellaneous")] + #region DontInsertBlankPages + [Category("Miscellaneous")] [Description("Don't insert blank pages in this section when printing duplex with blank pages")] //C2023-001 Added for Beaver Valley CAS sections (their two column format) private LazyLoad _DontInsertBlankPages; - public bool DontInsertBlankPages - { - get - { - return LazyLoad(ref _DontInsertBlankPages, "@DontInsertBlankPages"); - } - } - #endregion DontInsertBlankPages + public bool DontInsertBlankPages => LazyLoad(ref _DontInsertBlankPages, "@DontInsertBlankPages"); + #endregion DontInsertBlankPages - #region CenterLine - //CenterLineX="261.9" CenterLineYTop="673.2" CenterLineYBottom="44.2" - private LazyLoad _CenterLineX; - [Category("CenterLine")] - [DisplayName("X Location")] - [Description("Distance from left side of page")] - // horizontal positon of a center line that is drawn on the printed page - public float? CenterLineX - { - get - { - return LazyLoad(ref _CenterLineX, "@CenterLineX"); - } - } + #region CenterLine + //CenterLineX="261.9" CenterLineYTop="673.2" CenterLineYBottom="44.2" + private LazyLoad _CenterLineX; + [Category("CenterLine")] + [DisplayName("X Location")] + [Description("Distance from left side of page")] + // horizontal positon of a center line that is drawn on the printed page + public float? CenterLineX => LazyLoad(ref _CenterLineX, "@CenterLineX"); - // the vertical starting positon of a center line that is drawn on the printed page - private LazyLoad _CenterLineYTop; - [Category("CenterLine")] - [DisplayName("Y Top Location")] - [Description("starting vertical point of line")] - public float? CenterLineYTop - { - get - { - return LazyLoad(ref _CenterLineYTop, "@CenterLineYTop"); - } - } + // the vertical starting positon of a center line that is drawn on the printed page + private LazyLoad _CenterLineYTop; + [Category("CenterLine")] + [DisplayName("Y Top Location")] + [Description("starting vertical point of line")] + public float? CenterLineYTop => LazyLoad(ref _CenterLineYTop, "@CenterLineYTop"); - // the vertical ending positon of a center line that is drawn on the printed page - private LazyLoad _CenterLineYBottom; - [Category("CenterLine")] - [DisplayName("Y Bottom Location")] - [Description("ending vertical point of line")] - public float? CenterLineYBottom - { - get - { - return LazyLoad(ref _CenterLineYBottom, "@CenterLineYBottom"); - } - } + // the vertical ending positon of a center line that is drawn on the printed page + private LazyLoad _CenterLineYBottom; + [Category("CenterLine")] + [DisplayName("Y Bottom Location")] + [Description("ending vertical point of line")] + public float? CenterLineYBottom => LazyLoad(ref _CenterLineYBottom, "@CenterLineYBottom"); - private LazyLoad _CLineWidth; - [Category("CenterLine")] - [DisplayName("Line Width")] - [Description("Width of Lines Internal to Boxes")] - - // overrides the default pen width (.95) used to draw the center line - public float? CLineWidth - { - get - { - return LazyLoad(ref _CLineWidth, "@CLineWidth"); - } - } - #endregion CenterLine + private LazyLoad _CLineWidth; + [Category("CenterLine")] + [DisplayName("Line Width")] + [Description("Width of Lines Internal to Boxes")] - #region OptionalSectionContent - [Category("Miscellaneous")] + // overrides the default pen width (.95) used to draw the center line + public float? CLineWidth => LazyLoad(ref _CLineWidth, "@CLineWidth"); + #endregion CenterLine + + #region OptionalSectionContent + [Category("Miscellaneous")] [Description("Section Optional Content")] // don't print the "No Section Content" message when section is empty private LazyLoad _OptionalSectionContent; - public bool OptionalSectionContent - { - get - { - return LazyLoad(ref _OptionalSectionContent, "@OptionalSectionContent"); - } - } - #endregion OptionalSectionContent + public bool OptionalSectionContent => LazyLoad(ref _OptionalSectionContent, "@OptionalSectionContent"); + #endregion OptionalSectionContent - #region Section Number Flags - [Category("Miscellaneous")] + #region Section Number Flags + [Category("Miscellaneous")] [Description("Don't parse the section number - use DisplayNumber value")] // when creating a section tab, use as was entered in section properties private LazyLoad _DontParseSectionNumber; - public bool DontParseSectionNumber - { - get - { - return LazyLoad(ref _DontParseSectionNumber, "@DontParseSectionNumber"); - } - } - #endregion + public bool DontParseSectionNumber => LazyLoad(ref _DontParseSectionNumber, "@DontParseSectionNumber"); + #endregion - #region SpecialStepsFoldout - [Category("Miscellaneous")] + #region SpecialStepsFoldout + [Category("Miscellaneous")] [Description("Section Special Steps Foldout")] // (for step editor foldouts) reduces white space on the foldout page to allow more information on the page, // also special handling of step tabs when section numbers normally are part of step numbers private LazyLoad _SpecialStepsFoldout; - public bool SpecialStepsFoldout - { - get - { - return LazyLoad(ref _SpecialStepsFoldout, "@SpecialStepsFoldout"); - } - } + public bool SpecialStepsFoldout => LazyLoad(ref _SpecialStepsFoldout, "@SpecialStepsFoldout"); - [Category("Miscellaneous")] + [Category("Miscellaneous")] [Description("Section Special Steps Foldout with white space")] // allow for all of the other special foldout formatting, but not compress the page private LazyLoad _SpecialStepsFoldoutKeepWhiteSpace; - public bool SpecialStepsFoldoutKeepWhiteSpace - { - get - { - return LazyLoad(ref _SpecialStepsFoldoutKeepWhiteSpace, "@SpecialStepsFoldoutKeepWhiteSpace"); - } - } + public bool SpecialStepsFoldoutKeepWhiteSpace => LazyLoad(ref _SpecialStepsFoldoutKeepWhiteSpace, "@SpecialStepsFoldoutKeepWhiteSpace"); - [Category("Miscellaneous")] + [Category("Miscellaneous")] [Description("Section Extra Line Header")] // add and extra blank line before a Caution/Note header, appears to be used with SpecialStepsFoldout logic // and the SpaceIn set on Caution and Note step types private LazyLoad _ExtraLineHeader; - public bool ExtraLineHeader - { - get - { - return LazyLoad(ref _ExtraLineHeader, "@ExtraLineHeader"); - } - } - #endregion SpecialStepsFoldout + public bool ExtraLineHeader => LazyLoad(ref _ExtraLineHeader, "@ExtraLineHeader"); + #endregion SpecialStepsFoldout - #region UndSpecialStepsFoldout - [Category("Miscellaneous")] + #region UndSpecialStepsFoldout + [Category("Miscellaneous")] [Description("Section Cancel Section Title")] // used in Foldout section types, will underline the High Level Steps of a Foldout (Step Editor Section) private LazyLoad _UndSpecialStepsFoldout; - public bool UndSpecialStepsFoldout - { - get - { - return LazyLoad(ref _UndSpecialStepsFoldout, "@UndSpecialStepsFoldout"); - } - } - #endregion UndSpecialStepsFoldout + public bool UndSpecialStepsFoldout => LazyLoad(ref _UndSpecialStepsFoldout, "@UndSpecialStepsFoldout"); + #endregion UndSpecialStepsFoldout - #region CoverNoMergedPageNum - [Category("Miscellaneous")] + #region CoverNoMergedPageNum + [Category("Miscellaneous")] [Description("Cover Page Do Not Show Page Count")] // F2021-046: When doing the Merge option when printing all procedures, flag if cover page section // doesn't print the merged page number on first page of the merged pdf (used in printing Alarm Procedure sets) - private LazyLoad _CoverNoMergedPageNum; - public bool CoverNoMergedPageNum - { - get - { - return LazyLoad(ref _CoverNoMergedPageNum, "@CoverNoMergedPageNum"); - } - } - #endregion CoverNoMergedPageNum + private LazyLoad _CoverNoMergedPageNum; + public bool CoverNoMergedPageNum => LazyLoad(ref _CoverNoMergedPageNum, "@CoverNoMergedPageNum"); + #endregion CoverNoMergedPageNum - #region AlignHLSTabWithSect - [Category("Miscellaneous")] + #region AlignHLSTabWithSect + [Category("Miscellaneous")] [Description("Align HLS Tab With Sect")] // Align the starting position of the High Level Step to be under the section header (section title). // The step width is also ajusted to fit within the page margins private LazyLoad _AlignHLSTabWithSect; - public bool AlignHLSTabWithSect - { - get - { - return LazyLoad(ref _AlignHLSTabWithSect, "@AlignHLSTabWithSect"); - } - } - #endregion AlignHLSTabWithSect + public bool AlignHLSTabWithSect => LazyLoad(ref _AlignHLSTabWithSect, "@AlignHLSTabWithSect"); + #endregion AlignHLSTabWithSect - #region AdjSectTitleLoc - [Category("Miscellaneous")] + #region AdjSectTitleLoc + [Category("Miscellaneous")] [Description("Adjust Section Title Location")] // When high level steps are used as the high level section number and title (a ".0" is added to the high level @@ -540,44 +346,27 @@ namespace VEPROMS.CSLA.Library // This was added to support Barakah’s meta sections step/sub-step tabbing and the INITIAL sign off header // placement in the page header. private LazyLoad _AdjSectTitleLoc; - public bool AdjSectTitleLoc // B2022-129: don't indent HLS when flag is on (Barakah - single column step attachment with meta sect) - { - get - { - return LazyLoad(ref _AdjSectTitleLoc, "@AdjSectTitleLoc"); - } - } + public bool AdjSectTitleLoc // B2022-129: don't indent HLS when flag is on (Barakah - single column step attachment with meta sect) +=> LazyLoad(ref _AdjSectTitleLoc, "@AdjSectTitleLoc"); - // this will add additional spacing between the Section Numbers and Titles - private LazyLoad _SectTitleOffsetOverride; - public float? SectTitleOffsetOverride - { - get - { - return LazyLoad(ref _SectTitleOffsetOverride, "@SectTitleOffsetOverride"); - } - } + // this will add additional spacing between the Section Numbers and Titles + private LazyLoad _SectTitleOffsetOverride; + public float? SectTitleOffsetOverride => LazyLoad(ref _SectTitleOffsetOverride, "@SectTitleOffsetOverride"); - #endregion AdjSectTitleLoc + #endregion AdjSectTitleLoc - #region ShowAlarmPointWindowInfo - [Category("Miscellaneous")] + #region ShowAlarmPointWindowInfo + [Category("Miscellaneous")] [Description("Show Alarm Point Table Info in Step Editor")] //C2021-018 show alarm point RO data in step editor (BNPP Alarms) // used to display Alarm Point Table RO values in the editor. A read-only Note type is used, off of step the section title, to display the Alarm Point table RO information. private LazyLoad _ShowAlarmPointWindowInfo; - public bool ShowAlarmPointWindowInfo - { - get - { - return LazyLoad(ref _ShowAlarmPointWindowInfo, "@ShowAlarmPointWindowInfo"); - } - } - #endregion ShowAlarmPointWindowInfo + public bool ShowAlarmPointWindowInfo => LazyLoad(ref _ShowAlarmPointWindowInfo, "@ShowAlarmPointWindowInfo"); + #endregion ShowAlarmPointWindowInfo - #region ComponentList - [Category("Miscellaneous")] + #region ComponentList + [Category("Miscellaneous")] [Description("Component List")] // this is used generate a could different types of section and step formatting. @@ -586,17 +375,11 @@ namespace VEPROMS.CSLA.Library // It's used for Calvert Cliffs Alarm Point pages, Calvert Cliffs Valve List sections, // and Farley Component List tales (Figure section in EOP procedures). private LazyLoad _ComponentList; - public bool ComponentList - { - get - { - return LazyLoad(ref _ComponentList, "@ComponentList"); - } - } - #endregion ComponentList + public bool ComponentList => LazyLoad(ref _ComponentList, "@ComponentList"); + #endregion ComponentList - #region pagestyle - private PageStyle _pagestyle; + #region pagestyle + private PageStyle _pagestyle; [Category("Miscellaneous")] [DisplayName("Page Style")] [Description("Page Style")] @@ -607,8 +390,8 @@ namespace VEPROMS.CSLA.Library get { string str = "//PageStyles/PageStyle[" + (IntLookup("@PageStyle") + 1).ToString() + "]"; - XmlNode xn = SelectSingleNode(str); - if (_pagestyle == null) _pagestyle = new PageStyle(SelectSingleNode("//PageStyles/PageStyle[" + (IntLookup("@PageStyle") + 1).ToString() + "]")); + _ = SelectSingleNode(str); + if (_pagestyle == null) _pagestyle = new PageStyle(SelectSingleNode($"//PageStyles/PageStyle[{IntLookup("@PageStyle") + 1}]")); return _pagestyle; } } @@ -616,74 +399,29 @@ namespace VEPROMS.CSLA.Library #region SubElements private Layout _Layout; - public Layout Layout - { - get - { - return (_Layout == null ? _Layout = new Layout(SelectSingleNode("Layout")) : _Layout); - } - } - private SectTop _SectTop; - public SectTop SectTop - { - get - { - return (_SectTop == null ? _SectTop = new SectTop(SelectSingleNode("SectTop")) : _SectTop); - } - } - private Continue _Continue; - public Continue Continue - { - get - { - return (_Continue == null ? _Continue = new Continue(SelectSingleNode("Continue")) : _Continue); - } - } - private End _End; - public End End - { - get - { - return (_End == null ? _End = new End(SelectSingleNode("End")) : _End); - } - } - private Final _Final; - public Final Final - { - get - { - return (_Final == null ? _Final = new Final(SelectSingleNode("Final")) : _Final); - } - } - private StructureStyle _StructureStyle; - public StructureStyle StructureStyle - { - get - { - return (_StructureStyle == null ? _StructureStyle = new StructureStyle(SelectSingleNode("StructureStyle")) : _StructureStyle); - } - } - #endregion + public Layout Layout => _Layout ?? (_Layout = new Layout(SelectSingleNode("Layout"))); + private SectTop _SectTop; + public SectTop SectTop => _SectTop ?? (_SectTop = new SectTop(SelectSingleNode("SectTop"))); + private Continue _Continue; + public Continue Continue => _Continue ?? (_Continue = new Continue(SelectSingleNode("Continue"))); + private End _End; + public End End => _End ?? (_End = new End(SelectSingleNode("End"))); + private Final _Final; + public Final Final => _Final ?? (_Final = new Final(SelectSingleNode("Final"))); + private StructureStyle _StructureStyle; + public StructureStyle StructureStyle => _StructureStyle ?? (_StructureStyle = new StructureStyle(SelectSingleNode("StructureStyle"))); + #endregion - #region AltMultiUnitWording - [Category("Miscellaneous")] + #region AltMultiUnitWording + [Category("Miscellaneous")] [Description("Alternate Wording for Printing when MultiUnit")] // this will utilize Alternate Wording for Printing when MultiUnit and PrintCommonForZeroUnit is set private LazyLoad _AltMultiUnitWording; - public string AltMultiUnitWording - { - get - { - return LazyLoad(ref _AltMultiUnitWording, "@AltMultiUnitWording"); - } - } - #endregion IncludeInTOC - public override string ToString() - { - return String.Format("{0:D2} - {1}", Index, Name); - } - } + public string AltMultiUnitWording => LazyLoad(ref _AltMultiUnitWording, "@AltMultiUnitWording"); + #endregion IncludeInTOC + public override string ToString() => $"{Index:D2} - {Name}"; + } #endregion #region DocStyleList [TypeConverter(typeof(vlnListConverter))] @@ -710,53 +448,35 @@ namespace VEPROMS.CSLA.Library public Layout() : base() { } #region TopMargin private LazyLoad _TopMargin; - [Category("Layout")] - [DisplayName("Top Margin on Printed Page")] - [Description("Top Margin on Printed Page")] + [Category("Layout")] + [DisplayName("Top Margin on Printed Page")] + [Description("Top Margin on Printed Page")] - // The top point of the printed page to start printing the step text (or section number/title) - public float? TopMargin - { - get - { - return LazyLoad(ref _TopMargin, "@TopMargin"); - } - } - #endregion - #region FooterLength - private LazyLoad _FooterLength; - [Category("Location")] - [DisplayName("Number of lines required for footer")] - [Description("Number of lines required for footer")] + // The top point of the printed page to start printing the step text (or section number/title) + public float? TopMargin => LazyLoad(ref _TopMargin, "@TopMargin"); + #endregion + #region FooterLength + private LazyLoad _FooterLength; + [Category("Location")] + [DisplayName("Number of lines required for footer")] + [Description("Number of lines required for footer")] - // space to reserve if needed for bottom page messages (ex: continue message) - public float? FooterLength - { - get - { - return LazyLoad(ref _FooterLength, "@FooterLength"); - } - } - #endregion - #region ChangeBarAdjustment - // B2023-052: Beaver Valley - Inconsistent change bar location - private LazyLoad _AbsChgBarAdj; - [Category("Location")] - [DisplayName("Absolute change bar adjustment for margin differences")] - [Description("Absolute change bar adjustment for margin differences")] + // space to reserve if needed for bottom page messages (ex: continue message) + public float? FooterLength => LazyLoad(ref _FooterLength, "@FooterLength"); + #endregion + #region ChangeBarAdjustment + // B2023-052: Beaver Valley - Inconsistent change bar location + private LazyLoad _AbsChgBarAdj; + [Category("Location")] + [DisplayName("Absolute change bar adjustment for margin differences")] + [Description("Absolute change bar adjustment for margin differences")] - // when AbsoluteFixedChangeColumn flag is used it is from the LeftMargin. If a unique section has a different LeftMarge define, change bars in that section will not be located at the same location as the other sections. This allows for an adjustment to the change bar location to match the other sections - public float? AbsChgBarAdj - { - get - { - return LazyLoad(ref _AbsChgBarAdj, "@AbsChgBarAdj"); - } - } - #endregion ChangeBarAdjustment + // when AbsoluteFixedChangeColumn flag is used it is from the LeftMargin. If a unique section has a different LeftMarge define, change bars in that section will not be located at the same location as the other sections. This allows for an adjustment to the change bar location to match the other sections + public float? AbsChgBarAdj => LazyLoad(ref _AbsChgBarAdj, "@AbsChgBarAdj"); + #endregion ChangeBarAdjustment - #region LeftMargin - private LazyLoad _LeftMargin; + #region LeftMargin + private LazyLoad _LeftMargin; [Category("Location")] [DisplayName("Size of left margin")] [Description("Size of left margin")] @@ -834,86 +554,56 @@ namespace VEPROMS.CSLA.Library #region PageWidth private LazyLoad _PageWidth; - [Category("Location")] - [DisplayName("Width of Page")] - [Description("Width of Page")] + [Category("Location")] + [DisplayName("Width of Page")] + [Description("Width of Page")] - // width of the printed page from the LeftMargin (defines the Right Margin of the section) - public float? PageWidth - { - get - { - return LazyLoad(ref _PageWidth, "@PageWidth"); - } - } - #endregion PageWidth + // width of the printed page from the LeftMargin (defines the Right Margin of the section) + public float? PageWidth => LazyLoad(ref _PageWidth, "@PageWidth"); + #endregion PageWidth - #region MSWordXAdj - private LazyLoad _MSWordXAdj; - [Category("Location")] - [DisplayName("MSWord X Adjustment")] - [Description("X Placement of PDF during Print")] + #region MSWordXAdj + private LazyLoad _MSWordXAdj; + [Category("Location")] + [DisplayName("MSWord X Adjustment")] + [Description("X Placement of PDF during Print")] - // used for landscape Word sections, adjusts the Horizontal position on the printed page - public float? MSWordXAdj - { - get - { - return LazyLoad(ref _MSWordXAdj, "@MSWordXAdj"); - } - } - #endregion MSWordXAdj + // used for landscape Word sections, adjusts the Horizontal position on the printed page + public float? MSWordXAdj => LazyLoad(ref _MSWordXAdj, "@MSWordXAdj"); + #endregion MSWordXAdj - #region MSWordYAdj - private LazyLoad _MSWordYAdj; - [Category("Location")] - [DisplayName("MSWord Y Adjustment")] - [Description("Y Placement of PDF during Print")] + #region MSWordYAdj + private LazyLoad _MSWordYAdj; + [Category("Location")] + [DisplayName("MSWord Y Adjustment")] + [Description("Y Placement of PDF during Print")] - // used for landscape Word sections, adjusts the Vertical position on the printed page - public float? MSWordYAdj - { - get - { - return LazyLoad(ref _MSWordYAdj, "@MSWordYAdj"); - } - } - #endregion MSWordYAdj + // used for landscape Word sections, adjusts the Vertical position on the printed page + public float? MSWordYAdj => LazyLoad(ref _MSWordYAdj, "@MSWordYAdj"); + #endregion MSWordYAdj - #region SectionMacro - private LazyLoad _SectionMacro; - [Category("Extras")] - [DisplayName("Section Macro")] - [Description("Section Macro Prints With Title")] + #region SectionMacro + private LazyLoad _SectionMacro; + [Category("Extras")] + [DisplayName("Section Macro")] + [Description("Section Macro Prints With Title")] - // will print a defined print macro with the section title. - // (ex. Westinghouse Alarms format will print a solid line before the section title - // for the "Line Above Section Title" section style) - public string SectionMacro - { - get - { - return LazyLoad(ref _SectionMacro, "@SectionMacro"); - } - } - #endregion SectionMacro + // will print a defined print macro with the section title. + // (ex. Westinghouse Alarms format will print a solid line before the section title + // for the "Line Above Section Title" section style) + public string SectionMacro => LazyLoad(ref _SectionMacro, "@SectionMacro"); + #endregion SectionMacro - #region CenterToStepThenPage - [Category("Layout")] + #region CenterToStepThenPage + [Category("Layout")] [Description("CenterToStepThenPage")] // centering position of Tables and Figures is calulated first with repect to the table or figure width, then that positionm is centered with respect the printable page width and left margin private LazyLoad _CenterToStepThenPage; - public bool CenterToStepThenPage - { - get - { - return LazyLoad(ref _CenterToStepThenPage, "@CenterToStepThenPage"); - } - } - #endregion CenterToStepThenPage - } + public bool CenterToStepThenPage => LazyLoad(ref _CenterToStepThenPage, "@CenterToStepThenPage"); + #endregion CenterToStepThenPage + } #endregion Layout #region SectTopWcnTraining @@ -924,64 +614,40 @@ namespace VEPROMS.CSLA.Library public SectTop() : base() { } #region Font private VE_Font _Font; - [Category("Font")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return (_Font == null) ? _Font = new VE_Font(XmlNode) : _Font; - } - } - #endregion - #region Margin - private LazyLoad _Margin; - [Category("Section Continue Msg")] - [DisplayName("Margin for Section top msg")] - [Description("Margin for Section top msg")] + [Category("Font")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + #endregion + #region Margin + private LazyLoad _Margin; + [Category("Section Continue Msg")] + [DisplayName("Margin for Section top msg")] + [Description("Margin for Section top msg")] - // used to position Responsibility text for Wolf Creek Training format - public float? Margin - { - get - { - return LazyLoad(ref _Margin, "@Margin"); - } - } - #endregion Margin + // used to position Responsibility text for Wolf Creek Training format + public float? Margin => LazyLoad(ref _Margin, "@Margin"); + #endregion Margin - #region MaxLen - private LazyLoad _MaxLen; - [Category("Section Continue Msg")] - [DisplayName("MaxLen for text within the column")] - [Description("MaxLen for text within the column")] + #region MaxLen + private LazyLoad _MaxLen; + [Category("Section Continue Msg")] + [DisplayName("MaxLen for text within the column")] + [Description("MaxLen for text within the column")] - // the maxium length of Responsibility text (Wolf Creek Training format) - public int? MaxLen - { - get - { - return LazyLoad(ref _MaxLen, "@MaxLen"); - } - } - #endregion MaxLen - #region Message - private LazyLoad _Message; - [Category("Continue Msg")] - [DisplayName("Section Top Continue Msg")] - [Description("Section Top Continue Msg")] + // the maxium length of Responsibility text (Wolf Creek Training format) + public int? MaxLen => LazyLoad(ref _MaxLen, "@MaxLen"); + #endregion MaxLen + #region Message + private LazyLoad _Message; + [Category("Continue Msg")] + [DisplayName("Section Top Continue Msg")] + [Description("Section Top Continue Msg")] - // top continue message used only for Wolf Creek Training format - public string Message - { - get - { - return LazyLoad(ref _Message, "@Message"); - } - } - #endregion Message - } + // top continue message used only for Wolf Creek Training format + public string Message => LazyLoad(ref _Message, "@Message"); + #endregion Message + } #endregion SectTopWcnTraining #region ContinueAll @@ -993,44 +659,20 @@ namespace VEPROMS.CSLA.Library public Continue() : base() { } #region Font private VE_Font _Font; - [Category("Continue Msg")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return (_Font == null ? _Font = new VE_Font(base.XmlNode) : _Font); - } - } - #endregion - #region SubElements - private Top _Top; - public Top Top - { - get - { - return (_Top == null? _Top = new Top(SelectSingleNode("Top")): _Top); - } - } - private Bottom _Bottom; - public Bottom Bottom - { - get - { - return (_Bottom == null ? _Bottom = new Bottom(SelectSingleNode("Bottom")) : _Bottom); - } - } - private SectionTitle _SectionTitle; - public SectionTitle SectionTitle - { - get - { - return (_SectionTitle == null ? _SectionTitle = new SectionTitle(SelectSingleNode("SectionTitle")) : _SectionTitle); - } - } - #endregion - } + [Category("Continue Msg")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(base.XmlNode)); + #endregion + #region SubElements + private Top _Top; + public Top Top => _Top ?? (_Top = new Top(SelectSingleNode("Top"))); + private Bottom _Bottom; + public Bottom Bottom => _Bottom ?? (_Bottom = new Bottom(SelectSingleNode("Bottom"))); + private SectionTitle _SectionTitle; + public SectionTitle SectionTitle => _SectionTitle ?? (_SectionTitle = new SectionTitle(SelectSingleNode("SectionTitle"))); + #endregion + } #endregion #region Top [TypeConverter(typeof(ExpandableObjectConverter))] @@ -1040,138 +682,86 @@ namespace VEPROMS.CSLA.Library public Top() : base() { } #region Font private VE_Font _Font; - [Category("Font")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return (_Font == null) ? _Font = new VE_Font(XmlNode) : _Font; - } - } - #endregion - #region Margin - private LazyLoad _Margin; - [Category("Continue Msg")] - [DisplayName("Margin for top msg")] - [Description("Margin for top msg")] + [Category("Font")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + #endregion + #region Margin + private LazyLoad _Margin; + [Category("Continue Msg")] + [DisplayName("Margin for top msg")] + [Description("Margin for top msg")] - //value added to the left margin when calculating the center point of a top continue message. - public float? Margin - { - get - { - return LazyLoad(ref _Margin, "@Margin"); - } - } - #endregion Margin + //value added to the left margin when calculating the center point of a top continue message. + public float? Margin => LazyLoad(ref _Margin, "@Margin"); + #endregion Margin - #region RowOverride - // C2019-044 put in for Barakah Single Column format - // specify the row to put the top continue message - // this allows us to put the Top Continue Message on the same row as the checkoff (initials) header - per their writer's guide - private LazyLoad _RowOverride; - [Category("Continue Msg")] - [DisplayName("Top msg on specific row")] - [Description("Top msg on specific row")] - public float? RowOverride - { - get - { - return LazyLoad(ref _RowOverride, "@RowOverride"); - } - } - #endregion + #region RowOverride + // C2019-044 put in for Barakah Single Column format + // specify the row to put the top continue message + // this allows us to put the Top Continue Message on the same row as the checkoff (initials) header - per their writer's guide + private LazyLoad _RowOverride; + [Category("Continue Msg")] + [DisplayName("Top msg on specific row")] + [Description("Top msg on specific row")] + public float? RowOverride => LazyLoad(ref _RowOverride, "@RowOverride"); + #endregion - #region UseStepTabs - private LazyLoad _UseStepTabs; - [Category("Continue Msg")] - [DisplayName("Flag to use step tabs")] - [Description("Flag to use step tabs")] + #region UseStepTabs + private LazyLoad _UseStepTabs; + [Category("Continue Msg")] + [DisplayName("Flag to use step tabs")] + [Description("Flag to use step tabs")] - // added for Comanche Peak will print out step tabs as a top comtinue message. - public bool UseStepTabs - { - get - { - return LazyLoad(ref _UseStepTabs, "@UseStepTabs"); - } - } - #endregion UseStepTabs + // added for Comanche Peak will print out step tabs as a top comtinue message. + public bool UseStepTabs => LazyLoad(ref _UseStepTabs, "@UseStepTabs"); + #endregion UseStepTabs - #region HLS - private LazyLoad _HLS; - [Category("Continue Msg")] - [DisplayName("Include HLS in top continue msg")] - [Description("Include HLS in top continue msg")] + #region HLS + private LazyLoad _HLS; + [Category("Continue Msg")] + [DisplayName("Include HLS in top continue msg")] + [Description("Include HLS in top continue msg")] - // include the High Level Step in the top continue message - // - see DoTopContinueMsg in VlnParagraph for details - // set to "1" will use high level step tab and text - // set to "4" the high level step text is the section title, appears when fist level sub-step breaks - // set to "7" similar logic as "4" but for Vogtle Main Control Room alarms but use high level step text - // set to "6" handle when break occures on Caution/Note - // set to "3" special logic for Calvert Cliffs Alarms (the two column part) - public int? HLS - { - get - { - return LazyLoad(ref _HLS, "@HLS"); - } - } - #endregion HLS + // include the High Level Step in the top continue message + // - see DoTopContinueMsg in VlnParagraph for details + // set to "1" will use high level step tab and text + // set to "4" the high level step text is the section title, appears when fist level sub-step breaks + // set to "7" similar logic as "4" but for Vogtle Main Control Room alarms but use high level step text + // set to "6" handle when break occures on Caution/Note + // set to "3" special logic for Calvert Cliffs Alarms (the two column part) + public int? HLS => LazyLoad(ref _HLS, "@HLS"); + #endregion HLS - #region PlaceAtLeftMargin - private LazyLoad _PlaceAtLeftMargin; // F2019-033 only use the Left Margin plus any Top message margin - [Category("Continue Msg")] - [DisplayName("Flag to position at left margin")] - [Description("Flag to position at left margin")] + #region PlaceAtLeftMargin + private LazyLoad _PlaceAtLeftMargin; // F2019-033 only use the Left Margin plus any Top message margin + [Category("Continue Msg")] + [DisplayName("Flag to position at left margin")] + [Description("Flag to position at left margin")] - // position the top continue message with respect only to the left margin - public bool PlaceAtLeftMargin - { - get - { - return LazyLoad(ref _PlaceAtLeftMargin, "@PlaceAtLeftMargin"); - } - } - #endregion PlaceAtLeftMargin + // position the top continue message with respect only to the left margin + public bool PlaceAtLeftMargin => LazyLoad(ref _PlaceAtLeftMargin, "@PlaceAtLeftMargin"); + #endregion PlaceAtLeftMargin - #region Message - private LazyLoad _RemoveBullet; - public bool RemoveBullet // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. - { - get - { - return LazyLoad(ref _RemoveBullet, "@RemoveBullet"); - } - } + #region Message + private LazyLoad _RemoveBullet; + public bool RemoveBullet // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. +=> LazyLoad(ref _RemoveBullet, "@RemoveBullet"); - private LazyLoad _DontIncludeRNOTabIfHasAERParent; - public bool DontIncludeRNOTabIfHasAERParent // F2026-002: Vogtle Units 3&4 Top Continue Message. - { - get - { - return LazyLoad(ref _DontIncludeRNOTabIfHasAERParent, "@DontIncludeRNOTabIfHasAERParent"); - } - } + private LazyLoad _DontIncludeRNOTabIfHasAERParent; + public bool DontIncludeRNOTabIfHasAERParent // F2026-002: Vogtle Units 3&4 Top Continue Message. +=> LazyLoad(ref _DontIncludeRNOTabIfHasAERParent, "@DontIncludeRNOTabIfHasAERParent"); - private LazyLoad _Message; - [Category("Continue Msg")] - [DisplayName("Top Continue Msg")] - [Description("Top Continue Msg")] + private LazyLoad _Message; + [Category("Continue Msg")] + [DisplayName("Top Continue Msg")] + [Description("Top Continue Msg")] - // the top continue message string - may caontain special formatting items - see DoTopContinueMsg in vlnParagraph for different format settings - public string Message - { - get - { - return LazyLoad(ref _Message, "@Message"); - } - } - #endregion Message - } + // the top continue message string - may caontain special formatting items - see DoTopContinueMsg in vlnParagraph for different format settings + public string Message => LazyLoad(ref _Message, "@Message"); + #endregion Message + } #endregion Top @@ -1183,120 +773,72 @@ namespace VEPROMS.CSLA.Library public Bottom() : base() { } #region Font private VE_Font _Font; - [Category("Font")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return (_Font == null) ? _Font = new VE_Font(XmlNode) : _Font; - } - } - #endregion - #region Margin - private LazyLoad _Margin; - [Category("Continue Msg")] - [DisplayName("Margin for bottom msg")] - [Description("Margin for bottom msg")] + [Category("Font")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + #endregion + #region Margin + private LazyLoad _Margin; + [Category("Continue Msg")] + [DisplayName("Margin for bottom msg")] + [Description("Margin for bottom msg")] - // horitzontal position of the bottom continue message from the left margin - public float? Margin - { - get - { - return LazyLoad(ref _Margin, "@Margin"); - } - } - #endregion Margin + // horitzontal position of the bottom continue message from the left margin + public float? Margin => LazyLoad(ref _Margin, "@Margin"); + #endregion Margin - #region MarginR BGE - private LazyLoad _MarginR; - [Category("Continue Msg")] - [DisplayName("Margin for bottom msg RNO Column (if in both columns)")] - [Description("Margin for bottom msg RNO Column (if in both columns)")] + #region MarginR BGE + private LazyLoad _MarginR; + [Category("Continue Msg")] + [DisplayName("Margin for bottom msg RNO Column (if in both columns)")] + [Description("Margin for bottom msg RNO Column (if in both columns)")] - // horitzontal position from the left margin for a RNO bottom continue message - public float? MarginR - { - get - { - return LazyLoad(ref _MarginR, "@MarginR"); - } - } - #endregion MarginR BGE + // horitzontal position from the left margin for a RNO bottom continue message + public float? MarginR => LazyLoad(ref _MarginR, "@MarginR"); + #endregion MarginR BGE - #region Location - [Category("Continue Msg")] + #region Location + [Category("Continue Msg")] [Description("Bottom Continue Location")] private LazyLoad _Location; - // location of the bottom continue message - // E_ContBottomLoc list (ENum.cs): - // EndOfText = 0, - // BtwnTextAndBottom = 1, - // BottomOfPage = 2, - // BelowBottom1 = 3, - // BottomWithFooter = 4, - added for BGE for Alarms. This puts continue message on bottom AND if in CONDITION/RESPONSE table, at bottom of both columns. - // EndOfText2 = 5, - // BtwnTextAndBottom2 = 6 - Added for BGE, their continue message was a line or so too far down the page + // location of the bottom continue message + // E_ContBottomLoc list (ENum.cs): + // EndOfText = 0, + // BtwnTextAndBottom = 1, + // BottomOfPage = 2, + // BelowBottom1 = 3, + // BottomWithFooter = 4, - added for BGE for Alarms. This puts continue message on bottom AND if in CONDITION/RESPONSE table, at bottom of both columns. + // EndOfText2 = 5, + // BtwnTextAndBottom2 = 6 - Added for BGE, their continue message was a line or so too far down the page - public E_ContBottomLoc? Location - { - get - { - return LazyLoad(ref _Location, "@Location"); - } - } + public E_ContBottomLoc? Location => LazyLoad(ref _Location, "@Location"); - // flag for cases where step text was printing on top of the bottom continue messsage due to how a step was paginated - put in for Farley - private LazyLoad _NoOverrideSpace; - public bool NoOverrideSpace - { - get - { - return LazyLoad(ref _NoOverrideSpace, "@NoOverrideSpace"); - } - } + // flag for cases where step text was printing on top of the bottom continue messsage due to how a step was paginated - put in for Farley + private LazyLoad _NoOverrideSpace; + public bool NoOverrideSpace => LazyLoad(ref _NoOverrideSpace, "@NoOverrideSpace"); - // Location Adjustment of the calculated vertical position of the bottom continue message (from Location setting) - private LazyLoad _LocAdj; - public int? LocAdj - { - get - { + // Location Adjustment of the calculated vertical position of the bottom continue message (from Location setting) + private LazyLoad _LocAdj; + public int? LocAdj => LazyLoad(ref _LocAdj, "@LocAdj"); + #endregion Location - return LazyLoad(ref _LocAdj, "@LocAdj"); - } - } - #endregion Location + #region Message + private LazyLoad _RemoveBullet; + public bool RemoveBullet // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. +=> LazyLoad(ref _RemoveBullet, "@RemoveBullet"); - #region Message - private LazyLoad _RemoveBullet; - public bool RemoveBullet // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. - { - get - { - return LazyLoad(ref _RemoveBullet, "@RemoveBullet"); - } - } + private LazyLoad _Message; + [Category("Continue Msg")] + [DisplayName("Bottom Continue Msg")] + [Description("Bottom Continue Msg")] - private LazyLoad _Message; - [Category("Continue Msg")] - [DisplayName("Bottom Continue Msg")] - [Description("Bottom Continue Msg")] - - //the bottom continue message string - may caontain special formatting items - //- see DoBottomContinueMsg in vlnParagraph for different format settings - public string Message - { - get - { - return LazyLoad(ref _Message, "@Message"); - } - } - #endregion Message - } + //the bottom continue message string - may caontain special formatting items + //- see DoBottomContinueMsg in vlnParagraph for different format settings + public string Message => LazyLoad(ref _Message, "@Message"); + #endregion Message + } #endregion Bottom #region SectionTitle @@ -1307,20 +849,14 @@ namespace VEPROMS.CSLA.Library public SectionTitle() : base() { } #region AppendToTitle private LazyLoad _AppendToTitle; - [Category("Section Title Continue Msg")] - [DisplayName("AppendToTitle")] - [Description("Append Text to Section Title For Continue Msg")] + [Category("Section Title Continue Msg")] + [DisplayName("AppendToTitle")] + [Description("Append Text to Section Title For Continue Msg")] - // continue message to add to the section title - public string AppendToTitle - { - get - { - return LazyLoad(ref _AppendToTitle, "@AppendToTitle"); - } - } - #endregion AppendToTitle - } + // continue message to add to the section title + public string AppendToTitle => LazyLoad(ref _AppendToTitle, "@AppendToTitle"); + #endregion AppendToTitle + } #endregion //SectionTitle - continue setting #endregion ContinueAll @@ -1332,19 +868,13 @@ namespace VEPROMS.CSLA.Library public End() : base() { } #region Font private VE_Font _Font; - [Category("End Msg")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return (_Font == null ? _Font = new VE_Font(XmlNode) : _Font); - } - } - #endregion - #region Flag - private LazyLoad _Flag; + [Category("End Msg")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + #endregion + #region Flag + private LazyLoad _Flag; [Category("End Msg")] [DisplayName("End Msg Exists")] [Description("End Msg Exists")] @@ -1361,48 +891,24 @@ namespace VEPROMS.CSLA.Library #region Message private LazyLoad _Message; - [Category("End Msg")] - [DisplayName("End Message")] - [Description("End Message")] + [Category("End Msg")] + [DisplayName("End Message")] + [Description("End Message")] - // End Message Text - public string Message - { - get - { - return LazyLoad(ref _Message, "@Message"); - } - } + // End Message Text + public string Message => LazyLoad(ref _Message, "@Message"); - public string FixedMessage - { - get - { - return Message == null ? null : Message.Replace("\n","\r\n").Replace(@"{par}","\r\n"); - } - } + public string FixedMessage => Message?.Replace("\n", "\r\n").Replace(@"{par}", "\r\n"); - // amount of space from the left margin to print the End Message - private LazyLoad _Margin; - public float? Margin - { - get - { - return LazyLoad(ref _Margin, "@Margin"); - } - } + // amount of space from the left margin to print the End Message + private LazyLoad _Margin; + public float? Margin => LazyLoad(ref _Margin, "@Margin"); - // print the end message at the end of each sub-section - private LazyLoad _EndMessageOnEachSubSection; - public bool EndMessageOnEachSubSection - { - get - { - return LazyLoad(ref _EndMessageOnEachSubSection, "@EndMessageOnEachSubSection"); - } - } - #endregion Message - } + // print the end message at the end of each sub-section + private LazyLoad _EndMessageOnEachSubSection; + public bool EndMessageOnEachSubSection => LazyLoad(ref _EndMessageOnEachSubSection, "@EndMessageOnEachSubSection"); + #endregion Message + } #endregion End #region Final @@ -1412,19 +918,13 @@ namespace VEPROMS.CSLA.Library public Final(XmlNode xmlNode) : base(xmlNode) { } public Final() : base() { } private LazyLoad _Message; - [Category("Final Msg")] - [DisplayName("Final Message")] - [Description("Final Message")] - - // Final Message text to be printed on last page of procedure - public string Message - { - get - { - return LazyLoad(ref _Message, "@Message"); - } - } - } + [Category("Final Msg")] + [DisplayName("Final Message")] + [Description("Final Message")] + + // Final Message text to be printed on last page of procedure + public string Message => LazyLoad(ref _Message, "@Message"); + } #endregion Final #region StructureStyle @@ -1438,36 +938,24 @@ namespace VEPROMS.CSLA.Library [Description("Where Used")] private LazyLoad _Where; - // where with repect to the section is this DocStyle/PageList relationship used: - // UseOnAllPages (all pages of the section), UseOnFirstPage (only the first page of the section), - // UseOnAllButFirstPage (all except for the first page of the section). - // Note that when UseOnFirstPage is used, it but reference a DocStyle (IndexOtherThanFirstPage) - // that uses UseOnAllButFirstPage. + // where with repect to the section is this DocStyle/PageList relationship used: + // UseOnAllPages (all pages of the section), UseOnFirstPage (only the first page of the section), + // UseOnAllButFirstPage (all except for the first page of the section). + // Note that when UseOnFirstPage is used, it but reference a DocStyle (IndexOtherThanFirstPage) + // that uses UseOnAllButFirstPage. - public E_DocStyleUse? Where - { - get - { - return LazyLoad(ref _Where, "@Where"); - } - } - #endregion Where + public E_DocStyleUse? Where => LazyLoad(ref _Where, "@Where"); + #endregion Where - #region Style - [Category("Structure Style")] + #region Style + [Category("Structure Style")] [Description("Style")] // allow us to identify a specialized type of section (Table of Contents, Foldout Page, etc) as well as other unique formatting that deviates from the normal formatting/data entry of the procedure. See "E_DocStructStyle" in VEPROMS.CSLA.Library\ENums.cs for alist of the possible flags and descriptions. private LazyLoad _Style; - public E_DocStructStyle? Style - { - get - { - return LazyLoad(ref _Style, "@Style"); - } - } - #endregion Style - } + public E_DocStructStyle? Style => LazyLoad(ref _Style, "@Style"); + #endregion Style + } #endregion StructureStyle #endregion DocStyleAll } diff --git a/PROMS/VEPROMS.CSLA.Library/Format/ENums.cs b/PROMS/VEPROMS.CSLA.Library/Format/ENums.cs index 5d0a9ff5..2653103b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/ENums.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/ENums.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; -using System.Xml; -using System.ComponentModel; namespace VEPROMS.CSLA.Library { diff --git a/PROMS/VEPROMS.CSLA.Library/Format/EPFormatFile.cs b/PROMS/VEPROMS.CSLA.Library/Format/EPFormatFile.cs index 1d75f875..d881cdc9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/EPFormatFile.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/EPFormatFile.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.ComponentModel; using System.Xml; using System.Linq; @@ -32,54 +31,27 @@ namespace VEPROMS.CSLA.Library private LazyLoad _Name; [DisplayName("Name")] [Description("EP Viewer File Name")] - public string Name - { - get - { - return LazyLoad(ref _Name, "@Name"); - } - } + public string Name => LazyLoad(ref _Name, "@Name"); // Name of the EP Viewer Format File private LazyLoad _Description; [DisplayName("Description")] [Description("EP Viewer Description")] - public string Description - { - get - { - return LazyLoad(ref _Description, "@Description"); - } - } + public string Description => LazyLoad(ref _Description, "@Description"); // Id of Annotation Type Associated with this file private LazyLoad _AnnotationTypeID; [DisplayName("AnnotationTypeID")] [Description("Id of Annotation Type Associated with this file")] - public int? AnnotationTypeID - { - get - { - return LazyLoad(ref _AnnotationTypeID, "@AnnotationTypeID"); - } - } + public int? AnnotationTypeID => LazyLoad(ref _AnnotationTypeID, "@AnnotationTypeID"); // Return Name of Annotation that EP Format File is Attached to - public string AnnotationName() - { - return AnnotationTypeInfo.Get((int) AnnotationTypeID).Name; - } + public string AnnotationName() => AnnotationTypeInfo.Get((int)AnnotationTypeID).Name; //if xml value is blank, should element export? //defaults to true private LazyLoad _exportblank; [DisplayName("exportblank")] [Description("if xml value is blank, should element export?")] - public bool exportblank - { - get - { - return LazyLoad(ref _exportblank, "@exportblank"); - } - } + public bool exportblank => LazyLoad(ref _exportblank, "@exportblank"); // returns a list of fields that are defined in the EP format's structure private EPFields _FieldList; public EPFields FieldList @@ -141,8 +113,10 @@ namespace VEPROMS.CSLA.Library { if (dr.Read()) { - XmlDocument xd = new XmlDocument(); - xd.XmlResolver = null; + XmlDocument xd = new XmlDocument + { + XmlResolver = null + }; xd.LoadXml(dr.GetString("Data")); return xd; } @@ -255,21 +229,9 @@ namespace VEPROMS.CSLA.Library public EPField(XmlNode xmlNode) : base(xmlNode) { } public EPField() : base() { } private LazyLoad _name; - public string name - { - get - { - return LazyLoad(ref _name, "@name"); - } - } + public string name => LazyLoad(ref _name, "@name"); private LazyLoad _type; - public string type - { - get - { - return LazyLoad(ref _type, "@type"); - } - } + public string type => LazyLoad(ref _type, "@type"); private LazyLoad _label; public string label { @@ -284,22 +246,10 @@ namespace VEPROMS.CSLA.Library } } private LazyLoad _text; - public string text - { - get - { - return LazyLoad(ref _text, "@text"); - } - } + public string text => LazyLoad(ref _text, "@text"); //roid of group item that individual sub-items will be the choices for the list/combobox for ROSINGLE and ROMULTI private LazyLoad _rosource; - public string rosource - { - get - { - return LazyLoad(ref _rosource, "@rosource"); - } - } + public string rosource => LazyLoad(ref _rosource, "@rosource"); //the columns in the RO that will be included in the exports private LazyLoad _returncols; public List returncols() diff --git a/PROMS/VEPROMS.CSLA.Library/Format/PageStyles.cs b/PROMS/VEPROMS.CSLA.Library/Format/PageStyles.cs index a97edf71..7de782d0 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/PageStyles.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/PageStyles.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; using System.Xml; @@ -23,44 +20,23 @@ namespace VEPROMS.CSLA.Library #region Business Methods // description to associate with a DocStyle private LazyLoad _Name; - [DisplayName("Name")] - [Description("Page Style Name")] - public string Name - { - get - { - return LazyLoad(ref _Name, "@Name"); - } - } + [DisplayName("Name")] + [Description("Page Style Name")] + public string Name => LazyLoad(ref _Name, "@Name"); - // a unuque number that is referenced from the DocStyles - private LazyLoad _Index; - [DisplayName("Index")] - [Description("Page Style Index")] - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } + // a unuque number that is referenced from the DocStyles + private LazyLoad _Index; + [DisplayName("Index")] + [Description("Page Style Index")] + public int? Index => LazyLoad(ref _Index, "@Index"); - private PageItems _PageItems; - public PageItems PageItems - { - get - { - return (_PageItems == null)? _PageItems = new PageItems(SelectNodes("Item")): _PageItems; - } - } - #endregion - #region Override ToString - public override string ToString() - { - return string.Format("{0:D2} - {1}", Index, Name); - } - #endregion - } + private PageItems _PageItems; + public PageItems PageItems => _PageItems ?? (_PageItems = new PageItems(SelectNodes("Item"))); + #endregion + #region Override ToString + public override string ToString() => string.Format("{0:D2} - {1}", Index, Name); + #endregion + } #endregion #region PageItems [TypeConverter(typeof(vlnListConverter))] @@ -79,192 +55,91 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private VE_Font _Font; - [Category("Font")] - [DisplayName("Font")] - [Description("Font")] - public VE_Font Font - { - get - { - return (_Font == null) ?_Font = new VE_Font(XmlNode): _Font; - } - } - private RelatedItem _RelatedItem; - public RelatedItem RelatedItem - { - get - { - return (_RelatedItem == null) ? _RelatedItem = new RelatedItem(SelectSingleNode("RelatedItem")) : _RelatedItem; - } - } + [Category("Font")] + [DisplayName("Font")] + [Description("Font")] + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + private RelatedItem _RelatedItem; + public RelatedItem RelatedItem => _RelatedItem ?? (_RelatedItem = new RelatedItem(SelectSingleNode("RelatedItem"))); - // this can be an actual token, in curly braces, that dynamically gets replaced with information, or just plain text - private LazyLoad _Token; - [Category("Content")] - [DisplayName("Content")] - [Description("Item Content")] - public string Token - { - get - { - return LazyLoad(ref _Token, "@Token"); - } - } + // this can be an actual token, in curly braces, that dynamically gets replaced with information, or just plain text + private LazyLoad _Token; + [Category("Content")] + [DisplayName("Content")] + [Description("Item Content")] + public string Token => LazyLoad(ref _Token, "@Token"); - // the row on the page to place the Item - private LazyLoad _Row; - [Category("Location")] - [DisplayName("Vertical Position")] - [Description("Vertical Position")] - public float? Row - { - get - { - return LazyLoad(ref _Row, "@Row"); - } - } + // the row on the page to place the Item + private LazyLoad _Row; + [Category("Location")] + [DisplayName("Vertical Position")] + [Description("Vertical Position")] + public float? Row => LazyLoad(ref _Row, "@Row"); - // the column on the page to place the Item - private LazyLoad _Col; - [Category("Location")] - [DisplayName("Horizontal Position")] - [Description("Horizontal Position")] - public float? Col - { - get - { - return LazyLoad(ref _Col, "@Col"); - } - } + // the column on the page to place the Item + private LazyLoad _Col; + [Category("Location")] + [DisplayName("Horizontal Position")] + [Description("Horizontal Position")] + public float? Col => LazyLoad(ref _Col, "@Col"); - // the justification at the Col position in which to print the Token information - private LazyLoad _Justify; - public E_Justify? Justify - { - get - { - return LazyLoad(ref _Justify, "@Justify"); - } - } + // the justification at the Col position in which to print the Token information + private LazyLoad _Justify; + public E_Justify? Justify => LazyLoad(ref _Justify, "@Justify"); - //run the PROMS Replace Words logic on the resulting text of Token - private LazyLoad _RepWords; // F2021-053: Do replace words in page list - public bool RepWords - { - get - { - return LazyLoad(ref _RepWords, "@RepWords"); - } - } + //run the PROMS Replace Words logic on the resulting text of Token + private LazyLoad _RepWords; // F2021-053: Do replace words in page list + public bool RepWords => LazyLoad(ref _RepWords, "@RepWords"); - //Flag to tell PROMS to get the alarm value information based on the specified Child applicability - private LazyLoad _ROLkUpMatch; // C2021-065 (BNPP Alarms format) - public bool ROLkUpMatch - { - get - { - return LazyLoad(ref _ROLkUpMatch, "@ROLkUpMatch"); - } - } + //Flag to tell PROMS to get the alarm value information based on the specified Child applicability + private LazyLoad _ROLkUpMatch; // C2021-065 (BNPP Alarms format) + public bool ROLkUpMatch => LazyLoad(ref _ROLkUpMatch, "@ROLkUpMatch"); - // Flag to specify if that PageStyle Item should be used in creating alarm point information - // for viewing in the PROMS step editor - // this information is displayed in a Note that it build on the fly when first opening an Alarm Point page - private LazyLoad _ROLkUpInEditor; // C2021-018 (BNPP Alarms format) - public bool ROLkUpInEditor - { - get - { - return LazyLoad(ref _ROLkUpInEditor, "@ROLkUpInEditor"); - } - } + // Flag to specify if that PageStyle Item should be used in creating alarm point information + // for viewing in the PROMS step editor + // this information is displayed in a Note that it build on the fly when first opening an Alarm Point page + private LazyLoad _ROLkUpInEditor; // C2021-018 (BNPP Alarms format) + public bool ROLkUpInEditor => LazyLoad(ref _ROLkUpInEditor, "@ROLkUpInEditor"); - // defines a maxium width before the resolved PSI token (procedure specific information) text is wrapped - // on to the next line - private LazyLoad _MaxWidth; - public int? MaxWidth - { - get - { - return (LazyLoad(ref _MaxWidth, "@MaxWidth")); - } - } + // defines a maxium width before the resolved PSI token (procedure specific information) text is wrapped + // on to the next line + private LazyLoad _MaxWidth; + public int? MaxWidth => LazyLoad(ref _MaxWidth, "@MaxWidth"); - // MaxWidth, above, flagged that, if there was more than 1 line, the topmargin would be adjusted by however - // many lines the PSI item contained (for wst alarms). The MaxWidthCurPage is used when that adjustment - // should not be made, the length of the PSI item is only relevant for the current page. - // (see AdjustTopMarginForMultiLinePageListItems variable and how it is used) - private LazyLoad _MaxWidthCurPage; - public int? MaxWidthCurPage - { - get - { - return (LazyLoad(ref _MaxWidthCurPage, "@MaxWidthCurPage")); - } - } + // MaxWidth, above, flagged that, if there was more than 1 line, the topmargin would be adjusted by however + // many lines the PSI item contained (for wst alarms). The MaxWidthCurPage is used when that adjustment + // should not be made, the length of the PSI item is only relevant for the current page. + // (see AdjustTopMarginForMultiLinePageListItems variable and how it is used) + private LazyLoad _MaxWidthCurPage; + public int? MaxWidthCurPage => LazyLoad(ref _MaxWidthCurPage, "@MaxWidthCurPage"); - // the resolved pagestype item font size will be reduce in order to fit within the defined width - private LazyLoad _FontShrinkAftLen; // F2021-066 & 070 (text len before shrinking font) - public int? FontShrinkAftLen - { - get - { - return (LazyLoad(ref _FontShrinkAftLen, "@FontShrinkAftLen")); - } - } + // the resolved pagestype item font size will be reduce in order to fit within the defined width + private LazyLoad _FontShrinkAftLen; // F2021-066 & 070 (text len before shrinking font) + public int? FontShrinkAftLen => LazyLoad(ref _FontShrinkAftLen, "@FontShrinkAftLen"); - // used in Alarm Point Table page style values with FontShrinkAftLen set, will display this message if the text cannot be shrunk enough (and be readable) to fit within the defined width - private LazyLoad _FontTooSmallMsg; // F2021-066 message if can't shrink enough - public string FontTooSmallMsg - { - get - { - return LazyLoad(ref _FontTooSmallMsg, "@FontTooSmallMsg"); - } - } + // used in Alarm Point Table page style values with FontShrinkAftLen set, will display this message if the text cannot be shrunk enough (and be readable) to fit within the defined width + private LazyLoad _FontTooSmallMsg; // F2021-066 message if can't shrink enough + public string FontTooSmallMsg => LazyLoad(ref _FontTooSmallMsg, "@FontTooSmallMsg"); - // F2023-039 allow to select text color of a pagelist line - // sets a text color for the page style Item - private LazyLoad _TextColor; - public string TextColor - { - get - { - return LazyLoad(ref _TextColor, "@TextColor"); - } - } + // F2023-039 allow to select text color of a pagelist line + // sets a text color for the page style Item + private LazyLoad _TextColor; + public string TextColor => LazyLoad(ref _TextColor, "@TextColor"); - // set to a string, will remove the matching string from the end - // F2023-112 Vogtle Units 3 & Backgrounds - trim the ending "-B" from the procedure number (used in title box of page header) - private LazyLoad _TrimEnding; - public string TrimEnding - { - get - { - return LazyLoad(ref _TrimEnding, "@TrimEnding"); - } - } - // C2025-033 to specify to print pagestyle item for a specific Child procedure - private LazyLoad _ChildNum; - public int? ChildNum - { - get - { - return (LazyLoad(ref _ChildNum, "@ChildNum")); - } - } + // set to a string, will remove the matching string from the end + // F2023-112 Vogtle Units 3 & Backgrounds - trim the ending "-B" from the procedure number (used in title box of page header) + private LazyLoad _TrimEnding; + public string TrimEnding => LazyLoad(ref _TrimEnding, "@TrimEnding"); + // C2025-033 to specify to print pagestyle item for a specific Child procedure + private LazyLoad _ChildNum; + public int? ChildNum => LazyLoad(ref _ChildNum, "@ChildNum"); - #endregion - #region Override ToString - public override string ToString() - { - //return string.Format("({0:D5},{1:D5}) - {2}",Row,Col,Token); - return Token; - } - public override string GetPDDisplayName() - { return string.Format("({0},{1})",Row,Col); } - #endregion - } + #endregion + #region Override ToString + public override string ToString() => Token; + public override string GetPDDisplayName() => string.Format("({0},{1})", Row, Col); + #endregion + } #endregion #region RelatedItem // RelatedItem was added to allow a PSI logical to have an associated PSI item, and if both are @@ -281,53 +156,29 @@ namespace VEPROMS.CSLA.Library // the name of the PSI logical token to check private LazyLoad _Token; - [Category("RelatedContent")] - [DisplayName("RelatedContent")] - [Description("Item RelatedContent")] - public string Token - { - get - { - return LazyLoad(ref _Token, "@Token"); - } - } + [Category("RelatedContent")] + [DisplayName("RelatedContent")] + [Description("Item RelatedContent")] + public string Token => LazyLoad(ref _Token, "@Token"); - // new Row value to use for PageStyle Item - private LazyLoad _Row; - [Category("Location")] - [DisplayName("Vertical Position")] - [Description("Vertical Position")] - public float? Row - { - get - { - return LazyLoad(ref _Row, "@Row"); - } - } + // new Row value to use for PageStyle Item + private LazyLoad _Row; + [Category("Location")] + [DisplayName("Vertical Position")] + [Description("Vertical Position")] + public float? Row => LazyLoad(ref _Row, "@Row"); - // new Col value to use for PageStyle Item - private LazyLoad _Col; - [Category("Location")] - [DisplayName("Horizontal Position")] - [Description("Horizontal Position")] - public float? Col - { - get - { - return LazyLoad(ref _Col, "@Col"); - } - } + // new Col value to use for PageStyle Item + private LazyLoad _Col; + [Category("Location")] + [DisplayName("Horizontal Position")] + [Description("Horizontal Position")] + public float? Col => LazyLoad(ref _Col, "@Col"); - // new Justify value to use for PageStyle Item - private LazyLoad _Justify; - public E_Justify? Justify - { - get - { - return LazyLoad(ref _Justify, "@Justify"); - } - } - #endregion - } + // new Justify value to use for PageStyle Item + private LazyLoad _Justify; + public E_Justify? Justify => LazyLoad(ref _Justify, "@Justify"); + #endregion + } #endregion } diff --git a/PROMS/VEPROMS.CSLA.Library/Format/PlantFormat.cs b/PROMS/VEPROMS.CSLA.Library/Format/PlantFormat.cs index 36631cf5..28704379 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/PlantFormat.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/PlantFormat.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Xml; using System.ComponentModel; using System.Drawing; @@ -11,9 +10,10 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class PlantFormat { - public PlantFormat(IFormatOrFormatInfo format, string config) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping config for future use / Debugging")] + public PlantFormat(IFormatOrFormatInfo format, string config) { - _MyFormat = format; + MyFormat = format; string str = null; if (format is Format) str = (format as Format).Config; else if (format is FormatInfo) str = (format as FormatInfo).Config; @@ -26,26 +26,21 @@ namespace VEPROMS.CSLA.Library { if (_FormatConfig == null) { - _FormatConfig = GetFormatConfig(_MyFormat); + _FormatConfig = GetFormatConfig(MyFormat); } return _FormatConfig; } set { _FormatConfig = value; } } - #region User Control of Format (UCF) - // User Control of Format allows a PROMS user to make modifications to a very limited set of format settings - // Variables in this region are not set in the format files. They are used only in the C# code + #region User Control of Format (UCF) + // User Control of Format allows a PROMS user to make modifications to a very limited set of format settings + // Variables in this region are not set in the format files. They are used only in the C# code - // when IgnoreUCF is true, get the original data, i.e.don't apply any UCF changes to it - private static bool _IgnoreUCF = true; // turn off reading in UCF values when getting format information - public static bool IgnoreUCF - { - get { return PlantFormat._IgnoreUCF; } - set { PlantFormat._IgnoreUCF = value; } - } + // when IgnoreUCF is true, get the original data, i.e.don't apply any UCF changes to it + public static bool IgnoreUCF { get; set; } = true; - #endregion //User Control of Format (UCF) - public static FormatConfig GetFormatConfig(IFormatOrFormatInfo format) + #endregion //User Control of Format (UCF) + public static FormatConfig GetFormatConfig(IFormatOrFormatInfo format) { FormatConfig fc = null; string str = null; @@ -54,19 +49,15 @@ namespace VEPROMS.CSLA.Library if (str != null && str != "") fc = FormatConfig.Get(str); return fc; } - private IFormatOrFormatInfo _MyFormat; - public IFormatOrFormatInfo MyFormat - { - get { return _MyFormat; } - set { _MyFormat = value; } - } - private vlnFormatDocument _XmlDoc; + + public IFormatOrFormatInfo MyFormat { get; set; } + private vlnFormatDocument _XmlDoc; internal vlnFormatDocument XmlDoc { get { if (_XmlDoc == null) - _XmlDoc = new vlnFormatDocument(_MyFormat); + _XmlDoc = new vlnFormatDocument(MyFormat); return _XmlDoc; } } @@ -132,10 +123,10 @@ namespace VEPROMS.CSLA.Library public class VE_Font : vlnFormatItem { public VE_Font(XmlNode xmlNode) : base(xmlNode) { } - private string _ffam = null; - private int _fsize = 0; - private E_Style _fstyle = E_Style.None; - private float _fcpi = 0; + private readonly string _ffam = null; + private readonly int _fsize = 0; + private readonly E_Style _fstyle = E_Style.None; + private readonly float _fcpi = 0; public VE_Font(string family, int size, E_Style style, float CPI) { _Family = new LazyLoad(family); @@ -148,7 +139,8 @@ namespace VEPROMS.CSLA.Library _fcpi = CPI; } private LazyLoad _Family; - private static Dictionary _WinFontLookup = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary _WinFontLookup = new Dictionary(); // put the fonts in a dictionary so that we don't call new Font each time we reference it private static Font GetFont(string family, float size, FontStyle style) { @@ -157,34 +149,21 @@ namespace VEPROMS.CSLA.Library _WinFontLookup.Add(key, new Font(family, size, style)); return _WinFontLookup[key]; } - // part of bug B2017-117 and for conservation of window handles to reduce the frequency of - // the Out of Window Handles error when editing and printing. - // we are now using a common dictionary for font usages - public static Font GetWinSysFont(string family, float size, FontStyle style) - { - return GetFont(family, size, style); - } - public static Font GetWinSysFont(string family, float size) - { - return GetFont(family, size, FontStyle.Regular); - } - public static Font GetWinSysFont(FontFamily ffamily, float size, FontStyle style) - { - return GetFont(ffamily.Name, size, style); - } - public static Font GetWinSysFont(Font font, FontStyle style) - { - return GetFont(font.Name, font.Size, style); - } + // part of bug B2017-117 and for conservation of window handles to reduce the frequency of + // the Out of Window Handles error when editing and printing. + // we are now using a common dictionary for font usages + public static Font GetWinSysFont(string family, float size, FontStyle style) => GetFont(family, size, style); + public static Font GetWinSysFont(string family, float size) => GetFont(family, size, FontStyle.Regular); + public static Font GetWinSysFont(FontFamily ffamily, float size, FontStyle style) => GetFont(ffamily.Name, size, style); + public static Font GetWinSysFont(Font font, FontStyle style) => GetFont(font.Name, font.Size, style); - private Font _WindowsFont; + private Font _WindowsFont; public Font WindowsFont { get { if (_WindowsFont == null) { - //FontStyle style = (Family == "Cornet")?FontStyle.Italic : FontStyle.Regular; FontStyle style = FontStyle.Regular; if (Style != E_Style.None) { @@ -200,10 +179,7 @@ namespace VEPROMS.CSLA.Library _WindowsFont = GetFont("Arial", 10, FontStyle.Regular); else { - //if (_ffam != null) - // _WindowsFont = GetFont(_ffam, (float)_fsize, style); // this needs work. - //else - _WindowsFont = GetFont(Family, Size == 0 ? 10 : (float)Size, style); + _WindowsFont = GetFont(Family, Size == 0 ? 10 : (float)Size, style); } } return _WindowsFont; @@ -213,61 +189,19 @@ namespace VEPROMS.CSLA.Library _WindowsFont = value; } } - [Description("Font Family")] - public string Family - { - get - { - return LazyLoad(ref _Family,"Font/@Family"); - } - } - private LazyLoad _Size; - [Description("Font Size (in Double Points)")] - public int? Size - { - get - { - return LazyLoad(ref _Size, "Font/@Size"); - } - } - private LazyLoad _Style; - public E_Style? Style - { - get - { - return LazyLoad(ref _Style, "Font/@Style"); - } - //set - //{ - // _Style.Value = value; - //} - } - private LazyLoad _CPI; - public float? CPI - { - get - { - return LazyLoad(ref _CPI, "Font/@CPI"); - } - } - public float CharsToTwips - { - get - { - return (72 / (CPI ?? 12)); - } - - } - public override string ToString() - { - return string.Format("{0}, {1} pt, {2}", Family, Size, Style); - } - public bool FontIsProportional() - { - if (Family.Contains("Arial") || Family.Contains("Times New Roman")) return true; - return false; - } - } + [Description("Font Family")] + public string Family => LazyLoad(ref _Family, "Font/@Family"); + private LazyLoad _Size; + [Description("Font Size (in Double Points)")] + public int? Size => LazyLoad(ref _Size, "Font/@Size"); + private LazyLoad _Style; + public E_Style? Style => LazyLoad(ref _Style, "Font/@Style"); + private LazyLoad _CPI; + public float? CPI => LazyLoad(ref _CPI, "Font/@CPI"); + public float CharsToTwips => 72 / (CPI ?? 12); + public override string ToString() => string.Format("{0}, {1} pt, {2}", Family, Size, Style); + public bool FontIsProportional() => Family.Contains("Arial") || Family.Contains("Times New Roman"); + } #endregion #region FormatData [TypeConverter(typeof(ExpandableObjectConverter))] @@ -276,67 +210,31 @@ namespace VEPROMS.CSLA.Library public FormatData(XmlNode xmlNode) : base(xmlNode) { } // Name of the format - as it appears when selecting the format to use in PROMS private LazyLoad _Name; - public string Name - { - get - { - return LazyLoad(ref _Name, "@Name"); - } - } - // When true, this format is allowed to be used in the PROMS Express product - private LazyLoad _Express; - public bool Express - { - get - { - return LazyLoad(ref _Express, "@Express"); - } - } - // When set to True, it enables the use of a Procedure Set Specific dialog, containing defined fields - // in which the user enters data that is printed on all or specific pages for all of the procedures in the set using this format - private LazyLoad _SpecificInfo; - public bool SpecificInfo - { - get - { - return LazyLoad(ref _SpecificInfo, "@SpecificInfo"); - } - } - // this is a structure defined in the format file that defines labels and fields on a pop-up dialog - // in which the user will enter data - this is accessible only at the procedure set level - private SI _SI; - public SI SI - { - get - { - return _SI == null ? _SI = new SI(SelectSingleNode("SI")) : _SI; - } - } - // TPL represents Templates which are sizes of columns for 'table' type data. If the format - // has the 'UseSmartTemplate' format flag, this table will have starting location & widths, and - // other data for the listed step types. Data from this table overrides width data as specified - // by the step type format data. The only active format that has 'UseSmartTemplate' is WCNCKL. - // The TPL data is also used by other formats, many of which are using it for Enhanced Background - // & Deviations. The actual format of the template can be in an old or new format. The old format - // uses spaces as delimiters, the new uses commas. - private LazyLoad _TPL; - public string TPL - { - get - { - return LazyLoad(ref _TPL, "@TPL"); - } - } - // not defined in format files, we now use TPL to define both the original and new template - // the C# determines if it's a smart (new) template or the old style (search for NewTemplateFormat to see the code) - private bool _NewTemplateFormat; - public bool NewTemplateFormat - { - get { return _NewTemplateFormat; } - set { _NewTemplateFormat = value; } - } - // Creates a dictionary of the templates (TPL) defined in the format - private Dictionary _TopTemplateTypes; + public string Name => LazyLoad(ref _Name, "@Name"); + // When true, this format is allowed to be used in the PROMS Express product + private LazyLoad _Express; + public bool Express => LazyLoad(ref _Express, "@Express"); + // When set to True, it enables the use of a Procedure Set Specific dialog, containing defined fields + // in which the user enters data that is printed on all or specific pages for all of the procedures in the set using this format + private LazyLoad _SpecificInfo; + public bool SpecificInfo => LazyLoad(ref _SpecificInfo, "@SpecificInfo"); + // this is a structure defined in the format file that defines labels and fields on a pop-up dialog + // in which the user will enter data - this is accessible only at the procedure set level + private SI _SI; + public SI SI => _SI ?? (_SI = new SI(SelectSingleNode("SI"))); + // TPL represents Templates which are sizes of columns for 'table' type data. If the format + // has the 'UseSmartTemplate' format flag, this table will have starting location & widths, and + // other data for the listed step types. Data from this table overrides width data as specified + // by the step type format data. The only active format that has 'UseSmartTemplate' is WCNCKL. + // The TPL data is also used by other formats, many of which are using it for Enhanced Background + // & Deviations. The actual format of the template can be in an old or new format. The old format + // uses spaces as delimiters, the new uses commas. + private LazyLoad _TPL; + public string TPL => LazyLoad(ref _TPL, "@TPL"); + + public bool NewTemplateFormat { get; set; } + // Creates a dictionary of the templates (TPL) defined in the format + private Dictionary _TopTemplateTypes; public Dictionary TopTemplateTypes { get @@ -387,64 +285,63 @@ namespace VEPROMS.CSLA.Library int cnt = 0; int tmpStrIndxStart = 0; - int tmpStrIndxEnd = 0; - while (cnt < NumTemplates) + while (cnt < NumTemplates) { - tmpStrIndxEnd = TPL.IndexOf("\n", tmpStrIndxStart); - if (tmpStrIndxEnd < 0) + int tmpStrIndxEnd = TPL.IndexOf("\n", tmpStrIndxStart); + if (tmpStrIndxEnd < 0) { cnt++; continue; // maybe extra newlines at end of string. } string tpl = TPL.Substring(tmpStrIndxStart, tmpStrIndxEnd-tmpStrIndxStart); tmpStrIndxStart = tmpStrIndxEnd + 1; - int level = 0; - int type = 0; - int start = 0; - int width = 0; + int start = 0; + int width = 0; short nocol = 0; int row = 0; - string stmp = null; - if (!NewTemplateFormat) // not the smart template - { - string[] tmpOld = tpl.Split(" ".ToCharArray()); - level = Convert.ToInt32(tmpOld[0]); - type = Convert.ToInt32(tmpOld[1]); - if (tmpOld.Length <= 2) - stmp = null; - else if (tmpOld.Length > 3) - { - // Wolf Creek and Turkey Point Background formats have spaces as part of the text in the 3rd field, - // handle this special case - int indxx = tpl.IndexOf(" "); //skip past "level" - if (indxx < 0) stmp = null; // template incomplete set text to a null - else - { - indxx = tpl.IndexOf(" ", indxx + 1); //skip past "type" - stmp = (indxx > -1) ? tpl.Substring(indxx+1) : null; //if valid index grab text after "type" (+1 skips past the space char after the "type" number) - } - } - else - stmp = tmpOld[2]; - } - else - { - string[] tmpNew = tpl.Split(",".ToCharArray()); - if (tmpNew.Length < 5) - { - cnt++; - continue; // may be extra newlines at end of string - } - level = Convert.ToInt32(tmpNew[0]); - type = Convert.ToInt32(tmpNew[1]); - start = Convert.ToInt32(tmpNew[2]); - width = Convert.ToInt32(tmpNew[3]); - row = Convert.ToInt32(tmpNew[4]); - nocol = Convert.ToInt16(tmpNew[5]); - stmp = tmpNew.Length <= 6 ? null : tmpNew[6]; - } - // some plants (Wolf Creek, Turkey Point) have two line titles in their templates with "[(0014])" representing the hard return in the title - if (stmp != null) + int level; + int type; + string stmp; + if (!NewTemplateFormat) // not the smart template + { + string[] tmpOld = tpl.Split(" ".ToCharArray()); + level = Convert.ToInt32(tmpOld[0]); + type = Convert.ToInt32(tmpOld[1]); + if (tmpOld.Length <= 2) + stmp = null; + else if (tmpOld.Length > 3) + { + // Wolf Creek and Turkey Point Background formats have spaces as part of the text in the 3rd field, + // handle this special case + int indxx = tpl.IndexOf(" "); //skip past "level" + if (indxx < 0) stmp = null; // template incomplete set text to a null + else + { + indxx = tpl.IndexOf(" ", indxx + 1); //skip past "type" + stmp = (indxx > -1) ? tpl.Substring(indxx + 1) : null; //if valid index grab text after "type" (+1 skips past the space char after the "type" number) + } + } + else + stmp = tmpOld[2]; + } + else + { + string[] tmpNew = tpl.Split(",".ToCharArray()); + if (tmpNew.Length < 5) + { + cnt++; + continue; // may be extra newlines at end of string + } + level = Convert.ToInt32(tmpNew[0]); + type = Convert.ToInt32(tmpNew[1]); + start = Convert.ToInt32(tmpNew[2]); + width = Convert.ToInt32(tmpNew[3]); + row = Convert.ToInt32(tmpNew[4]); + nocol = Convert.ToInt16(tmpNew[5]); + stmp = tmpNew.Length <= 6 ? null : tmpNew[6]; + } + // some plants (Wolf Creek, Turkey Point) have two line titles in their templates with "[(0014])" representing the hard return in the title + if (stmp != null) { stmp = stmp.Replace("[(0014])", "\\line "); // Hard Return stmp = stmp.Replace("\xFFFD", @"\u160?"); // Hard Space B2018-052 replace old(from 16-bit) hardspace character with the unicode hardspace character @@ -462,49 +359,26 @@ namespace VEPROMS.CSLA.Library // where we check which bits of the integer is set to determine if that option can be used. // See E_PurchaseOptions in ENums.cs for a description of each option flag (bit) private LazyLoad _PurchaseOptions; - public E_PurchaseOptions? PurchaseOptions - { - get - { - return LazyLoad(ref _PurchaseOptions, "@PurchaseOptions"); - } - } - // Set at the top of the format(under FormatData) defined the default font used in this format. - // Specific step types can have different font information assigned to override this default - private VE_Font _Font; - public VE_Font Font - { - get - { - return _Font == null? _Font = new VE_Font(base.XmlNode): _Font; - } - } + public E_PurchaseOptions? PurchaseOptions => LazyLoad(ref _PurchaseOptions, "@PurchaseOptions"); + // Set at the top of the format(under FormatData) defined the default font used in this format. + // Specific step types can have different font information assigned to override this default + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); - // Defines the printed page size (ex: US Letter, A4) - private PDFPageSize _PDFPageSize; - public PDFPageSize PDFPageSize // C2020-002 paper size is now set in the format files - { - get - { - return _PDFPageSize == null ? _PDFPageSize = new PDFPageSize(SelectSingleNode("PDFPageSize")) : _PDFPageSize; - } - } - //C2021-005 Format file grouping containing a list of possible font sizes (used only for table text via the Table Ribbon) - private FontSizes _FontSizes; - public FontSizes FontSizes - { - get - { - return _FontSizes == null ? _FontSizes = new FontSizes(SelectSingleNode("FontSizes")) : _FontSizes; - } - } - // C2021-004 This gets the list for additional Table Cell shading options defined in the format (base) file - private ShadingOptionList _ShadingOptionList; + // Defines the printed page size (ex: US Letter, A4) + private PDFPageSize _PDFPageSize; + // C2020-002 paper size is now set in the format files + public PDFPageSize PDFPageSize => _PDFPageSize ?? (_PDFPageSize = new PDFPageSize(SelectSingleNode("PDFPageSize"))); + //C2021-005 Format file grouping containing a list of possible font sizes (used only for table text via the Table Ribbon) + private FontSizes _FontSizes; + public FontSizes FontSizes => _FontSizes ?? (_FontSizes = new FontSizes(SelectSingleNode("FontSizes"))); + // C2021-004 This gets the list for additional Table Cell shading options defined in the format (base) file + private ShadingOptionList _ShadingOptionList; public ShadingOptionList ShadingOptionList { get { - return (_ShadingOptionList == null) ? _ShadingOptionList = new ShadingOptionList(SelectNodes("MoreShadingOptions/ShadingOption")) : _ShadingOptionList; + return _ShadingOptionList ?? (_ShadingOptionList = new ShadingOptionList(SelectNodes("MoreShadingOptions/ShadingOption"))); } set { _ShadingOptionList = value; } } @@ -514,7 +388,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_UnitWatermarkList == null) ? _UnitWatermarkList = new UnitWatermarkList(SelectNodes("UnitWatermarkData/UnitWatermark")) : _UnitWatermarkList; + return _UnitWatermarkList ?? (_UnitWatermarkList = new UnitWatermarkList(SelectNodes("UnitWatermarkData/UnitWatermark"))); } set { _UnitWatermarkList = value; } } @@ -525,81 +399,45 @@ namespace VEPROMS.CSLA.Library { get { - return (_SymbolList == null) ? _SymbolList = new SymbolList(SelectNodes("Symbols/Symbol")) : _SymbolList; + return _SymbolList ?? (_SymbolList = new SymbolList(SelectNodes("Symbols/Symbol"))); } set { _SymbolList = value; } } // gets the high level node that contains setting used in the procedure step editor private EditData _EditData; - public EditData EditData - { - get - { - return _EditData == null ? _EditData = new EditData(SelectSingleNode("EditData")): _EditData; - } - } - // gets the high level node that contains settings used to generate PDFs (print) - private PrintData _PrintData; - public PrintData PrintData - { - get - { - return _PrintData == null? _PrintData = new PrintData(SelectSingleNode("PrintData")):_PrintData; - } - } - // get high level node containing settings used for both edit and print - private ProcData _ProcData; - public ProcData ProcData - { - get - { - return _ProcData == null? _ProcData = new ProcData(SelectSingleNode("ProcData")):_ProcData; - } - } - // get high level node containing settings pertraining to sections of a procedure - private SectData _SectData; - public SectData SectData - { - get - { - return _SectData == null? _SectData = new SectData(SelectSingleNode("SectData")):_SectData; - } - } - // get a list of box formatting information primarily used for Cautions, Notes, and Warnings. - private BoxList _BoxList; + public EditData EditData => _EditData ?? (_EditData = new EditData(SelectSingleNode("EditData"))); + // gets the high level node that contains settings used to generate PDFs (print) + private PrintData _PrintData; + public PrintData PrintData => _PrintData ?? (_PrintData = new PrintData(SelectSingleNode("PrintData"))); + // get high level node containing settings used for both edit and print + private ProcData _ProcData; + public ProcData ProcData => _ProcData ?? (_ProcData = new ProcData(SelectSingleNode("ProcData"))); + // get high level node containing settings pertraining to sections of a procedure + private SectData _SectData; + public SectData SectData => _SectData ?? (_SectData = new SectData(SelectSingleNode("SectData"))); + // get a list of box formatting information primarily used for Cautions, Notes, and Warnings. + private BoxList _BoxList; public BoxList BoxList { get { - return _BoxList == null? _BoxList = new BoxList(SelectNodes("BoxData/Box"),MyFormat):_BoxList; + return _BoxList ?? (_BoxList = new BoxList(SelectNodes("BoxData/Box"), MyFormat)); } set { _BoxList = value; } } // gets a list of trainsition formatting information for various types of transitions private TransData _TransData; - public TransData TransData - { - get - { - return _TransData == null? _TransData = new TransData(SelectSingleNode("TransData")):_TransData; - } - } - // get format settings related to handling Referenced Object values - private ROData _ROData; - public ROData ROData - { - get - { - return _ROData == null ? _ROData = new ROData(SelectSingleNode("ROData")) : _ROData; - } - } - // gets a list containing all of the defined step types and step parts (high level, sub-steps, cations, notes, etc) - private StepDataList _StepDataList; + public TransData TransData => _TransData ?? (_TransData = new TransData(SelectSingleNode("TransData"))); + // get format settings related to handling Referenced Object values + private ROData _ROData; + public ROData ROData => _ROData ?? (_ROData = new ROData(SelectSingleNode("ROData"))); + // gets a list containing all of the defined step types and step parts (high level, sub-steps, cations, notes, etc) + private StepDataList _StepDataList; public StepDataList StepDataList { get { - return _StepDataList == null? _StepDataList = new StepDataList(SelectNodes("StepData/Step"),MyFormat):_StepDataList; + return _StepDataList ?? (_StepDataList = new StepDataList(SelectNodes("StepData/Step"), MyFormat)); } set { _StepDataList = value; } } @@ -649,8 +487,10 @@ namespace VEPROMS.CSLA.Library while (top.ParentType != "Base") { bool foundit = false; - string sParStp = StepDataList[formatStepType].ParentType; - foreach (StepData stp in StepDataList) +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Keeping for Debugging + string sParStp = StepDataList[formatStepType].ParentType; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + foreach (StepData stp in StepDataList) { if (top.ParentType == stp.Type) { @@ -865,14 +705,8 @@ namespace VEPROMS.CSLA.Library // Defines the printed page size (ex: US Letter, A4) private LazyLoad _PaperSize; - public string PaperSize - { - get - { - return LazyLoad(ref _PaperSize, "@PaperSize"); // C2020-002 paper size is now set in the format files - } - } - } + public string PaperSize => LazyLoad(ref _PaperSize, "@PaperSize"); // C2020-002 paper size is now set in the format files + } #endregion #region FontSizes // C2021-005 the list of possible font sizes are set in the format files @@ -881,14 +715,8 @@ namespace VEPROMS.CSLA.Library { public FontSizes(XmlNode xmlNode) : base(xmlNode) { } private LazyLoad _TableFontSizes; - public string TableFontSizes - { - get - { - return LazyLoad(ref _TableFontSizes, "@TableFontSizes"); // C2021-005 list of possible font sizes for table text - } - } - } + public string TableFontSizes => LazyLoad(ref _TableFontSizes, "@TableFontSizes"); // C2021-005 list of possible font sizes for table text + } #endregion #region ShadingOptions // C2021-004 Additional shading color options defined in the format file @@ -904,64 +732,25 @@ namespace VEPROMS.CSLA.Library public ShadingOption() : base() { } [Category("Ints")] private LazyLoad _Alpha; - public int? Alpha - { - get - { - return LazyLoad(ref _Alpha, "@A"); - } - } - [Category("Ints")] + public int? Alpha => LazyLoad(ref _Alpha, "@A"); + [Category("Ints")] private LazyLoad _Red; - public int? Red - { - get - { - return LazyLoad(ref _Red, "@R"); - } - } - [Category("Ints")] + public int? Red => LazyLoad(ref _Red, "@R"); + [Category("Ints")] private LazyLoad _Green; - public int? Green - { - get - { - return LazyLoad(ref _Green, "@G"); - } - } - [Category("Ints")] + public int? Green => LazyLoad(ref _Green, "@G"); + [Category("Ints")] private LazyLoad _Blue; - public int? Blue - { - get - { - return LazyLoad(ref _Blue, "@B"); - } - } - [Category("Strings")] + public int? Blue => LazyLoad(ref _Blue, "@B"); + [Category("Strings")] private LazyLoad _Desc; - public string Desc - { - get - { - return LazyLoad(ref _Desc, "@Desc"); - } - } - public override string GetPDDisplayName() - { return Desc; } - public override string GetPDDescription() - { return string.Format("Shading Description '{0}' Alpha {1} Red {2} Green {3} Blue {4}", Desc, Alpha, Red, Green, Blue); } - public override string GetPDCategory() - { return "Additional Shading Options"; } - public override string ToString() - { - return Desc; - } - public string GetARBGstringForTableCells() - { - return string.Format("[A={0}, R={1}, G={2}, B={3}]", Alpha, Red, Green, Blue); - } - } + public string Desc => LazyLoad(ref _Desc, "@Desc"); + public override string GetPDDisplayName() => Desc; + public override string GetPDDescription() => string.Format("Shading Description '{0}' Alpha {1} Red {2} Green {3} Blue {4}", Desc, Alpha, Red, Green, Blue); + public override string GetPDCategory() => "Additional Shading Options"; + public override string ToString() => Desc; + public string GetARBGstringForTableCells() => string.Format("[A={0}, R={1}, G={2}, B={3}]", Alpha, Red, Green, Blue); + } [TypeConverter(typeof(vlnListConverter))] public class ShadingOptionList : vlnFormatList { @@ -995,32 +784,15 @@ namespace VEPROMS.CSLA.Library public UnitWatermark() : base() { } [Category("Strings")] private LazyLoad _ProcNumPrefix; - public string ProcNumPrefix // based on the what the procedure number starts with, usually a resolved unit toke (ex: ) - { - get - { - return LazyLoad(ref _ProcNumPrefix, "@ProcNumPrefix"); - } - } - [Category("Strings")] + // based on the what the procedure number starts with, usually a resolved unit toke (ex: ) + public string ProcNumPrefix => LazyLoad(ref _ProcNumPrefix, "@ProcNumPrefix"); + [Category("Strings")] private LazyLoad _WMText; - public string WMText - { - get - { - return LazyLoad(ref _WMText, "@WMText"); - } - } - [Category("Strings")] + public string WMText => LazyLoad(ref _WMText, "@WMText"); + [Category("Strings")] private LazyLoad _WMColor; - public string WMColor - { - get - { - return LazyLoad(ref _WMColor, "@WMColor"); - } - } - } + public string WMColor => LazyLoad(ref _WMColor, "@WMColor"); + } [TypeConverter(typeof(vlnListConverter))] public class UnitWatermarkList : vlnFormatList { @@ -1035,33 +807,15 @@ namespace VEPROMS.CSLA.Library public Symbol() : base() { } [Category("Ints")] private LazyLoad _Unicode; - public int? Unicode - { - get - { - return LazyLoad(ref _Unicode, "@Unicode"); - } - } - [Category("Strings")] + public int? Unicode => LazyLoad(ref _Unicode, "@Unicode"); + [Category("Strings")] private LazyLoad _Desc; - public string Desc - { - get - { - return LazyLoad(ref _Desc, "@Desc"); - } - } - public override string GetPDDisplayName() - { return Desc; } - public override string GetPDDescription() - { return string.Format("Symbol Unicode '{0}' Description '{1}'", Unicode, Desc); } - public override string GetPDCategory() - { return "Supported Symbols"; } - public override string ToString() - { - return Desc; - } - } + public string Desc => LazyLoad(ref _Desc, "@Desc"); + public override string GetPDDisplayName() => Desc; + public override string GetPDDescription() => string.Format("Symbol Unicode '{0}' Description '{1}'", Unicode, Desc); + public override string GetPDCategory() => "Supported Symbols"; + public override string ToString() => Desc; + } [TypeConverter(typeof(vlnListConverter))] public class SymbolList : vlnFormatList { @@ -1096,7 +850,6 @@ namespace VEPROMS.CSLA.Library nocolm = c; hmacro = 0x00F0 & nocolm >> 4; if (hmacro > 0) hmacro = 4; // bge - this was in 16bit code - int blines = (0x0F00 & nocolm) >> 8; boxed = ((0xF000 & nocolm) >> 12) != 0; nocolm = (short)(0x000F & nocolm); text = x; @@ -1112,14 +865,8 @@ namespace VEPROMS.CSLA.Library // - No change bars will be added // - existing change bars will remain private LazyLoad _EditoralSpellCheck; - public bool EditoralSpellCheck - { - get - { - return LazyLoad(ref _EditoralSpellCheck, "@EditoralSpellCheck"); - } - } - } + public bool EditoralSpellCheck => LazyLoad(ref _EditoralSpellCheck, "@EditoralSpellCheck"); + } #endregion #region PrintDataAll #region PrintData @@ -1131,294 +878,132 @@ namespace VEPROMS.CSLA.Library // List of procedure descriptions (ProcDescr) inwhich we match the beginning of a procedure number // in order to print procedure description text via a pagelist token private ProcDescrList _ProcDescrList; - public ProcDescrList ProcDescrList - { - get - { - return _ProcDescrList == null? _ProcDescrList = new ProcDescrList(SelectNodes("ProcDescrList/ProcDescr")):_ProcDescrList; - } - } + public ProcDescrList ProcDescrList => _ProcDescrList ?? (_ProcDescrList = new ProcDescrList(SelectNodes("ProcDescrList/ProcDescr"))); - // an offset value for the placement of step tabs used in a Supplemental Information section of SAMG procedures - // to allow space for a Note or Caution tab. - private LazyLoad _SupInfoTabOff; - public int? SupInfoTabOff - { - get - { - return LazyLoad(ref _SupInfoTabOff, "@SupInfoTabOff"); - } - } + // an offset value for the placement of step tabs used in a Supplemental Information section of SAMG procedures + // to allow space for a Note or Caution tab. + private LazyLoad _SupInfoTabOff; + public int? SupInfoTabOff => LazyLoad(ref _SupInfoTabOff, "@SupInfoTabOff"); - // Flag to determin if the parent tab is used as the first part of a supplemental info step/sub-step tab. - private LazyLoad _SupInfoIncludeParTab; - public bool SupInfoIncludeParTab - { - get - { - return LazyLoad(ref _SupInfoIncludeParTab, "@SupInfoIncludeParTab"); - } - } + // Flag to determin if the parent tab is used as the first part of a supplemental info step/sub-step tab. + private LazyLoad _SupInfoIncludeParTab; + public bool SupInfoIncludeParTab => LazyLoad(ref _SupInfoIncludeParTab, "@SupInfoIncludeParTab"); - // Shift the hoizontal positon of a step by 12 if the supplemental Info step tab was going to print over step text - private LazyLoad _SupInfoAdjustXOffForLongTab; - public bool SupInfoAdjustXOffForLongTab - { - get - { - return LazyLoad(ref _SupInfoAdjustXOffForLongTab, "@SupInfoAdjustXOffForLongTab"); - } - } + // Shift the hoizontal positon of a step by 12 if the supplemental Info step tab was going to print over step text + private LazyLoad _SupInfoAdjustXOffForLongTab; + public bool SupInfoAdjustXOffForLongTab => LazyLoad(ref _SupInfoAdjustXOffForLongTab, "@SupInfoAdjustXOffForLongTab"); - // flag to allow user to enter the procedure revision number, either a forward or back slash, - // then the revision date or revision text - private LazyLoad _DoRevDate; - public bool DoRevDate - { - get - { - return LazyLoad(ref _DoRevDate, "@DoRevDate"); - } - } + // flag to allow user to enter the procedure revision number, either a forward or back slash, + // then the revision date or revision text + private LazyLoad _DoRevDate; + public bool DoRevDate => LazyLoad(ref _DoRevDate, "@DoRevDate"); - // Print alternate foldout pages within a defined range of procedure step pages. - // You can have multiple Foldout Page sections within a procedure, - // each pertaining to a range of steps (ranges cannot overlap) - used by Shearon Harris - private LazyLoad _AlternateFloatingFoldout; - public bool AlternateFloatingFoldout - { - get - { - return LazyLoad(ref _AlternateFloatingFoldout, "@AlternateFloatingFoldout"); - } - } + // Print alternate foldout pages within a defined range of procedure step pages. + // You can have multiple Foldout Page sections within a procedure, + // each pertaining to a range of steps (ranges cannot overlap) - used by Shearon Harris + private LazyLoad _AlternateFloatingFoldout; + public bool AlternateFloatingFoldout => LazyLoad(ref _AlternateFloatingFoldout, "@AlternateFloatingFoldout"); - // Allows the user to identify a procedure section that is to be used as a foldout page - // that is printed on the backside of procedure step pages - private LazyLoad _SectionLevelFoldouts; - public bool SectionLevelFoldouts - { - get - { - return LazyLoad(ref _SectionLevelFoldouts, "@SectionLevelFoldouts"); - } - } + // Allows the user to identify a procedure section that is to be used as a foldout page + // that is printed on the backside of procedure step pages + private LazyLoad _SectionLevelFoldouts; + public bool SectionLevelFoldouts => LazyLoad(ref _SectionLevelFoldouts, "@SectionLevelFoldouts"); - // This will replace any forward or back slash character they may be in the procedures's PDF file name - // with the character defined in the plant's format file - private LazyLoad _SlashReplace; - public string SlashReplace - { - get - { - return LazyLoad(ref _SlashReplace, "@SlashReplace"); - } - } + // This will replace any forward or back slash character they may be in the procedures's PDF file name + // with the character defined in the plant's format file + private LazyLoad _SlashReplace; + public string SlashReplace => LazyLoad(ref _SlashReplace, "@SlashReplace"); - // Flag - (flag is named incorrectly) when set allows user to append to the procedure's revision number, - // a backslash character followed by a revision date - private LazyLoad _RevDateWithForwardSlash; - public bool RevDateWithForwardSlash - { - get - { - return LazyLoad(ref _RevDateWithForwardSlash, "@RevDateWithForwardSlash"); - } - } + // Flag - (flag is named incorrectly) when set allows user to append to the procedure's revision number, + // a backslash character followed by a revision date + private LazyLoad _RevDateWithForwardSlash; + public bool RevDateWithForwardSlash => LazyLoad(ref _RevDateWithForwardSlash, "@RevDateWithForwardSlash"); - // On the Working Draft Properties page, Turns on a text box for the user to enter in a unit number - // that is used on cover pages and in the page header - D.C. Cook and Calvert Cliffs formats - private LazyLoad _UnitNumber; - public bool UnitNumber - { - get - { - return LazyLoad(ref _UnitNumber, "@UnitNumber"); - } - } + // On the Working Draft Properties page, Turns on a text box for the user to enter in a unit number + // that is used on cover pages and in the page header - D.C. Cook and Calvert Cliffs formats + private LazyLoad _UnitNumber; + public bool UnitNumber => LazyLoad(ref _UnitNumber, "@UnitNumber"); - // Flag allow for using the UnitProcSetString transition defintion variable which will build - // a prefix to the referenced procedure number - // ex: UnitProcSetString ="{PSI:UNITCOM}-{SI:SETNAME}-{PSI:SETID|4023}-" will look for UNITCOM in - // the Procedure Specific Information, then SETNAME in the Set Specific Information (working draft), - // then the SETID in the Procedure Specific Information (or use 4023) if nothing is entered - private LazyLoad _OutSideTransSetName; //B2019-072: For AEP, use PSI & SI for outside transition text - public bool OutSideTransSetName - { - get - { - return LazyLoad(ref _OutSideTransSetName, "@OutSideTransSetName"); - } - } + // Flag allow for using the UnitProcSetString transition defintion variable which will build + // a prefix to the referenced procedure number + // ex: UnitProcSetString ="{PSI:UNITCOM}-{SI:SETNAME}-{PSI:SETID|4023}-" will look for UNITCOM in + // the Procedure Specific Information, then SETNAME in the Set Specific Information (working draft), + // then the SETID in the Procedure Specific Information (or use 4023) if nothing is entered + private LazyLoad _OutSideTransSetName; //B2019-072: For AEP, use PSI & SI for outside transition text + public bool OutSideTransSetName => LazyLoad(ref _OutSideTransSetName, "@OutSideTransSetName"); - // For Calvert Cliffs, this allows for double letted step tabs, speical handling in Transitions, - // special pagination logic for their style of procedures - private LazyLoad _SpecialCaseCalvert; - public bool SpecialCaseCalvert - { - get - { - return LazyLoad(ref _SpecialCaseCalvert, "@SpecialCaseCalvert"); - } - } + // For Calvert Cliffs, this allows for double letted step tabs, speical handling in Transitions, + // special pagination logic for their style of procedures + private LazyLoad _SpecialCaseCalvert; + public bool SpecialCaseCalvert => LazyLoad(ref _SpecialCaseCalvert, "@SpecialCaseCalvert"); - // Calvert Alarms have the top part of the alarm point page in single column, the the bottom part in two column. - // Also special processing of Note, Cautions and Warnings - private LazyLoad _SpecialCaseCalvertAlarm; - public bool SpecialCaseCalvertAlarm - { - get - { - return LazyLoad(ref _SpecialCaseCalvertAlarm, "@SpecialCaseCalvertAlarm"); - } - } + // Calvert Alarms have the top part of the alarm point page in single column, the the bottom part in two column. + // Also special processing of Note, Cautions and Warnings + private LazyLoad _SpecialCaseCalvertAlarm; + public bool SpecialCaseCalvertAlarm => LazyLoad(ref _SpecialCaseCalvertAlarm, "@SpecialCaseCalvertAlarm"); - // Special pagination logic to handle out of the ordinary procedure formating and steps with RNOs - // that go on for pages - private LazyLoad _SpecialCaseCalvertPagination; - public bool SpecialCaseCalvertPagination - { - get - { - return LazyLoad(ref _SpecialCaseCalvertPagination, "@SpecialCaseCalvertPagination"); - } - } + // Special pagination logic to handle out of the ordinary procedure formating and steps with RNOs + // that go on for pages + private LazyLoad _SpecialCaseCalvertPagination; + public bool SpecialCaseCalvertPagination => LazyLoad(ref _SpecialCaseCalvertPagination, "@SpecialCaseCalvertPagination"); - // B2023-034 for use with Beaver Valley AOP format - // This allows for the use of the UseOnFirst docstyle setting on a mixture of sections and sub-sections - private LazyLoad _UseOnFirstForSeparatePaginationOnSubSect; - public bool UseOnFirstForSeparatePaginationOnSubSect - { - get - { - return LazyLoad(ref _UseOnFirstForSeparatePaginationOnSubSect, "@UseOnFirstForSeparatePaginationOnSubSect"); - } - } + // B2023-034 for use with Beaver Valley AOP format + // This allows for the use of the UseOnFirst docstyle setting on a mixture of sections and sub-sections + private LazyLoad _UseOnFirstForSeparatePaginationOnSubSect; + public bool UseOnFirstForSeparatePaginationOnSubSect => LazyLoad(ref _UseOnFirstForSeparatePaginationOnSubSect, "@UseOnFirstForSeparatePaginationOnSubSect"); - // B2023-043 for use with Beaver Valley AOP format - allow attributes, such as superscript on section titles - // when printing - private LazyLoad _SectionTitleWithAttributes; - public bool SectionTitleWithAttributes - { - get - { - return LazyLoad(ref _SectionTitleWithAttributes, "@SectionTitleWithAttributes"); - } - } + // B2023-043 for use with Beaver Valley AOP format - allow attributes, such as superscript on section titles + // when printing + private LazyLoad _SectionTitleWithAttributes; + public bool SectionTitleWithAttributes => LazyLoad(ref _SectionTitleWithAttributes, "@SectionTitleWithAttributes"); - // Format Flag enabling special formatting and printing of training materials - Wolf Creek Training format - private LazyLoad _WCNTraining; - public bool WCNTraining - { - get - { - return LazyLoad(ref _WCNTraining, "@WCNTraining"); - } - } + // Format Flag enabling special formatting and printing of training materials - Wolf Creek Training format + private LazyLoad _WCNTraining; + public bool WCNTraining => LazyLoad(ref _WCNTraining, "@WCNTraining"); - // Only used in Calvert Cliffs Valve format - only supporting code checks to see - // if a note should be a footnote - private LazyLoad _HorizontalSubsteps; - public bool HorizontalSubsteps - { - get - { - return LazyLoad(ref _HorizontalSubsteps, "@HorizontalSubsteps"); - } - } + // Only used in Calvert Cliffs Valve format - only supporting code checks to see + // if a note should be a footnote + private LazyLoad _HorizontalSubsteps; + public bool HorizontalSubsteps => LazyLoad(ref _HorizontalSubsteps, "@HorizontalSubsteps"); - // Doesn't reset the paglist for the first sub-section when printing - // - appears to be needed for plants with AP1000 procedures - private LazyLoad _SpecialCaseWestinghouse; - public bool SpecialCaseWestinghouse - { - get - { - return LazyLoad(ref _SpecialCaseWestinghouse, "@SpecialCaseWestinghouse"); - } - } + // Doesn't reset the paglist for the first sub-section when printing + // - appears to be needed for plants with AP1000 procedures + private LazyLoad _SpecialCaseWestinghouse; + public bool SpecialCaseWestinghouse => LazyLoad(ref _SpecialCaseWestinghouse, "@SpecialCaseWestinghouse"); - // Put in for Comanche Peak to print "COMMON" for the unit number instead of "Unit 0" - private LazyLoad _PrintCommonForZeroUnit; - public bool PrintCommonForZeroUnit - { - get - { - return LazyLoad(ref _PrintCommonForZeroUnit, "@PrintCommonForZeroUnit"); - } - } + // Put in for Comanche Peak to print "COMMON" for the unit number instead of "Unit 0" + private LazyLoad _PrintCommonForZeroUnit; + public bool PrintCommonForZeroUnit => LazyLoad(ref _PrintCommonForZeroUnit, "@PrintCommonForZeroUnit"); - // F2021-033: Barakah Alarm: no blank line between HLS & first substep - private LazyLoad _NoBlankHlsAndFirstSub; - public bool NoBlankHlsAndFirstSub - { - get - { - return LazyLoad(ref _NoBlankHlsAndFirstSub, "@NoBlankHlsAndFirstSub"); - } - } + // F2021-033: Barakah Alarm: no blank line between HLS & first substep + private LazyLoad _NoBlankHlsAndFirstSub; + public bool NoBlankHlsAndFirstSub => LazyLoad(ref _NoBlankHlsAndFirstSub, "@NoBlankHlsAndFirstSub"); - // F2021-025: Barakah Alarm: no blank line between last Note/Caution/Warn & box line - private LazyLoad _NoBlankLastNoteCautionWarn; - public bool NoBlankLastNoteCautionWarn - { - get - { - return LazyLoad(ref _NoBlankLastNoteCautionWarn, "@NoBlankLastNoteCautionWarn"); - } - } + // F2021-025: Barakah Alarm: no blank line between last Note/Caution/Warn & box line + private LazyLoad _NoBlankLastNoteCautionWarn; + public bool NoBlankLastNoteCautionWarn => LazyLoad(ref _NoBlankLastNoteCautionWarn, "@NoBlankLastNoteCautionWarn"); - // F2023-126: Vogtle Alarms - center single line caution/note if more than one type exist off step - private LazyLoad _NoteCautionCenterOneAllTypes; - public bool NoteCautionCenterOneAllTypes - { - get - { - return LazyLoad(ref _NoteCautionCenterOneAllTypes, "@NoteCautionCenterOneAllTypes"); - } - } + // F2023-126: Vogtle Alarms - center single line caution/note if more than one type exist off step + private LazyLoad _NoteCautionCenterOneAllTypes; + public bool NoteCautionCenterOneAllTypes => LazyLoad(ref _NoteCautionCenterOneAllTypes, "@NoteCautionCenterOneAllTypes"); - // C2021-063 Barakah Alarm: check box to generate Alarm Point List Text - private LazyLoad _ChkBoxToGeneratePointListText; - public bool ChkBoxToGeneratePointListText - { - get - { - return LazyLoad(ref _ChkBoxToGeneratePointListText, "@ChkBoxToGeneratePointListText"); - } - } + // C2021-063 Barakah Alarm: check box to generate Alarm Point List Text + private LazyLoad _ChkBoxToGeneratePointListText; + public bool ChkBoxToGeneratePointListText => LazyLoad(ref _ChkBoxToGeneratePointListText, "@ChkBoxToGeneratePointListText"); - // C2022-004 When a procedure is approved, force the watermark of the unit number - // (defined in the format file under UnitWatermarkData) - private LazyLoad _UseUnitWatermarkOnApproved; - public bool UseUnitWatermarkOnApproved - { - get - { - return LazyLoad(ref _UseUnitWatermarkOnApproved, "@UseUnitWatermarkOnApproved"); - } - } + // C2022-004 When a procedure is approved, force the watermark of the unit number + // (defined in the format file under UnitWatermarkData) + private LazyLoad _UseUnitWatermarkOnApproved; + public bool UseUnitWatermarkOnApproved => LazyLoad(ref _UseUnitWatermarkOnApproved, "@UseUnitWatermarkOnApproved"); - // B2022-086: Barakah - flag to adjust ypagesize for pagination when 1st and later pages have different printable box size - private LazyLoad _AdjFirstSecDocStylesInPagination; - public bool AdjFirstSecDocStylesInPagination - { - get - { - return LazyLoad(ref _AdjFirstSecDocStylesInPagination, "@AdjFirstSecDocStylesInPagination"); - } - } + // B2022-086: Barakah - flag to adjust ypagesize for pagination when 1st and later pages have different printable box size + private LazyLoad _AdjFirstSecDocStylesInPagination; + public bool AdjFirstSecDocStylesInPagination => LazyLoad(ref _AdjFirstSecDocStylesInPagination, "@AdjFirstSecDocStylesInPagination"); - // Adjust the image size to better fit on the printed page - private LazyLoad _AdjustLargeImage; - public bool AdjustLargeImage - { - get - { - return LazyLoad(ref _AdjustLargeImage, "@AdjustLargeImage"); - } - } - } + // Adjust the image size to better fit on the printed page + private LazyLoad _AdjustLargeImage; + public bool AdjustLargeImage => LazyLoad(ref _AdjustLargeImage, "@AdjustLargeImage"); + } #endregion PrintData #region ProcDescr [TypeConverter(typeof(ExpandableObjectConverter))] @@ -1429,38 +1014,17 @@ namespace VEPROMS.CSLA.Library // procedure number part (pattern) to match to find a description to use with the {PROCDESC} pagelist token private LazyLoad _MatchProcNumber; - public string MatchProcNumber - { - get - { - return LazyLoad(ref _MatchProcNumber, "@MatchProcNumber"); - } - } + public string MatchProcNumber => LazyLoad(ref _MatchProcNumber, "@MatchProcNumber"); - // The description text associated with a MatchProcNumber Text is used to replace the {PROCDES1} pagelist - private LazyLoad _ProcDescr1; - public string ProcDescr1 - { - get - { - return LazyLoad(ref _ProcDescr1, "@ProcDescr1"); - } - } + // The description text associated with a MatchProcNumber Text is used to replace the {PROCDES1} pagelist + private LazyLoad _ProcDescr1; + public string ProcDescr1 => LazyLoad(ref _ProcDescr1, "@ProcDescr1"); - // A second description text associated with a MatchProcNumber. Text is used to replace the {PROCDES2} - private LazyLoad _ProcDescr2; - public string ProcDescr2 - { - get - { - return LazyLoad(ref _ProcDescr2, "@ProcDescr2"); - } - } - public override string ToString() - { - return string.Format("{0}, {1}", ProcDescr1, MatchProcNumber); - } - } + // A second description text associated with a MatchProcNumber. Text is used to replace the {PROCDES2} + private LazyLoad _ProcDescr2; + public string ProcDescr2 => LazyLoad(ref _ProcDescr2, "@ProcDescr2"); + public override string ToString() => string.Format("{0}, {1}", ProcDescr1, MatchProcNumber); + } #region ProcDescrList [TypeConverter(typeof(vlnListConverter))] public class ProcDescrList : vlnFormatList @@ -1477,98 +1041,44 @@ namespace VEPROMS.CSLA.Library { public ProcData(XmlNode xmlNode) : base(xmlNode) { } private ChangeBarData _ChangeBarData; - public ChangeBarData ChangeBarData - { - get - { - return _ChangeBarData == null ? _ChangeBarData = new ChangeBarData(SelectSingleNode("ChangeBarData")) : _ChangeBarData; - } - } - private CheckOffData _CheckOffData; - public CheckOffData CheckOffData - { - get - { - return _CheckOffData == null ? _CheckOffData = new CheckOffData(SelectSingleNode("CheckOffData")) : _CheckOffData; - } - } - private PSI _PSI; - public PSI PSI - { - get - { - return _PSI == null ? _PSI = new PSI(SelectSingleNode("PSI")) : _PSI; - } - } + public ChangeBarData ChangeBarData => _ChangeBarData ?? (_ChangeBarData = new ChangeBarData(SelectSingleNode("ChangeBarData"))); + private CheckOffData _CheckOffData; + public CheckOffData CheckOffData => _CheckOffData ?? (_CheckOffData = new CheckOffData(SelectSingleNode("CheckOffData"))); + private PSI _PSI; + public PSI PSI => _PSI ?? (_PSI = new PSI(SelectSingleNode("PSI"))); - // specifies the maxiumn length of the procedure title before PROMS considers to wrap the title - // this is used with the {PROCTITLE} PageStyle toekn - private LazyLoad _TitleLength; - public int? TitleLength - { - get - { - return LazyLoad(ref _TitleLength, "@TitleLength"); - } - } + // specifies the maxiumn length of the procedure title before PROMS considers to wrap the title + // this is used with the {PROCTITLE} PageStyle toekn + private LazyLoad _TitleLength; + public int? TitleLength => LazyLoad(ref _TitleLength, "@TitleLength"); - // Length of the procedure title before wrapping on the Cover Page. T - // his is used with the {COVERPROCTITLE} PageSytle token - private LazyLoad _CoverTitleLength; - public int? CoverTitleLength - { - get - { - return LazyLoad(ref _CoverTitleLength, "@CoverTitleLength"); - } - } + // Length of the procedure title before wrapping on the Cover Page. T + // his is used with the {COVERPROCTITLE} PageSytle token + private LazyLoad _CoverTitleLength; + public int? CoverTitleLength => LazyLoad(ref _CoverTitleLength, "@CoverTitleLength"); - // Uppercase the procedure title when printed - private LazyLoad _CapitalizeTitle; - public bool CapitalizeTitle - { - get - { - return LazyLoad(ref _CapitalizeTitle, "@CapitalizeTitle"); - } - } + // Uppercase the procedure title when printed + private LazyLoad _CapitalizeTitle; + public bool CapitalizeTitle => LazyLoad(ref _CapitalizeTitle, "@CapitalizeTitle"); - // If a procedure or section does not have a title PROMS puts in "" as default title text - // by default (base format) PROMS will print "" - // When set to False, this flag prevents PROMS printing the text "" - // This also affects transiton references - private LazyLoad _PrintNoTitle; - public bool PrintNoTitle - { - get - { - return LazyLoad(ref _PrintNoTitle, "@PrintNoTitle"); - } - } + // If a procedure or section does not have a title PROMS puts in "" as default title text + // by default (base format) PROMS will print "" + // When set to False, this flag prevents PROMS printing the text "" + // This also affects transiton references + private LazyLoad _PrintNoTitle; + public bool PrintNoTitle => LazyLoad(ref _PrintNoTitle, "@PrintNoTitle"); - // This will print Notes at the bottom of the page as footnotes - // Use by Calvert Cliffs (BGE) primarily for their landscaped valve sections - private LazyLoad _NotesToFootnotes; - public bool NotesToFootnotes - { - get - { - return LazyLoad(ref _NotesToFootnotes, "@NotesToFootnotes"); - } - } + // This will print Notes at the bottom of the page as footnotes + // Use by Calvert Cliffs (BGE) primarily for their landscaped valve sections + private LazyLoad _NotesToFootnotes; + public bool NotesToFootnotes => LazyLoad(ref _NotesToFootnotes, "@NotesToFootnotes"); - // C2021-027: Procedure level PC/PC - // This allows us to assign an entire procedure's applicability level - // instead of just the sections and steps - private LazyLoad _ProcAppl; - public bool ProcAppl - { - get - { - return LazyLoad(ref _ProcAppl, "@ProcAppl"); - } - } - } + // C2021-027: Procedure level PC/PC + // This allows us to assign an entire procedure's applicability level + // instead of just the sections and steps + private LazyLoad _ProcAppl; + public bool ProcAppl => LazyLoad(ref _ProcAppl, "@ProcAppl"); + } #endregion #region PsiAll @@ -1582,58 +1092,22 @@ namespace VEPROMS.CSLA.Library // and cover pages (i.e. signaure names, dates, Use Categories) public PSI(XmlNode xmlNode) : base(xmlNode) { } private LazyLoad _x; - public int? x - { - get - { - return LazyLoad(ref _x, "@x"); - } - } - private LazyLoad _y; - public int? y - { - get - { - return LazyLoad(ref _y, "@y"); - } - } - private LazyLoad _Caption; - // caption for the PSI window - public string Caption - { - get - { - return LazyLoad(ref _Caption, "@Caption"); - } - } - private LazyLoad _ButtonsOnBottom; // change to bool - // place the OK and Cancel buttons on the bottom of the PSI window - public string ButtonsOnBottom - { - get - { - return LazyLoad(ref _ButtonsOnBottom, "@ButtonsOnBottom"); - } - } - // returns a list of labels that are defined in the format's PSI structure - private SILabels _LabelList; - public SILabels LabelList - { - get - { - return _LabelList == null ? _LabelList = new SILabels(SelectNodes("/PlantFormat/FormatData/ProcData/PSI/Label")) : _LabelList; - } - } - // returns a list of fields that are defined in the format's PSI structure - private SIFields _FieldList; - public SIFields FieldList - { - get - { - return _FieldList == null ? _FieldList = new SIFields(SelectNodes("/PlantFormat/FormatData/ProcData/PSI/Field")) : _FieldList; - } - } - } + public int? x => LazyLoad(ref _x, "@x"); + private LazyLoad _y; + public int? y => LazyLoad(ref _y, "@y"); + private LazyLoad _Caption; + // caption for the PSI window + public string Caption => LazyLoad(ref _Caption, "@Caption"); + private LazyLoad _ButtonsOnBottom; // change to bool + // place the OK and Cancel buttons on the bottom of the PSI window + public string ButtonsOnBottom => LazyLoad(ref _ButtonsOnBottom, "@ButtonsOnBottom"); + // returns a list of labels that are defined in the format's PSI structure + private SILabels _LabelList; + public SILabels LabelList => _LabelList ?? (_LabelList = new SILabels(SelectNodes("/PlantFormat/FormatData/ProcData/PSI/Label"))); + // returns a list of fields that are defined in the format's PSI structure + private SIFields _FieldList; + public SIFields FieldList => _FieldList ?? (_FieldList = new SIFields(SelectNodes("/PlantFormat/FormatData/ProcData/PSI/Field"))); + } public class SILabels : vlnFormatList { public SILabels(XmlNodeList xmlNodeList) : base(xmlNodeList) { } @@ -1645,54 +1119,18 @@ namespace VEPROMS.CSLA.Library public SILabel(XmlNode xmlNode) : base(xmlNode) { } public SILabel() : base() { } private LazyLoad _text; - public string text - { - get - { - return LazyLoad(ref _text, "@text"); - } - } - private LazyLoad _Justify; - public string Justify - { - get - { - return LazyLoad(ref _Justify, "@Justify"); - } - } - private LazyLoad _x; - public int? x - { - get - { - return LazyLoad(ref _x, "@x"); - } - } - private LazyLoad _y; - public int? y - { - get - { - return LazyLoad(ref _y, "@y"); - } - } - private LazyLoad _width; - public int? width - { - get - { - return LazyLoad(ref _width, "@width"); - } - } - private LazyLoad _height; - public int? height - { - get - { - return LazyLoad(ref _height, "@height"); - } - } - } + public string text => LazyLoad(ref _text, "@text"); + private LazyLoad _Justify; + public string Justify => LazyLoad(ref _Justify, "@Justify"); + private LazyLoad _x; + public int? x => LazyLoad(ref _x, "@x"); + private LazyLoad _y; + public int? y => LazyLoad(ref _y, "@y"); + private LazyLoad _width; + public int? width => LazyLoad(ref _width, "@width"); + private LazyLoad _height; + public int? height => LazyLoad(ref _height, "@height"); + } public class SIFields : vlnFormatList { public SIFields(XmlNodeList xmlNodeList) : base(xmlNodeList) { } @@ -1703,78 +1141,24 @@ namespace VEPROMS.CSLA.Library public SIField(XmlNode xmlNode) : base(xmlNode) { } public SIField() : base() { } private LazyLoad _name; - public string name - { - get - { - return LazyLoad(ref _name, "@name"); - } - } - private LazyLoad _type; - public string type - { - get - { - return LazyLoad(ref _type, "@type"); - } - } - private LazyLoad _text; - public string text - { - get - { - return LazyLoad(ref _text, "@text"); - } - } - private LazyLoad _Length; - public int? Length - { - get - { - return LazyLoad(ref _Length, "@Length"); - } - } - private LazyLoad _x; - public int? x - { - get - { - return LazyLoad(ref _x, "@x"); - } - } - private LazyLoad _y; - public int? y - { - get - { - return LazyLoad(ref _y, "@y"); - } - } - private LazyLoad _width; - public int? width - { - get - { - return LazyLoad(ref _width, "@width"); - } - } - private LazyLoad _height; - public int? height - { - get - { - return LazyLoad(ref _height, "@height"); - } - } - private LazyLoad _hasAppl; - public string hasAppl - { - get - { - return LazyLoad(ref _hasAppl, "@hasAppl"); - } - } - } + public string name => LazyLoad(ref _name, "@name"); + private LazyLoad _type; + public string type => LazyLoad(ref _type, "@type"); + private LazyLoad _text; + public string text => LazyLoad(ref _text, "@text"); + private LazyLoad _Length; + public int? Length => LazyLoad(ref _Length, "@Length"); + private LazyLoad _x; + public int? x => LazyLoad(ref _x, "@x"); + private LazyLoad _y; + public int? y => LazyLoad(ref _y, "@y"); + private LazyLoad _width; + public int? width => LazyLoad(ref _width, "@width"); + private LazyLoad _height; + public int? height => LazyLoad(ref _height, "@height"); + private LazyLoad _hasAppl; + public string hasAppl => LazyLoad(ref _hasAppl, "@hasAppl"); + } #endregion #region SIAll // classes to handle Set Specific information @@ -1784,56 +1168,20 @@ namespace VEPROMS.CSLA.Library { public SI(XmlNode xmlNode) : base(xmlNode) { } private LazyLoad _x; - public int? x - { - get - { - return LazyLoad(ref _x, "@x"); - } - } - private LazyLoad _y; - public int? y - { - get - { - return LazyLoad(ref _y, "@y"); - } - } - // caption for the the Set Specific information window - private LazyLoad _Caption; - public string Caption - { - get - { - return LazyLoad(ref _Caption, "@Caption"); - } - } - // the the OK and Cancel buttons on the bottom of the SI Window - private LazyLoad _ButtonsOnBottom; // change to bool - public string ButtonsOnBottom - { - get - { - return LazyLoad(ref _ButtonsOnBottom, "@ButtonsOnBottom"); - } - } - private SILabels _LabelList; - public SILabels LabelList - { - get - { - return _LabelList == null ? _LabelList = new SILabels(SelectNodes("/PlantFormat/FormatData/SI/Label")) : _LabelList; - } - } - private SIFields _FieldList; - public SIFields FieldList - { - get - { - return _FieldList == null ? _FieldList = new SIFields(SelectNodes("/PlantFormat/FormatData/SI/Field")) : _FieldList; - } - } - } + public int? x => LazyLoad(ref _x, "@x"); + private LazyLoad _y; + public int? y => LazyLoad(ref _y, "@y"); + // caption for the the Set Specific information window + private LazyLoad _Caption; + public string Caption => LazyLoad(ref _Caption, "@Caption"); + // the the OK and Cancel buttons on the bottom of the SI Window + private LazyLoad _ButtonsOnBottom; // change to bool + public string ButtonsOnBottom => LazyLoad(ref _ButtonsOnBottom, "@ButtonsOnBottom"); + private SILabels _LabelList; + public SILabels LabelList => _LabelList ?? (_LabelList = new SILabels(SelectNodes("/PlantFormat/FormatData/SI/Label"))); + private SIFields _FieldList; + public SIFields FieldList => _FieldList ?? (_FieldList = new SIFields(SelectNodes("/PlantFormat/FormatData/SI/Field"))); + } #endregion #region CheckOffAll #region CheckOffData @@ -1865,10 +1213,10 @@ namespace VEPROMS.CSLA.Library get { if (_CheckOffHeaderList != null) return _CheckOffHeaderList; - FormatConfig fc = PlantFormat.GetFormatConfig(MyFormat); + _ = PlantFormat.GetFormatConfig(MyFormat); - // merge the checkoff header lists from the current format and the list from the base - _CheckOffHeaderList = new CheckOffHeaderList(SelectNodes("CheckOffHeaderList/CheckOffHeader"), MyFormat); + // merge the checkoff header lists from the current format and the list from the base + _CheckOffHeaderList = new CheckOffHeaderList(SelectNodes("CheckOffHeaderList/CheckOffHeader"), MyFormat); return _CheckOffHeaderList; } @@ -1877,108 +1225,48 @@ namespace VEPROMS.CSLA.Library // This is used with the {INITIALS} pagelist token and will put the word "INITIALS" at the specified pagelist // location for the checkoff column header. Used by Calvert Cliffs (BGEOI and BGESTP formats) private LazyLoad _CheckOffHeaderInPagelist; - public bool CheckOffHeaderInPagelist - { - get - { - return LazyLoad(ref _CheckOffHeaderInPagelist, "@CheckOffHeaderInPagelist"); - } - } - // Menu heading for checkoffs/signoffs. When this is set to "Signoff", the checkoff list is not enabled - private LazyLoad _Menu; - public string Menu - { - get - { - return LazyLoad(ref _Menu, "@Menu"); - } - } + public bool CheckOffHeaderInPagelist => LazyLoad(ref _CheckOffHeaderInPagelist, "@CheckOffHeaderInPagelist"); + // Menu heading for checkoffs/signoffs. When this is set to "Signoff", the checkoff list is not enabled + private LazyLoad _Menu; + public string Menu => LazyLoad(ref _Menu, "@Menu"); - // this will make room on the page for checkoffs by adjusting the step text width. Used for cases where there isn't - // a checkoff header (we adjust step text width when a checkoff header is printed) - private LazyLoad _CheckOffAdjustment; - public float? CheckOffAdjustment - { - get - { - return LazyLoad(ref _CheckOffAdjustment, "@CheckOffAdjustment"); - } - } - // used for checkoff (initial line) next to the step number tab. the XLocation number is added to the left margin - private LazyLoad _XLocation; - public float? XLocation - { - get - { - return LazyLoad(ref _XLocation, "@XLocation"); - } - } + // this will make room on the page for checkoffs by adjusting the step text width. Used for cases where there isn't + // a checkoff header (we adjust step text width when a checkoff header is printed) + private LazyLoad _CheckOffAdjustment; + public float? CheckOffAdjustment => LazyLoad(ref _CheckOffAdjustment, "@CheckOffAdjustment"); + // used for checkoff (initial line) next to the step number tab. the XLocation number is added to the left margin + private LazyLoad _XLocation; + public float? XLocation => LazyLoad(ref _XLocation, "@XLocation"); - // relative location of the checkoff based on the text width and its location on the page - private LazyLoad _RelXLocation; - public float? RelXLocation - { - get - { - return LazyLoad(ref _RelXLocation, "@RelXLocation"); - } - } + // relative location of the checkoff based on the text width and its location on the page + private LazyLoad _RelXLocation; + public float? RelXLocation => LazyLoad(ref _RelXLocation, "@RelXLocation"); - //Start printing the checkoff on the last line of the step text (when set here applies to all checkofs) - private LazyLoad _DropCheckOff; - public bool DropCheckOff - { - get - { - return LazyLoad(ref _DropCheckOff, "@DropCheckOff"); - } - } + //Start printing the checkoff on the last line of the step text (when set here applies to all checkofs) + private LazyLoad _DropCheckOff; + public bool DropCheckOff => LazyLoad(ref _DropCheckOff, "@DropCheckOff"); - // put checkoff only on High Level Steps - private LazyLoad _CheckOffOnHLSOnly; - public bool CheckOffOnHLSOnly - { - get - { - return LazyLoad(ref _CheckOffOnHLSOnly, "@CheckOffOnHLSOnly"); - } - } + // put checkoff only on High Level Steps + private LazyLoad _CheckOffOnHLSOnly; + public bool CheckOffOnHLSOnly => LazyLoad(ref _CheckOffOnHLSOnly, "@CheckOffOnHLSOnly"); - // SkipSpaces puts the checkoff macro (if specified in the format) next to the step tab - // the print logic looks at the step tab and skips (backwards) the lenth (width) of the tab - // to position the checkoff - // - this is used for Bryon and Braidwood - private LazyLoad _SkipSpaces; - public bool SkipSpaces - { - get - { - return LazyLoad(ref _SkipSpaces, "@SkipSpaces"); - } - } + // SkipSpaces puts the checkoff macro (if specified in the format) next to the step tab + // the print logic looks at the step tab and skips (backwards) the lenth (width) of the tab + // to position the checkoff + // - this is used for Bryon and Braidwood + private LazyLoad _SkipSpaces; + public bool SkipSpaces => LazyLoad(ref _SkipSpaces, "@SkipSpaces"); - // put in for Bryon and Braidwood - // enables the selection of a checkoff only when on a sub-step type - private LazyLoad _CheckoffOnSubStepsOnly; - public bool CheckoffOnSubStepsOnly - { - get - { - return LazyLoad(ref _CheckoffOnSubStepsOnly, "@CheckoffOnSubStepsOnly"); - } - } + // put in for Bryon and Braidwood + // enables the selection of a checkoff only when on a sub-step type + private LazyLoad _CheckoffOnSubStepsOnly; + public bool CheckoffOnSubStepsOnly => LazyLoad(ref _CheckoffOnSubStepsOnly, "@CheckoffOnSubStepsOnly"); - // C2019-040 This will adjust the right margin (making room for the checkoff) without the need of selecting a checkoff header - // the flag allows us to use existing coding that prior to this was restricted by format file name - private LazyLoad _CheckoffsWithoutHeader; - public bool CheckoffsWithoutHeader - { - get - { - return LazyLoad(ref _CheckoffsWithoutHeader, "@CheckoffsWithoutHeader"); - } - } - } + // C2019-040 This will adjust the right margin (making room for the checkoff) without the need of selecting a checkoff header + // the flag allows us to use existing coding that prior to this was restricted by format file name + private LazyLoad _CheckoffsWithoutHeader; + public bool CheckoffsWithoutHeader => LazyLoad(ref _CheckoffsWithoutHeader, "@CheckoffsWithoutHeader"); + } #endregion #region CheckOff @@ -1988,108 +1276,48 @@ namespace VEPROMS.CSLA.Library public CheckOff(XmlNode xmlNode) : base(xmlNode) { } public CheckOff() : base() { } private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } - // C2020-003 used to sort list of checkoffs in the combo box - // a foat number can be used (ex 2.75) to fine tune the sorting - private LazyLoad _OrderBy; - public float? OrderBy - { - get - { - return LazyLoad(ref _OrderBy, "@OrderBy"); - } - } - // User Interface Mark (UIMark) is the deimal number of an ASCII character that is desplayed in the step editor - // to indicate the selected checkoff - private LazyLoad _UIMark; - public int? UIMark - { - get - { - return LazyLoad(ref _UIMark, "@UIMark"); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); + // C2020-003 used to sort list of checkoffs in the combo box + // a foat number can be used (ex 2.75) to fine tune the sorting + private LazyLoad _OrderBy; + public float? OrderBy => LazyLoad(ref _OrderBy, "@OrderBy"); + // User Interface Mark (UIMark) is the deimal number of an ASCII character that is desplayed in the step editor + // to indicate the selected checkoff + private LazyLoad _UIMark; + public int? UIMark => LazyLoad(ref _UIMark, "@UIMark"); - // If a positive numer, start the checkoff that number of lines minus one down from the start of the text - // and add that many lines after. - // If it's negative number, start the checkoff on the same line as the text - // and add positive of that number of lines after the checkoff macro. (see vlnPaaragraph.cs) - private LazyLoad _CheckOffXtraLines; - public float? CheckOffXtraLines - { - get - { - return LazyLoad(ref _CheckOffXtraLines, "@CheckOffXtraLines"); - } - } + // If a positive numer, start the checkoff that number of lines minus one down from the start of the text + // and add that many lines after. + // If it's negative number, start the checkoff on the same line as the text + // and add positive of that number of lines after the checkoff macro. (see vlnPaaragraph.cs) + private LazyLoad _CheckOffXtraLines; + public float? CheckOffXtraLines => LazyLoad(ref _CheckOffXtraLines, "@CheckOffXtraLines"); - // Add blank lines to make room for loner signoffs (checkoffs) - private LazyLoad _CheckOffNumberOfLines; - public float? CheckOffNumberOfLines - { - get - { - return LazyLoad(ref _CheckOffNumberOfLines, "@CheckOffNumberOfLines"); - } - } + // Add blank lines to make room for loner signoffs (checkoffs) + private LazyLoad _CheckOffNumberOfLines; + public float? CheckOffNumberOfLines => LazyLoad(ref _CheckOffNumberOfLines, "@CheckOffNumberOfLines"); - //Descriptive text shown in the checkoff selection list - private LazyLoad _MenuItem; - public string MenuItem - { - get - { - return LazyLoad(ref _MenuItem, "@MenuItem"); - } - } + //Descriptive text shown in the checkoff selection list + private LazyLoad _MenuItem; + public string MenuItem => LazyLoad(ref _MenuItem, "@MenuItem"); - // Name of the macro defined in the correspoinding SVG (GenMac) file. - // The print logic uese this macro to draw the checkoff - private LazyLoad _Macro; - public string Macro - { - get - { - return LazyLoad(ref _Macro, "@Macro"); - } - } + // Name of the macro defined in the correspoinding SVG (GenMac) file. + // The print logic uese this macro to draw the checkoff + private LazyLoad _Macro; + public string Macro => LazyLoad(ref _Macro, "@Macro"); - //Don’t' print the checkoff if the step text is empty (all spaces or hardspaces) - private LazyLoad _NotOnEmpty; - public bool NotOnEmpty - { - get - { - return LazyLoad(ref _NotOnEmpty, "@NotOnEmpty"); - } - } + //Don’t' print the checkoff if the step text is empty (all spaces or hardspaces) + private LazyLoad _NotOnEmpty; + public bool NotOnEmpty => LazyLoad(ref _NotOnEmpty, "@NotOnEmpty"); - // Start printing the checkoff on the last line of the step text (applies to just this checkoff) - private LazyLoad _DropCheckOff; - public bool DropCheckOff - { - get - { - return LazyLoad(ref _DropCheckOff, "@DropCheckOff"); - } - } - public override string GetPDDisplayName() - { return string.Format("[{0}]",Index); } - public override string GetPDDescription() - { return string.Format("[{0}] - {1}", Index, MenuItem); } - public override string GetPDCategory() - { return "Checkoff Data"; } - public override string ToString() - { - return MenuItem; - } - } + // Start printing the checkoff on the last line of the step text (applies to just this checkoff) + private LazyLoad _DropCheckOff; + public bool DropCheckOff => LazyLoad(ref _DropCheckOff, "@DropCheckOff"); + public override string GetPDDisplayName() => string.Format("[{0}]", Index); + public override string GetPDDescription() => string.Format("[{0}] - {1}", Index, MenuItem); + public override string GetPDCategory() => "Checkoff Data"; + public override string ToString() => MenuItem; + } #endregion #region ShwRplWds // C2029-025 Show or hide replace words. Can highlight replace words in editor. @@ -2098,41 +1326,20 @@ namespace VEPROMS.CSLA.Library public ShwRplWds(XmlNode xmlNode) : base(xmlNode) { } public ShwRplWds() : base() { } private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); - // User Interface Mark (UIMark) is the deimal number of an ASCII character that is desplayed in the step editor - // to indicate the selected checkoff - private LazyLoad _UIMark; - public int? UIMark - { - get - { - return LazyLoad(ref _UIMark, "@UIMark"); - } - } + // User Interface Mark (UIMark) is the deimal number of an ASCII character that is desplayed in the step editor + // to indicate the selected checkoff + private LazyLoad _UIMark; + public int? UIMark => LazyLoad(ref _UIMark, "@UIMark"); - //Descriptive text shown in the checkoff selection list - private LazyLoad _MenuItem; - public string MenuItem - { - get - { - return LazyLoad(ref _MenuItem, "@MenuItem"); - } - } + //Descriptive text shown in the checkoff selection list + private LazyLoad _MenuItem; + public string MenuItem => LazyLoad(ref _MenuItem, "@MenuItem"); - public override string ToString() - { - return MenuItem; - } - } + public override string ToString() => MenuItem; + } #endregion #region CheckOffList [TypeConverter(typeof(vlnIndexedListConverter))] @@ -2159,42 +1366,18 @@ namespace VEPROMS.CSLA.Library public CheckOffHeader(XmlNode xmlNode) : base(xmlNode) { } public CheckOffHeader() : base() { } private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null ? _Font = new VE_Font(base.XmlNode) : _Font); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); - // the checkoff column heading text (when printed) - private LazyLoad _CheckOffHeading; - public string CheckOffHeading - { - get - { - return LazyLoad(ref _CheckOffHeading, "@CheckOffHeading"); - } - } - public override string GetPDDisplayName() - { return string.Format("[{0}]", Index); } - public override string GetPDDescription() - { return string.Format("[{0}] - {1}", Index, CheckOffHeading); } - public override string GetPDCategory() - { return "Checkoff Header Data"; } - public override string ToString() - { - return CheckOffHeading; - } - } + // the checkoff column heading text (when printed) + private LazyLoad _CheckOffHeading; + public string CheckOffHeading => LazyLoad(ref _CheckOffHeading, "@CheckOffHeading"); + public override string GetPDDisplayName() => string.Format("[{0}]", Index); + public override string GetPDDescription() => string.Format("[{0}] - {1}", Index, CheckOffHeading); + public override string GetPDCategory() => "Checkoff Header Data"; + public override string ToString() => CheckOffHeading; + } #endregion #region CheckOffHeaderList [TypeConverter(typeof(vlnIndexedListConverter))] @@ -2225,105 +1408,51 @@ namespace VEPROMS.CSLA.Library // AER on LEFT, RNO on Right // To the Left of Text private LazyLoad _DefaultCBLoc; - public string DefaultCBLoc - { - get - { - return LazyLoad(ref _DefaultCBLoc, "@DefaultCBLoc"); - } - } - // text that is place next to the change bar - // DateChgID (Date and Change ID) - // RevNum (Revision Number) - // ChgID (Change ID) - // None (No Change Bar Message) - // UserDef (User Defined Message) - private LazyLoad _ChangeBarMessage; - public string ChangeBarMessage - { - get - { - return LazyLoad(ref _ChangeBarMessage, "@ChangeBarMessage"); - } - } - // FixedChangeColumn + - Column location for change bars - // 0 - Separate AER and RNO change bars to the right of the text - // -10 to -1 - Change bars on left (specify # of columns from the text) - // <-10 - AER change bars on the left and RNO change bars on the right. - private LazyLoad _FixedChangeColumn; - public int? FixedChangeColumn - { - get - { - return LazyLoad(ref _FixedChangeColumn, "@FixedChangeColumn"); - } - } - // specific location of change bars for text in AER column - // - appears to be used when FixedChageColumn is set to a number <-10 - private LazyLoad _FixedAERChangeColumn; - public int? FixedAERChangeColumn - { - get - { - return LazyLoad(ref _FixedAERChangeColumn, "@FixedAERChangeColumn"); - } - } + public string DefaultCBLoc => LazyLoad(ref _DefaultCBLoc, "@DefaultCBLoc"); + // text that is place next to the change bar + // DateChgID (Date and Change ID) + // RevNum (Revision Number) + // ChgID (Change ID) + // None (No Change Bar Message) + // UserDef (User Defined Message) + private LazyLoad _ChangeBarMessage; + public string ChangeBarMessage => LazyLoad(ref _ChangeBarMessage, "@ChangeBarMessage"); + // FixedChangeColumn + - Column location for change bars + // 0 - Separate AER and RNO change bars to the right of the text + // -10 to -1 - Change bars on left (specify # of columns from the text) + // <-10 - AER change bars on the left and RNO change bars on the right. + private LazyLoad _FixedChangeColumn; + public int? FixedChangeColumn => LazyLoad(ref _FixedChangeColumn, "@FixedChangeColumn"); + // specific location of change bars for text in AER column + // - appears to be used when FixedChageColumn is set to a number <-10 + private LazyLoad _FixedAERChangeColumn; + public int? FixedAERChangeColumn => LazyLoad(ref _FixedAERChangeColumn, "@FixedAERChangeColumn"); - // if the format has the absolutefixedchangecolumn format flag, then always use the fixedchangecolumn from the - // format, otherwise, use the default column based on the selected location, stored in the base format. - private LazyLoad _AbsoluteFixedChangeColumn; - public bool AbsoluteFixedChangeColumn - { - get - { - return LazyLoad(ref _AbsoluteFixedChangeColumn, "@AbsoluteFixedChangeColumn"); - } - } + // if the format has the absolutefixedchangecolumn format flag, then always use the fixedchangecolumn from the + // format, otherwise, use the default column based on the selected location, stored in the base format. + private LazyLoad _AbsoluteFixedChangeColumn; + public bool AbsoluteFixedChangeColumn => LazyLoad(ref _AbsoluteFixedChangeColumn, "@AbsoluteFixedChangeColumn"); - // Continue the change bar through the blank lines for consectutive changed steps - private LazyLoad _ContinuousChangeBars; - public bool ContinuousChangeBars - { - get - { - return LazyLoad(ref _ContinuousChangeBars, "@ContinuousChangeBars"); - } - } + // Continue the change bar through the blank lines for consectutive changed steps + private LazyLoad _ContinuousChangeBars; + public bool ContinuousChangeBars => LazyLoad(ref _ContinuousChangeBars, "@ContinuousChangeBars"); - // will allow user to type in a change ID text to be placed next to the the change bar for the piece of changed text - // user is prompted to enter a change ID when opening a procedure. - // A Change ID tab i placed on the procedure editor ribbon to allow the user to modify the change id entered - // upon opening the procedure - // an option on the step properties pannel allows user to modify the change id text for that piece of changed text. - private LazyLoad _ChangeIds; - public bool ChangeIds - { - get - { - return LazyLoad(ref _ChangeIds, "@ChangeIds"); - } - } - // extend the change bar that is on the last RNO step down to the RNO separator - // (only a couple plants and a RNO separator) - private LazyLoad _ChangeBarToRNOSep; - public bool ChangeBarToRNOSep - { - get - { - return LazyLoad(ref _ChangeBarToRNOSep, "@ChangeBarToRNOSep"); - } - } - - // don't do one continuous change bar when there are multiple Notes or Caution types next to each other - private LazyLoad _SeparateChangeBarsForDiffNotesCautions; - public bool SeparateChangeBarsForDiffNotesCautions - { - get - { - return LazyLoad(ref _SeparateChangeBarsForDiffNotesCautions, "@SeparateChangeBarsForDiffNotesCautions"); - } - } - } + // will allow user to type in a change ID text to be placed next to the the change bar for the piece of changed text + // user is prompted to enter a change ID when opening a procedure. + // A Change ID tab i placed on the procedure editor ribbon to allow the user to modify the change id entered + // upon opening the procedure + // an option on the step properties pannel allows user to modify the change id text for that piece of changed text. + private LazyLoad _ChangeIds; + public bool ChangeIds => LazyLoad(ref _ChangeIds, "@ChangeIds"); + // extend the change bar that is on the last RNO step down to the RNO separator + // (only a couple plants and a RNO separator) + private LazyLoad _ChangeBarToRNOSep; + public bool ChangeBarToRNOSep => LazyLoad(ref _ChangeBarToRNOSep, "@ChangeBarToRNOSep"); + + // don't do one continuous change bar when there are multiple Notes or Caution types next to each other + private LazyLoad _SeparateChangeBarsForDiffNotesCautions; + public bool SeparateChangeBarsForDiffNotesCautions => LazyLoad(ref _SeparateChangeBarsForDiffNotesCautions, "@SeparateChangeBarsForDiffNotesCautions"); + } #endregion #endregion #region SectDataAll @@ -2402,7 +1531,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_ReplaceStrList == null) ? _ReplaceStrList = new ReplaceStrList(SelectNodes("ReplaceStrData/ReplaceStr")) : _ReplaceStrList; + return _ReplaceStrList ?? (_ReplaceStrList = new ReplaceStrList(SelectNodes("ReplaceStrData/ReplaceStr"))); } set { _ReplaceStrList = value; } } @@ -2411,7 +1540,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_ReplaceSymbolCharList == null) ? _ReplaceSymbolCharList = new ReplaceSymbolCharList(SelectNodes("ReplaceSymbolChars/ReplaceChar"), MyFormat) : _ReplaceSymbolCharList; + return _ReplaceSymbolCharList ?? (_ReplaceSymbolCharList = new ReplaceSymbolCharList(SelectNodes("ReplaceSymbolChars/ReplaceChar"), MyFormat)); } set { _ReplaceSymbolCharList = value; } } @@ -2441,155 +1570,70 @@ namespace VEPROMS.CSLA.Library // - used when section number and title are printed on the same line via pagelist // - used for landscaped sections private LazyLoad _SectNumAndTlLenLand; // B2021-119: large titles on Landscape Word Attachments are printing on 2 lines. - public int? SectNumAndTlLenLand - { - get - { - return LazyLoad(ref _SectNumAndTlLenLand, "@SectNumAndTlLenLand"); - } - } + public int? SectNumAndTlLenLand => LazyLoad(ref _SectNumAndTlLenLand, "@SectNumAndTlLenLand"); - // flag to determine if the ReplaceWords logic will be run on non-Setpoint RO values - private LazyLoad _ReplaceWordsInROs; - public bool ReplaceWordsInROs - { - get - { - return LazyLoad(ref _ReplaceWordsInROs, "@ReplaceWordsInROs"); - } - } - // C2021-061: For Barakah don't do replace if word is surrounded by " or ' - // Initial fix was 11/3/21. Added parens do the quotes on 11/16/21 - private LazyLoad _NoReplaceQuoteParenWords; - public bool NoReplaceQuoteParenWords - { - get - { - return LazyLoad(ref _NoReplaceQuoteParenWords, "@NoReplaceQuoteParenWords"); - } - } + // flag to determine if the ReplaceWords logic will be run on non-Setpoint RO values + private LazyLoad _ReplaceWordsInROs; + public bool ReplaceWordsInROs => LazyLoad(ref _ReplaceWordsInROs, "@ReplaceWordsInROs"); + // C2021-061: For Barakah don't do replace if word is surrounded by " or ' + // Initial fix was 11/3/21. Added parens do the quotes on 11/16/21 + private LazyLoad _NoReplaceQuoteParenWords; + public bool NoReplaceQuoteParenWords => LazyLoad(ref _NoReplaceQuoteParenWords, "@NoReplaceQuoteParenWords"); - // When set to true, turns on the option to add sub-sections to non-Word sections - private LazyLoad _UseMetaSections; - public bool UseMetaSections - { - get - { - return LazyLoad(ref _UseMetaSections, "@UseMetaSections"); - } - } + // When set to true, turns on the option to add sub-sections to non-Word sections + private LazyLoad _UseMetaSections; + public bool UseMetaSections => LazyLoad(ref _UseMetaSections, "@UseMetaSections"); - // when printing count the sub-section level towards the step level - // - works only when the TieTabToLevel format flag is also true - private LazyLoad _CountSubSectionsForLevel; - public bool CountSubSectionsForLevel - { - get - { - return LazyLoad(ref _CountSubSectionsForLevel, "@CountSubSectionsForLevel"); - } - } + // when printing count the sub-section level towards the step level + // - works only when the TieTabToLevel format flag is also true + private LazyLoad _CountSubSectionsForLevel; + public bool CountSubSectionsForLevel => LazyLoad(ref _CountSubSectionsForLevel, "@CountSubSectionsForLevel"); - // prints a list of phone numbers at the bottom of the page - // - Calvert Cliffs - private LazyLoad _PrintPhoneList; - public bool PrintPhoneList - { - get - { - return LazyLoad(ref _PrintPhoneList, "@PrintPhoneList"); - } - } + // prints a list of phone numbers at the bottom of the page + // - Calvert Cliffs + private LazyLoad _PrintPhoneList; + public bool PrintPhoneList => LazyLoad(ref _PrintPhoneList, "@PrintPhoneList"); - // Set the default to NO for the automatic Indent of sub sections (this a a check box on the section properties page) - private LazyLoad _DefaultNoSubAutoIndent; - public bool DefaultNoSubAutoIndent - { - get - { - return LazyLoad(ref _DefaultNoSubAutoIndent, "@DefaultNoSubAutoIndent"); - } - } + // Set the default to NO for the automatic Indent of sub sections (this a a check box on the section properties page) + private LazyLoad _DefaultNoSubAutoIndent; + public bool DefaultNoSubAutoIndent => LazyLoad(ref _DefaultNoSubAutoIndent, "@DefaultNoSubAutoIndent"); - // convert the caret (^) to he delta symbol in Referenced Objects (RO) return values - private LazyLoad _ConvertCaretToDelta; - public bool ConvertCaretToDelta - { - get - { - return LazyLoad(ref _ConvertCaretToDelta, "@ConvertCaretToDelta"); - } - } + // convert the caret (^) to he delta symbol in Referenced Objects (RO) return values + private LazyLoad _ConvertCaretToDelta; + public bool ConvertCaretToDelta => LazyLoad(ref _ConvertCaretToDelta, "@ConvertCaretToDelta"); - //B2019-037 throw back from DOS VE-PROMS, convert "~" to subscript and "#" to superscript in RO return values - private LazyLoad _UseTildaPoundCharsForSuperSubScriptInROValues; - public bool UseTildaPoundCharsForSuperSubScriptInROValues - { - get - { - return LazyLoad(ref _UseTildaPoundCharsForSuperSubScriptInROValues, "@UseTildaPoundCharsForSuperSubScriptInROValues"); - } - } + //B2019-037 throw back from DOS VE-PROMS, convert "~" to subscript and "#" to superscript in RO return values + private LazyLoad _UseTildaPoundCharsForSuperSubScriptInROValues; + public bool UseTildaPoundCharsForSuperSubScriptInROValues => LazyLoad(ref _UseTildaPoundCharsForSuperSubScriptInROValues, "@UseTildaPoundCharsForSuperSubScriptInROValues"); - // C2022-021 will convert ">=" to the greater than or equal symbol, "<=" to the less than or equal symbol and "+-" to plus/minus symbol for RO return values - private LazyLoad _ConvertGTELTEPMinROValue; - public bool ConvertGTELTEPMinROValue - { - get - { - return LazyLoad(ref _ConvertGTELTEPMinROValue, "@ConvertGTELTEPMinROValue"); - } - } + // C2022-021 will convert ">=" to the greater than or equal symbol, "<=" to the less than or equal symbol and "+-" to plus/minus symbol for RO return values + private LazyLoad _ConvertGTELTEPMinROValue; + public bool ConvertGTELTEPMinROValue => LazyLoad(ref _ConvertGTELTEPMinROValue, "@ConvertGTELTEPMinROValue"); - // C2019-043 will convert "->" to the right arrow symbol and "<-" to the left arrow symbol - // for RO return values. - // was put in Barakah (BNPP) but found issue when RO was in a PROMS table cell, - // logic was added to no do this convert if in a table. - // BNPP decided to turned it off in altogether in their format files. - private LazyLoad _UseDashGreaterLessThenForArrowsInROValue; - public bool UseDashGreaterLessThenForArrowsInROValue - { - get - { - return LazyLoad(ref _UseDashGreaterLessThenForArrowsInROValue, "@UseDashGreaterLessThenForArrowsInROValue"); - } - } + // C2019-043 will convert "->" to the right arrow symbol and "<-" to the left arrow symbol + // for RO return values. + // was put in Barakah (BNPP) but found issue when RO was in a PROMS table cell, + // logic was added to no do this convert if in a table. + // BNPP decided to turned it off in altogether in their format files. + private LazyLoad _UseDashGreaterLessThenForArrowsInROValue; + public bool UseDashGreaterLessThenForArrowsInROValue => LazyLoad(ref _UseDashGreaterLessThenForArrowsInROValue, "@UseDashGreaterLessThenForArrowsInROValue"); - // Use only for RO return values placed in Word sections, the underbar character '_' - // will toggle underlining ON/OFF in the RO return value text - private LazyLoad _ConvertUnderscoreToUnderline; - public bool ConvertUnderscoreToUnderline - { - get - { - //B2017-256 - Value was not using _ConvertUnderscoreToUnderline - return LazyLoad(ref _ConvertUnderscoreToUnderline, "@ConvertUnderscoreToUnderline"); - } - } + // Use only for RO return values placed in Word sections, the underbar character '_' + // will toggle underlining ON/OFF in the RO return value text + private LazyLoad _ConvertUnderscoreToUnderline; + public bool ConvertUnderscoreToUnderline => LazyLoad(ref _ConvertUnderscoreToUnderline, "@ConvertUnderscoreToUnderline"); - // This format flag turns off the Replace Words functionality. - // in 16-bit proms, this was done simply by having an empty Replace Words list. - // in 32-bit the inheiradence logic finds a replace words list in the base format - // if the plant format does not have one. Thus the need of this format flag. - private LazyLoad _TurnOffReplaceWords; - public bool TurnOffReplaceWords - { - get - { - return LazyLoad(ref _TurnOffReplaceWords, "@TurnOffReplaceWords"); - } - } + // This format flag turns off the Replace Words functionality. + // in 16-bit proms, this was done simply by having an empty Replace Words list. + // in 32-bit the inheiradence logic finds a replace words list in the base format + // if the plant format does not have one. Thus the need of this format flag. + private LazyLoad _TurnOffReplaceWords; + public bool TurnOffReplaceWords => LazyLoad(ref _TurnOffReplaceWords, "@TurnOffReplaceWords"); - // B2022-002: Section text is printing into the INITIAL column (BNPP1new) - private LazyLoad _AdjWidthForCheckOff; - public bool AdjWidthForCheckOff - { - get - { - return LazyLoad(ref _AdjWidthForCheckOff, "@AdjWidthForCheckOff"); - } - } - } + // B2022-002: Section text is printing into the INITIAL column (BNPP1new) + private LazyLoad _AdjWidthForCheckOff; + public bool AdjWidthForCheckOff => LazyLoad(ref _AdjWidthForCheckOff, "@AdjWidthForCheckOff"); + } #endregion #region SectionNumber [TypeConverter(typeof(ExpandableObjectConverter))] @@ -2600,41 +1644,17 @@ namespace VEPROMS.CSLA.Library // starting position from the left margin inwhich to place the section number private LazyLoad _Pos; - public float? Pos - { - get - { - return LazyLoad(ref _Pos, "@Pos"); - } - } - // Left (PSLeft), Center (PSCenter) - // justification of the text for the starting position (Pos) - private LazyLoad _Just; - public string Just - { - get - { - return LazyLoad(ref _Just, "@Just"); - } - } - // only for a first level section, print using a font size of 14 and sytle of bold - private LazyLoad _Level0Big; - public bool Level0Big - { - get - { - return LazyLoad(ref _Level0Big, "@Level0Big"); - } - } - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null ? _Font = new VE_Font(base.XmlNode) : _Font); - } - } - } + public float? Pos => LazyLoad(ref _Pos, "@Pos"); + // Left (PSLeft), Center (PSCenter) + // justification of the text for the starting position (Pos) + private LazyLoad _Just; + public string Just => LazyLoad(ref _Just, "@Just"); + // only for a first level section, print using a font size of 14 and sytle of bold + private LazyLoad _Level0Big; + public bool Level0Big => LazyLoad(ref _Level0Big, "@Level0Big"); + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + } #endregion #region SectionHeader [TypeConverter(typeof(ExpandableObjectConverter))] @@ -2645,68 +1665,26 @@ namespace VEPROMS.CSLA.Library // starting position from the left margin inwhich to place the section number private LazyLoad _Pos; - public float? Pos - { - get - { - return LazyLoad(ref _Pos, "@Pos"); - } - } - // Left (PSLeft), Center (PSCenter) - // justification of the text for the starting position (Pos) - private LazyLoad _Just; - public string Just - { - get - { - return LazyLoad(ref _Just, "@Just"); - } - } - // only for a first level section, print using a font size of 14 and sytle of bold - private LazyLoad _Level0Big; - public bool Level0Big - { - get - { - return LazyLoad(ref _Level0Big, "@Level0Big"); - } - } - // Turn off underlining of section title for sub-sections - private LazyLoad _OnlyUnderlineTopSect; - public bool OnlyUnderlineTopSect - { - get - { - return LazyLoad(ref _OnlyUnderlineTopSect, "@OnlyUnderlineTopSect"); - } - } - //Turn off bolding of section title for sub-sections - private LazyLoad _OnlyBoldTopSect; - public bool OnlyBoldTopSect - { - get - { - return LazyLoad(ref _OnlyBoldTopSect, "@OnlyBoldTopSect"); - } - } - // If the section number is null or all blanks, then use the SectionNumber.Pos to position the section title - private LazyLoad _UseNumPosWhenNumBlank; - public bool UseNumPosWhenNumBlank - { - get - { - return LazyLoad(ref _UseNumPosWhenNumBlank, "@UseNumPosWhenNumBlank"); - } - } - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null ? _Font = new VE_Font(base.XmlNode) : _Font); - } - } - } + public float? Pos => LazyLoad(ref _Pos, "@Pos"); + // Left (PSLeft), Center (PSCenter) + // justification of the text for the starting position (Pos) + private LazyLoad _Just; + public string Just => LazyLoad(ref _Just, "@Just"); + // only for a first level section, print using a font size of 14 and sytle of bold + private LazyLoad _Level0Big; + public bool Level0Big => LazyLoad(ref _Level0Big, "@Level0Big"); + // Turn off underlining of section title for sub-sections + private LazyLoad _OnlyUnderlineTopSect; + public bool OnlyUnderlineTopSect => LazyLoad(ref _OnlyUnderlineTopSect, "@OnlyUnderlineTopSect"); + //Turn off bolding of section title for sub-sections + private LazyLoad _OnlyBoldTopSect; + public bool OnlyBoldTopSect => LazyLoad(ref _OnlyBoldTopSect, "@OnlyBoldTopSect"); + // If the section number is null or all blanks, then use the SectionNumber.Pos to position the section title + private LazyLoad _UseNumPosWhenNumBlank; + public bool UseNumPosWhenNumBlank => LazyLoad(ref _UseNumPosWhenNumBlank, "@UseNumPosWhenNumBlank"); + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + } #endregion #region SectionHeaderSeparatorLine [TypeConverter(typeof(ExpandableObjectConverter))] @@ -2717,23 +1695,11 @@ namespace VEPROMS.CSLA.Library // starting position, from the left margin, of the sparator line private LazyLoad _XStartPos; - public float? XStartPos - { - get - { - return LazyLoad(ref _XStartPos, "@XStartPos"); - } - } - // Length of the spearator line - private LazyLoad _Length; - public float? Length - { - get - { - return LazyLoad(ref _Length, "@Length"); - } - } - } + public float? XStartPos => LazyLoad(ref _XStartPos, "@XStartPos"); + // Length of the spearator line + private LazyLoad _Length; + public float? Length => LazyLoad(ref _Length, "@Length"); + } #endregion #region StepSectionDataAll @@ -2747,7 +1713,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_TextTypeValueList == null) ? _TextTypeValueList = new TextTypeValueList(SelectNodes("TextTypeValue/short")) : _TextTypeValueList; + return _TextTypeValueList ?? (_TextTypeValueList = new TextTypeValueList(SelectNodes("TextTypeValue/short"))); } set { _TextTypeValueList = value; } } @@ -2756,7 +1722,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_TextTypeList == null) ? _TextTypeList = new TextTypeList(SelectNodes("TextType/string")) : _TextTypeList; + return _TextTypeList ?? (_TextTypeList = new TextTypeList(SelectNodes("TextType/string"))); } set { _TextTypeList = value; } } @@ -2765,7 +1731,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_UnderlineTerminateList == null) ? _UnderlineTerminateList = new UnderlineTerminateList(SelectNodes("UnderlineTerminate/string")) : _UnderlineTerminateList; + return _UnderlineTerminateList ?? (_UnderlineTerminateList = new UnderlineTerminateList(SelectNodes("UnderlineTerminate/string"))); } set { _UnderlineTerminateList = value; } } @@ -2774,7 +1740,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_ObserveNCString1List == null) ? _ObserveNCString1List = new ObserveNCString1List(SelectNodes("ObserveNCString1/string")) : _ObserveNCString1List; + return _ObserveNCString1List ?? (_ObserveNCString1List = new ObserveNCString1List(SelectNodes("ObserveNCString1/string"))); } set { _ObserveNCString1List = value; } } @@ -2783,7 +1749,7 @@ namespace VEPROMS.CSLA.Library { get { - return (_ObserveNCString2List == null) ? _ObserveNCString2List = new ObserveNCString2List(SelectNodes("ObserveNCString2/string")) : _ObserveNCString2List; + return _ObserveNCString2List ?? (_ObserveNCString2List = new ObserveNCString2List(SelectNodes("ObserveNCString2/string"))); } set { _ObserveNCString2List = value; } } @@ -2792,251 +1758,113 @@ namespace VEPROMS.CSLA.Library { get { - return (_StepSectionLayoutData == null) ? _StepSectionLayoutData = new StepSectionLayoutData(SelectSingleNode("StpSectLayData")) : _StepSectionLayoutData; + return _StepSectionLayoutData ?? (_StepSectionLayoutData = new StepSectionLayoutData(SelectSingleNode("StpSectLayData"))); } } // a list of the sequential tab formatting based on the level of the step/sub-step private SeqTabFmtList _SeqTabFmtList; - public SeqTabFmtList SeqTabFmtList - { - get - { - return (_SeqTabFmtList == null) ? _SeqTabFmtList = new SeqTabFmtList(SelectNodes("SequentialTabFormat/SeqTabFmt"), MyFormat) : _SeqTabFmtList; - } - } - private StepSectionPrintData _StepSectionPrintData; - public StepSectionPrintData StepSectionPrintData - { - get - { - return (_StepSectionPrintData == null) ? _StepSectionPrintData = new StepSectionPrintData(SelectSingleNode("StpSectPrtData")) : _StepSectionPrintData; - } - } - // indent character used in RTF - // base format has this set to "0" which the code that uses this will resign this to "\x5" - private LazyLoad _IndentToken; - public string IndentToken - { - get - { - return LazyLoad(ref _IndentToken, "@IndentToken"); - } - } - // this is the default bullet character used for sub-step types that are indented and then use a bullet as the - // sub-step tab. Base format has this as a solid bullet (ascii character number 7), - // other plants use lower cased 'o' for an open bullet. - private LazyLoad _IdentB; - public string IdentB - { - get - { - return LazyLoad(ref _IdentB, "@IdentB"); - } - } - // special step tabbing and print formatting for enhanced background documennts - // - required by Wolf Creek's background format. - private LazyLoad _WolfCreekBackgroundFormat; - public bool WolfCreekBackgroundFormat - { - get - { - return LazyLoad(ref _WolfCreekBackgroundFormat, "@WolfCreekBackgroundFormat"); - } - } + public SeqTabFmtList SeqTabFmtList => _SeqTabFmtList ?? (_SeqTabFmtList = new SeqTabFmtList(SelectNodes("SequentialTabFormat/SeqTabFmt"), MyFormat)); + private StepSectionPrintData _StepSectionPrintData; + public StepSectionPrintData StepSectionPrintData => _StepSectionPrintData ?? (_StepSectionPrintData = new StepSectionPrintData(SelectSingleNode("StpSectPrtData"))); + // indent character used in RTF + // base format has this set to "0" which the code that uses this will resign this to "\x5" + private LazyLoad _IndentToken; + public string IndentToken => LazyLoad(ref _IndentToken, "@IndentToken"); + // this is the default bullet character used for sub-step types that are indented and then use a bullet as the + // sub-step tab. Base format has this as a solid bullet (ascii character number 7), + // other plants use lower cased 'o' for an open bullet. + private LazyLoad _IdentB; + public string IdentB => LazyLoad(ref _IdentB, "@IdentB"); + // special step tabbing and print formatting for enhanced background documennts + // - required by Wolf Creek's background format. + private LazyLoad _WolfCreekBackgroundFormat; + public bool WolfCreekBackgroundFormat => LazyLoad(ref _WolfCreekBackgroundFormat, "@WolfCreekBackgroundFormat"); - // special formatting of steps and sub-steps to create an on the fly table when printed - private LazyLoad _WolfcreekCKLFormat; - public bool WolfcreekCKLFormat - { - get - { - return LazyLoad(ref _WolfcreekCKLFormat, "@WolfcreekCKLFormat"); - } - } + // special formatting of steps and sub-steps to create an on the fly table when printed + private LazyLoad _WolfcreekCKLFormat; + public bool WolfcreekCKLFormat => LazyLoad(ref _WolfcreekCKLFormat, "@WolfcreekCKLFormat"); - // special formatting Vogtle Unit 3 and 4 Backgrounds: allows use of override width on AND and List sub-step types, - // and the calculation of the width of the paragraph sub-step type - private LazyLoad _Vogtle3and4BackgroundFormat; - public bool Vogtle3and4BackgroundFormat - { - get - { - return LazyLoad(ref _Vogtle3and4BackgroundFormat, "@Vogtle3and4BackgroundFormat"); - } - } + // special formatting Vogtle Unit 3 and 4 Backgrounds: allows use of override width on AND and List sub-step types, + // and the calculation of the width of the paragraph sub-step type + private LazyLoad _Vogtle3and4BackgroundFormat; + public bool Vogtle3and4BackgroundFormat => LazyLoad(ref _Vogtle3and4BackgroundFormat, "@Vogtle3and4BackgroundFormat"); - // This translates into nx10x10y where y is superscripted. - // For example, .E3 -> x103 where 3 is superscripted - // and 10.E5 -> 10x10-5 where 5 is superscripted - private LazyLoad _FortranFormatNumbers; - public bool FortranFormatNumbers - { - get - { - return LazyLoad(ref _FortranFormatNumbers, "@FortranFormatNumbers"); - } - } + // This translates into nx10x10y where y is superscripted. + // For example, .E3 -> x103 where 3 is superscripted + // and 10.E5 -> 10x10-5 where 5 is superscripted + private LazyLoad _FortranFormatNumbers; + public bool FortranFormatNumbers => LazyLoad(ref _FortranFormatNumbers, "@FortranFormatNumbers"); - // FloatingContinueMessage format flag: - // if breaking at the AER put continue message in left column, - // if breaking RNO put continue message in Right column. - private LazyLoad _FloatingContinueMessage; - public bool FloatingContinueMessage - { - get - { - return LazyLoad(ref _FloatingContinueMessage, "@FloatingContinueMessage"); - } - } + // FloatingContinueMessage format flag: + // if breaking at the AER put continue message in left column, + // if breaking RNO put continue message in Right column. + private LazyLoad _FloatingContinueMessage; + public bool FloatingContinueMessage => LazyLoad(ref _FloatingContinueMessage, "@FloatingContinueMessage"); - // used when section title is not printed via the pagelist, will print the title with "continued" - // appended to it when the section print multiple pages - private LazyLoad _ContinueSectionHeader; - public bool ContinueSectionHeader - { - get - { - return LazyLoad(ref _ContinueSectionHeader, "@ContinueSectionHeader"); - } - } + // used when section title is not printed via the pagelist, will print the title with "continued" + // appended to it when the section print multiple pages + private LazyLoad _ContinueSectionHeader; + public bool ContinueSectionHeader => LazyLoad(ref _ContinueSectionHeader, "@ContinueSectionHeader"); - // the font size of the text that is sub-scripted is made smaller - private LazyLoad _CompressHPSub; - public bool CompressHPSub - { - get - { - return LazyLoad(ref _CompressHPSub, "@CompressHPSub"); - } - } + // the font size of the text that is sub-scripted is made smaller + private LazyLoad _CompressHPSub; + public bool CompressHPSub => LazyLoad(ref _CompressHPSub, "@CompressHPSub"); - // the font size of the text that is super-scripted is made smaller - private LazyLoad _CompressHPSuper; - public bool CompressHPSuper - { - get - { - return LazyLoad(ref _CompressHPSuper, "@CompressHPSuper"); - } - } + // the font size of the text that is super-scripted is made smaller + private LazyLoad _CompressHPSuper; + public bool CompressHPSuper => LazyLoad(ref _CompressHPSuper, "@CompressHPSuper"); - // special handling of super and sub scripts when the font is a proportial font - private LazyLoad _CompressPropSubSup; - public bool CompressPropSubSup - { - get - { - return LazyLoad(ref _CompressPropSubSup, "@CompressPropSubSup"); - } - } + // special handling of super and sub scripts when the font is a proportial font + private LazyLoad _CompressPropSubSup; + public bool CompressPropSubSup => LazyLoad(ref _CompressPropSubSup, "@CompressPropSubSup"); - // used in Ginna's Attachment format - // adjust the width of the Cautions and Note to not exend page the end of the HLS width - // ie, shorten the width if the Caution or Note is off of a sub-step - private LazyLoad _LimitCautionNoteWithToHLS; - public bool LimitCautionNoteWidthToHLS - { - get - { - return LazyLoad(ref _LimitCautionNoteWithToHLS, "@LimitCautionNoteWithToHLS"); - } - } - // Used in Ginn's Attachment format - // only bullet multiple Caution/Note types if they are exactly the same type (ex. CAUTION vs CAUTION1) - private LazyLoad _OnlyBulletSameCautionNoteType; - public bool OnlyBulletSameCautionNoteType - { - get - { - return LazyLoad(ref _OnlyBulletSameCautionNoteType, "@OnlyBulletSameCautionNoteType"); - } - } + // used in Ginna's Attachment format + // adjust the width of the Cautions and Note to not exend page the end of the HLS width + // ie, shorten the width if the Caution or Note is off of a sub-step + private LazyLoad _LimitCautionNoteWithToHLS; + public bool LimitCautionNoteWidthToHLS => LazyLoad(ref _LimitCautionNoteWithToHLS, "@LimitCautionNoteWithToHLS"); + // Used in Ginn's Attachment format + // only bullet multiple Caution/Note types if they are exactly the same type (ex. CAUTION vs CAUTION1) + private LazyLoad _OnlyBulletSameCautionNoteType; + public bool OnlyBulletSameCautionNoteType => LazyLoad(ref _OnlyBulletSameCautionNoteType, "@OnlyBulletSameCautionNoteType"); - // ImperfectStructure is used so that the sequential numbering for substeps under an RNO is not same - // numbering (alpha vs numeric), if the HLS has substeps - WCN uses this, as well as other plants. - // skips the step tab level ahead by 2 more - private LazyLoad _ImperfectStructure; - public bool ImperfectStructure - { - get - { - return LazyLoad(ref _ImperfectStructure, "@ImperfectStructure"); - } - } + // ImperfectStructure is used so that the sequential numbering for substeps under an RNO is not same + // numbering (alpha vs numeric), if the HLS has substeps - WCN uses this, as well as other plants. + // skips the step tab level ahead by 2 more + private LazyLoad _ImperfectStructure; + public bool ImperfectStructure => LazyLoad(ref _ImperfectStructure, "@ImperfectStructure"); - // like imperfectStructure, but only for the first level RNO - private LazyLoad _ImperfectSubstep; - public bool ImperfectSubstep - { - get - { - return LazyLoad(ref _ImperfectSubstep, "@ImperfectSubstep"); - } - } + // like imperfectStructure, but only for the first level RNO + private LazyLoad _ImperfectSubstep; + public bool ImperfectSubstep => LazyLoad(ref _ImperfectSubstep, "@ImperfectSubstep"); - // used with ImperfectStructure, skips the step tab level ahead by 2 more (for a total of 4) - private LazyLoad _ImperfectStructurePlus4; - public bool ImperfectStructurePlus4 - { - get - { - return LazyLoad(ref _ImperfectStructurePlus4, "@ImperfectStructurePlus4"); - } - } + // used with ImperfectStructure, skips the step tab level ahead by 2 more (for a total of 4) + private LazyLoad _ImperfectStructurePlus4; + public bool ImperfectStructurePlus4 => LazyLoad(ref _ImperfectStructurePlus4, "@ImperfectStructurePlus4"); - // When the sub-step tab include it's parent tab, this flag will ignor any step/sub-step tabs that are not a number or letter - private LazyLoad _SkipNonSeqTabWithPar; - public bool SkipNonSeqTabWithPar - { - get - { - return LazyLoad(ref _SkipNonSeqTabWithPar, "@SkipNonSeqTabWithPar"); - } - } + // When the sub-step tab include it's parent tab, this flag will ignor any step/sub-step tabs that are not a number or letter + private LazyLoad _SkipNonSeqTabWithPar; + public bool SkipNonSeqTabWithPar => LazyLoad(ref _SkipNonSeqTabWithPar, "@SkipNonSeqTabWithPar"); - // when determining the sub-step level (for tabs and printing), count only sequential sub-steps (excluding RNOs, Cautions, and Notes - private LazyLoad _CountAllSubLevels; - public bool CountAllSubLevels - { - get - { - return LazyLoad(ref _CountAllSubLevels, "@CountAllSubLevels"); - } - } + // when determining the sub-step level (for tabs and printing), count only sequential sub-steps (excluding RNOs, Cautions, and Notes + private LazyLoad _CountAllSubLevels; + public bool CountAllSubLevels => LazyLoad(ref _CountAllSubLevels, "@CountAllSubLevels"); - // don't reset (remove) the indent (RTF indent char) on step text when there are hard returns - private LazyLoad _DontResetIndentOnNewline; - public bool DontResetIndentOnNewline - { - get - { - return LazyLoad(ref _DontResetIndentOnNewline, "@DontResetIndentOnNewline"); - } - } + // don't reset (remove) the indent (RTF indent char) on step text when there are hard returns + private LazyLoad _DontResetIndentOnNewline; + public bool DontResetIndentOnNewline => LazyLoad(ref _DontResetIndentOnNewline, "@DontResetIndentOnNewline"); - // C2018-024 I in Arial font changed to I in TimesNewRoman - // put in for McGuire (MCGall format) - private LazyLoad _ChangeFontUpperCaseIinArial; - public bool ChangeFontUpperCaseIinArial - { - get - { - return LazyLoad(ref _ChangeFontUpperCaseIinArial, "@ChangeFontUpperCaseIinArial"); - } - } + // C2018-024 I in Arial font changed to I in TimesNewRoman + // put in for McGuire (MCGall format) + private LazyLoad _ChangeFontUpperCaseIinArial; + public bool ChangeFontUpperCaseIinArial => LazyLoad(ref _ChangeFontUpperCaseIinArial, "@ChangeFontUpperCaseIinArial"); - // F2024-080 South Texas - // Used to show if "Initial Line Disable" checkbox should show in the DisplayTab - private LazyLoad _ShowInitialLineDisable; - public bool ShowInitialLineDisable - { - get - { - return LazyLoad(ref _ShowInitialLineDisable, "@ShowInitialLineDisable"); - } - } - } + // F2024-080 South Texas + // Used to show if "Initial Line Disable" checkbox should show in the DisplayTab + private LazyLoad _ShowInitialLineDisable; + public bool ShowInitialLineDisable => LazyLoad(ref _ShowInitialLineDisable, "@ShowInitialLineDisable"); + } #endregion - StepSectionData #region TextTypeValue [TypeConverter(typeof(ExpandableObjectConverter))] @@ -3045,24 +1873,12 @@ namespace VEPROMS.CSLA.Library public TextTypeValue(XmlNode xmlNode) : base(xmlNode) { } public TextTypeValue() : base() { } private LazyLoad _TheValue; - public int? TheValue - { - get - { - return LazyLoad(ref _TheValue, "text()"); - } - } - public override string GetPDDisplayName() - { return "Value"; } - public override string GetPDDescription() - { return string.Format("TextTypeValue '{0}'", TheValue); } - public override string GetPDCategory() - { return "Text Type Value"; } - public override string ToString() - { - return TheValue.ToString(); - } - } + public int? TheValue => LazyLoad(ref _TheValue, "text()"); + public override string GetPDDisplayName() => "Value"; + public override string GetPDDescription() => string.Format("TextTypeValue '{0}'", TheValue); + public override string GetPDCategory() => "Text Type Value"; + public override string ToString() => TheValue.ToString(); + } #endregion - TextTypeValue #region TextTypeValueList [TypeConverter(typeof(vlnListConverter))] @@ -3079,24 +1895,12 @@ namespace VEPROMS.CSLA.Library public TextType() : base() { } //[Category("Strings")] private LazyLoad _Text; - public string Text - { - get - { - return LazyLoad(ref _Text, "text()"); - } - } - public override string GetPDDisplayName() - { return "Text"; } - public override string GetPDDescription() - { return string.Format("TextType '{0}'", Text); } - public override string GetPDCategory() - { return "Text Type"; } - public override string ToString() - { - return Text; - } - } + public string Text => LazyLoad(ref _Text, "text()"); + public override string GetPDDisplayName() => "Text"; + public override string GetPDDescription() => string.Format("TextType '{0}'", Text); + public override string GetPDCategory() => "Text Type"; + public override string ToString() => Text; + } #endregion - TextType #region TextTypeList [TypeConverter(typeof(vlnListConverter))] @@ -3112,24 +1916,12 @@ namespace VEPROMS.CSLA.Library public UnderlineTerminate(XmlNode xmlNode) : base(xmlNode) { } public UnderlineTerminate() : base() { } private LazyLoad _Text; - public string Text - { - get - { - return LazyLoad(ref _Text, "text()"); - } - } - public override string GetPDDisplayName() - { return "Text"; } - public override string GetPDDescription() - { return string.Format("UnderlineTerminate '{0}'", Text); } - public override string GetPDCategory() - { return "Underline Terminate"; } - public override string ToString() - { - return Text; - } - } + public string Text => LazyLoad(ref _Text, "text()"); + public override string GetPDDisplayName() => "Text"; + public override string GetPDDescription() => string.Format("UnderlineTerminate '{0}'", Text); + public override string GetPDCategory() => "Underline Terminate"; + public override string ToString() => Text; + } #endregion - UnderlineTerminate #region UnderlineTerminateList [TypeConverter(typeof(vlnListConverter))] @@ -3145,24 +1937,12 @@ namespace VEPROMS.CSLA.Library public ObserveNCString1(XmlNode xmlNode) : base(xmlNode) { } public ObserveNCString1() : base() { } private LazyLoad _Text; - public string Text - { - get - { - return LazyLoad(ref _Text, "text()"); - } - } - public override string GetPDDisplayName() - { return "Text"; } - public override string GetPDDescription() - { return string.Format("ObserveNCString1 '{0}'", Text); } - public override string GetPDCategory() - { return "ObserveNCString1"; } - public override string ToString() - { - return Text; - } - } + public string Text => LazyLoad(ref _Text, "text()"); + public override string GetPDDisplayName() => "Text"; + public override string GetPDDescription() => string.Format("ObserveNCString1 '{0}'", Text); + public override string GetPDCategory() => "ObserveNCString1"; + public override string ToString() => Text; + } #endregion - ObserveNCString1 #region ObserveNCString1List [TypeConverter(typeof(vlnListConverter))] @@ -3178,24 +1958,12 @@ namespace VEPROMS.CSLA.Library public ObserveNCString2(XmlNode xmlNode) : base(xmlNode) { } public ObserveNCString2() : base() { } private LazyLoad _Text; - public string Text - { - get - { - return LazyLoad(ref _Text, "text()"); - } - } - public override string GetPDDisplayName() - { return "Text"; } - public override string GetPDDescription() - { return string.Format("ObserveNCString2 '{0}'", Text); } - public override string GetPDCategory() - { return "ObserveNCString2"; } - public override string ToString() - { - return Text; - } - } + public string Text => LazyLoad(ref _Text, "text()"); + public override string GetPDDisplayName() => "Text"; + public override string GetPDDescription() => string.Format("ObserveNCString2 '{0}'", Text); + public override string GetPDCategory() => "ObserveNCString2"; + public override string ToString() => Text; + } #endregion - ObserveNCString2 #region ObserveNCString2List [TypeConverter(typeof(vlnListConverter))] @@ -3219,47 +1987,23 @@ namespace VEPROMS.CSLA.Library // the string what will be replaced private LazyLoad _ReplaceWord; - public string ReplaceWord - { - get - { - return LazyLoad(ref _ReplaceWord, "@ReplaceWord"); - } - } - [Category("Strings")] + public string ReplaceWord => LazyLoad(ref _ReplaceWord, "@ReplaceWord"); + [Category("Strings")] // string to use for the replacement private LazyLoad _ReplaceWith; - public string ReplaceWith - { - get - { - return LazyLoad(ref _ReplaceWith, "@ReplaceWith"); - } - } - // flags to control where the replacement is allowed: - // ex: "High, RNO, Caution, Note, Table, Substep, Attach" - // see E_ReplaceFlags in "CSLA.Library\Format\ENums.cs" for the complete list + public string ReplaceWith => LazyLoad(ref _ReplaceWith, "@ReplaceWith"); + // flags to control where the replacement is allowed: + // ex: "High, RNO, Caution, Note, Table, Substep, Attach" + // see E_ReplaceFlags in "CSLA.Library\Format\ENums.cs" for the complete list - private LazyLoad _Flag; - public E_ReplaceFlags? Flag - { - get - { - return LazyLoad(ref _Flag, "@Flag"); - } - } - public override string GetPDDisplayName() - { return ReplaceWord; } - public override string GetPDDescription() - { return string.Format("Replace '{0}' with '{1}'", ReplaceWord, ReplaceWith); } - public override string GetPDCategory() - { return "Words to Replace"; } - public override string ToString() - { - return ReplaceWith; - } - } + private LazyLoad _Flag; + public E_ReplaceFlags? Flag => LazyLoad(ref _Flag, "@Flag"); + public override string GetPDDisplayName() => ReplaceWord; + public override string GetPDDescription() => string.Format("Replace '{0}' with '{1}'", ReplaceWord, ReplaceWith); + public override string GetPDCategory() => "Words to Replace"; + public override string ToString() => ReplaceWith; + } #endregion - ReplaceStr #region ReplaceStrList @@ -3279,47 +2023,23 @@ namespace VEPROMS.CSLA.Library // A unique index number for this symbol list private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } - [Category("Strings")] + public int? Index => LazyLoad(ref _Index, "@Index"); + [Category("Strings")] //The Unicode number of the symbol we are replacing private LazyLoad _Unicode; - public string Unicode - { - get - { - return LazyLoad(ref _Unicode, "@Unicode"); - } - } - [Category("Strings")] + public string Unicode => LazyLoad(ref _Unicode, "@Unicode"); + [Category("Strings")] //The Unicode number of the symbol we want to use instead (this is optional) private LazyLoad _Replace; - public string Replace - { - get - { - return LazyLoad(ref _Replace, "@Replace"); - } - } - [Category("Strings")] + public string Replace => LazyLoad(ref _Replace, "@Replace"); + [Category("Strings")] // The font family of the replacement symbol character (this is optional) private LazyLoad _Family; - public string Family - { - get - { - return LazyLoad(ref _Family, "@Family"); - } - } - [Category("FontStyle?")] + public string Family => LazyLoad(ref _Family, "@Family"); + [Category("FontStyle?")] // the font style for the symbol character (bold, Italics, Underline) - this is optional private LazyLoad _Style; // format has E_Style value. The public will translate it to a systemdrawing.FontStyle used in printing public FontStyle? Style @@ -3346,24 +2066,12 @@ namespace VEPROMS.CSLA.Library // The font size of the replacement symbol character (this is optional) private LazyLoad _Size; - public float? Size - { - get - { - return LazyLoad(ref _Size, "@Size"); - } - } - public override string GetPDDisplayName() - { return Unicode; } - public override string GetPDDescription() - { return string.Format("Replace '{0}' with '{1}'", Unicode, Replace); } - public override string GetPDCategory() - { return "Chars to Replace"; } - public override string ToString() - { - return Replace; - } - } + public float? Size => LazyLoad(ref _Size, "@Size"); + public override string GetPDDisplayName() => Unicode; + public override string GetPDDescription() => string.Format("Replace '{0}' with '{1}'", Unicode, Replace); + public override string GetPDCategory() => "Chars to Replace"; + public override string ToString() => Replace; + } #endregion - ReplaceChar #region ReplaceSymbolCharList @@ -3390,278 +2098,116 @@ namespace VEPROMS.CSLA.Library // the font and placement settings for the separator words used for OR the sub-steps // and the Explicit And sub-steps private Separator _Separator; - public Separator Separator - { - get - { - return (_Separator == null) ? _Separator = new Separator(SelectSingleNode("Separator")) : _Separator; - } - } - // the size of a tab in points. If not set, then 6 points will be used. - // note - don't add and set this to Base format, some code check for no value set - private LazyLoad _TabPtsPerChar; - public float? TabPtsPerChar - { - get - { - return LazyLoad(ref _TabPtsPerChar, "@TabPtsPerChar"); - } - } - // will define the placement of Notes, Cautions, and Warning with repect to the step they apply - // value is a string containing a list of StepData Index numbers for the defined Cautions and Notes types - a Warning is a redifined Caution or Note - private LazyLoad _CautionNoteOrder; - public string CautionNoteOrder - { - get - { - return LazyLoad(ref _CautionNoteOrder, "@CautionNoteOrder"); - } - } + public Separator Separator => _Separator ?? (_Separator = new Separator(SelectSingleNode("Separator"))); + // the size of a tab in points. If not set, then 6 points will be used. + // note - don't add and set this to Base format, some code check for no value set + private LazyLoad _TabPtsPerChar; + public float? TabPtsPerChar => LazyLoad(ref _TabPtsPerChar, "@TabPtsPerChar"); + // will define the placement of Notes, Cautions, and Warning with repect to the step they apply + // value is a string containing a list of StepData Index numbers for the defined Cautions and Notes types - a Warning is a redifined Caution or Note + private LazyLoad _CautionNoteOrder; + public string CautionNoteOrder => LazyLoad(ref _CautionNoteOrder, "@CautionNoteOrder"); - // starting position for High Level step text from the left margin - private LazyLoad _ColS; - public float? ColS - { - get - { - return LazyLoad(ref _ColS, "@ColS"); - } - } + // starting position for High Level step text from the left margin + private LazyLoad _ColS; + public float? ColS => LazyLoad(ref _ColS, "@ColS"); - // starting positon for cautions and notes that do not have a border (box format associated to it) - private LazyLoad _ColT; - public float? ColT - { - get - { - return LazyLoad(ref _ColT, "@ColT"); - } - } + // starting positon for cautions and notes that do not have a border (box format associated to it) + private LazyLoad _ColT; + public float? ColT => LazyLoad(ref _ColT, "@ColT"); - // Width of Text (note/caution) fields. This is overridden by BxTxtWidth, if the text is boxed. - private LazyLoad _WidT; - public float? WidT - { - get - { - return LazyLoad(ref _WidT, "@WidT"); - } - } + // Width of Text (note/caution) fields. This is overridden by BxTxtWidth, if the text is boxed. + private LazyLoad _WidT; + public float? WidT => LazyLoad(ref _WidT, "@WidT"); - // default column mode of the step editor sections - used in Section Properties - // if PMode is zero, the default column mode is two column - private LazyLoad _PMode; - public int? PMode - { - get - { - return LazyLoad(ref _PMode, "@PMode"); - } - } + // default column mode of the step editor sections - used in Section Properties + // if PMode is zero, the default column mode is two column + private LazyLoad _PMode; + public int? PMode => LazyLoad(ref _PMode, "@PMode"); - // default column mode of the step editor sections - used in Procedure Properties - private LazyLoad _ColumnMode; - public int? ColumnMode - { - get - { - return LazyLoad(ref _ColumnMode, "@ColumnMode"); - } - } - // set the width of RNO text to be same as its parent - put in for V.C. Summer (SUM formats) - private LazyLoad _RNOWidthSameAsHighParent; - public bool RNOWidthSameAsHighParent - { - get - { - return LazyLoad(ref _RNOWidthSameAsHighParent, "@RNOWidthSameAsHighParent"); - } - } - // used with the RNOWidthSameAsHighParent flag, is width value if this is the top RNO (parent RNO) - // - put in for V.C. Summer (SUM formats) - private LazyLoad _SingleColumnRNOIndent; - public float? SingleColumnRNOIndent - { - get - { - return LazyLoad(ref _SingleColumnRNOIndent, "@SingleColumnRNOIndent"); - } - } + // default column mode of the step editor sections - used in Procedure Properties + private LazyLoad _ColumnMode; + public int? ColumnMode => LazyLoad(ref _ColumnMode, "@ColumnMode"); + // set the width of RNO text to be same as its parent - put in for V.C. Summer (SUM formats) + private LazyLoad _RNOWidthSameAsHighParent; + public bool RNOWidthSameAsHighParent => LazyLoad(ref _RNOWidthSameAsHighParent, "@RNOWidthSameAsHighParent"); + // used with the RNOWidthSameAsHighParent flag, is width value if this is the top RNO (parent RNO) + // - put in for V.C. Summer (SUM formats) + private LazyLoad _SingleColumnRNOIndent; + public float? SingleColumnRNOIndent => LazyLoad(ref _SingleColumnRNOIndent, "@SingleColumnRNOIndent"); - // B2020-140 for Wolf Creek check boxes in tables were printing too high in the table cells - added format variable to overide topPlacementAdjust (WCN format files) - private LazyLoad _OverrideTableTopIndent; - public int? OverrideTableTopIndent - { - get - { - return LazyLoad(ref _OverrideTableTopIndent, "@OverrideTableTopIndent"); - } - } - // the space between columns of the procedure text (between AER and RNO columns) - private LazyLoad _ColRTable; - public string ColRTable - { - get - { - return LazyLoad(ref _ColRTable, "@ColRTable"); - } - } + // B2020-140 for Wolf Creek check boxes in tables were printing too high in the table cells - added format variable to overide topPlacementAdjust (WCN format files) + private LazyLoad _OverrideTableTopIndent; + public int? OverrideTableTopIndent => LazyLoad(ref _OverrideTableTopIndent, "@OverrideTableTopIndent"); + // the space between columns of the procedure text (between AER and RNO columns) + private LazyLoad _ColRTable; + public string ColRTable => LazyLoad(ref _ColRTable, "@ColRTable"); - // the high level step text width, in the PROMS editor, based on on many columns the procedure has - private LazyLoad _WidSTableEdit; - public string WidSTableEdit - { - get - { - return LazyLoad(ref _WidSTableEdit, "@WidSTableEdit"); - } - } + // the high level step text width, in the PROMS editor, based on on many columns the procedure has + private LazyLoad _WidSTableEdit; + public string WidSTableEdit => LazyLoad(ref _WidSTableEdit, "@WidSTableEdit"); - // the high level step text width, when printed, based on on many columns the procedure has - private LazyLoad _WidSTablePrint; - public string WidSTablePrint - { - get - { - return LazyLoad(ref _WidSTablePrint, "@WidSTablePrint"); - } - } + // the high level step text width, when printed, based on on many columns the procedure has + private LazyLoad _WidSTablePrint; + public string WidSTablePrint => LazyLoad(ref _WidSTablePrint, "@WidSTablePrint"); - // Adjust the RNO width off the high level step - private LazyLoad _RNOWidthAlt; - public string RNOWidthAlt - { - get - { - return LazyLoad(ref _RNOWidthAlt, "@RNOWidthAlt"); - } - } + // Adjust the RNO width off the high level step + private LazyLoad _RNOWidthAlt; + public string RNOWidthAlt => LazyLoad(ref _RNOWidthAlt, "@RNOWidthAlt"); - // adjust the RNO width for all RNOs - D.C. Cook (AEP formats) - private LazyLoad _RNOWidthAltAll; - public int? RNOWidthAltAll - { - get - { - return LazyLoad(ref _RNOWidthAltAll, "@RNOWidthAltAll"); - } - } - // adjust the width of the RNO off of an AER sub-step - private LazyLoad _RNOWidthAdj; - public string RNOWidthAdj - { - get - { - return LazyLoad(ref _RNOWidthAdj, "@RNOWidthAdj"); - } - } + // adjust the RNO width for all RNOs - D.C. Cook (AEP formats) + private LazyLoad _RNOWidthAltAll; + public int? RNOWidthAltAll => LazyLoad(ref _RNOWidthAltAll, "@RNOWidthAltAll"); + // adjust the width of the RNO off of an AER sub-step + private LazyLoad _RNOWidthAdj; + public string RNOWidthAdj => LazyLoad(ref _RNOWidthAdj, "@RNOWidthAdj"); - // Use the parent's RNO indent - private LazyLoad _UseRNOParentIdent; - public string UseRNOParentIdent - { - get - { - return LazyLoad(ref _UseRNOParentIdent, "@UseRNOParentIdent"); - } - } - // Adjusts the placement of the Note and Caution tabs in deviations - private LazyLoad _DevNoteOrCautionTabOffset; - public string DevNoteOrCautionTabOffset - { - get - { - return LazyLoad(ref _DevNoteOrCautionTabOffset, "@DevNoteOrCautionTabOffset"); - } - } + // Use the parent's RNO indent + private LazyLoad _UseRNOParentIdent; + public string UseRNOParentIdent => LazyLoad(ref _UseRNOParentIdent, "@UseRNOParentIdent"); + // Adjusts the placement of the Note and Caution tabs in deviations + private LazyLoad _DevNoteOrCautionTabOffset; + public string DevNoteOrCautionTabOffset => LazyLoad(ref _DevNoteOrCautionTabOffset, "@DevNoteOrCautionTabOffset"); - // adjustment to the starting positoin of the note/caution boxes - // - this is used sub-formats for Byron and Braidwood (CEW_00, EXCLN01) - private LazyLoad _BoxLeftAdj; - public string BoxLeftAdj - { - get - { - return LazyLoad(ref _BoxLeftAdj, "@BoxLeftAdj"); - } - } + // adjustment to the starting positoin of the note/caution boxes + // - this is used sub-formats for Byron and Braidwood (CEW_00, EXCLN01) + private LazyLoad _BoxLeftAdj; + public string BoxLeftAdj => LazyLoad(ref _BoxLeftAdj, "@BoxLeftAdj"); - // B2019-049 added check for table being in a Caution or Note - if so, use the single column setting for the format variable TableCenterPos - private LazyLoad _TableCenterPos; - public string TableCenterPos - { - get - { - return LazyLoad(ref _TableCenterPos, "@TableCenterPos"); - } - } + // B2019-049 added check for table being in a Caution or Note - if so, use the single column setting for the format variable TableCenterPos + private LazyLoad _TableCenterPos; + public string TableCenterPos => LazyLoad(ref _TableCenterPos, "@TableCenterPos"); - // Turn on editing and printing format for Deviation Documents (non-enhanced document) - // uses the Caution and Note type for the EOP and ERG step number, the widths are reduced - // and they are placed to the left of the high level step text - private LazyLoad _Dev_Format; - public bool Dev_Format - { - get - { - return LazyLoad(ref _Dev_Format, "@Dev_Format"); - } - } - // links procedure step number and text (also links Cautions and Note). Uses a template for the step editor to enter deviation and support text (like enhanced backgrounds). Prints like the non-enhanced deviation document - private LazyLoad _EnhancedShortFormDev; - public bool EnhancedShortFormDev - { - get - { - return LazyLoad(ref _EnhancedShortFormDev, "@EnhancedShortFormDev"); - } - } + // Turn on editing and printing format for Deviation Documents (non-enhanced document) + // uses the Caution and Note type for the EOP and ERG step number, the widths are reduced + // and they are placed to the left of the high level step text + private LazyLoad _Dev_Format; + public bool Dev_Format => LazyLoad(ref _Dev_Format, "@Dev_Format"); + // links procedure step number and text (also links Cautions and Note). Uses a template for the step editor to enter deviation and support text (like enhanced backgrounds). Prints like the non-enhanced deviation document + private LazyLoad _EnhancedShortFormDev; + public bool EnhancedShortFormDev => LazyLoad(ref _EnhancedShortFormDev, "@EnhancedShortFormDev"); - // this flag is set in the plant format file when you want to be able to break steps that begin in the - // middle of the page. If this flag is not set, then any step that will not fit on a single page will - // cause a page break, i.e. start at the top of the next page. - private LazyLoad _SpecialPageBreakFlag; - public bool SpecialPageBreakFlag - { - get - { - return LazyLoad(ref _SpecialPageBreakFlag, "@SpecialPageBreakFlag"); - } - } + // this flag is set in the plant format file when you want to be able to break steps that begin in the + // middle of the page. If this flag is not set, then any step that will not fit on a single page will + // cause a page break, i.e. start at the top of the next page. + private LazyLoad _SpecialPageBreakFlag; + public bool SpecialPageBreakFlag => LazyLoad(ref _SpecialPageBreakFlag, "@SpecialPageBreakFlag"); - // paginate on a step if the entire step will fit on it's own page but not fit on the remainer of the current page - private LazyLoad _PaginateOnStepThatWillFitOnBlankPage; - public bool PaginateOnStepThatWillFitOnBlankPage - { - get - { - return LazyLoad(ref _PaginateOnStepThatWillFitOnBlankPage, "@PaginateOnStepThatWillFitOnBlankPage"); - } - } + // paginate on a step if the entire step will fit on it's own page but not fit on the remainer of the current page + private LazyLoad _PaginateOnStepThatWillFitOnBlankPage; + public bool PaginateOnStepThatWillFitOnBlankPage => LazyLoad(ref _PaginateOnStepThatWillFitOnBlankPage, "@PaginateOnStepThatWillFitOnBlankPage"); - // allows the first child to be separated from its parent - private LazyLoad _PaginateOnFirstSubstep; - public bool PaginateOnFirstSubstep - { - get - { - return LazyLoad(ref _PaginateOnFirstSubstep, "@PaginateOnFirstSubstep"); - } - } + // allows the first child to be separated from its parent + private LazyLoad _PaginateOnFirstSubstep; + public bool PaginateOnFirstSubstep => LazyLoad(ref _PaginateOnFirstSubstep, "@PaginateOnFirstSubstep"); - // keep the table's parent with the table (if at all possible, don't break the table from the parent) - private LazyLoad _PageBreakParentWithTable; // B2020-101: Add format flag for table pagination - public bool PageBreakParentWithTable - { - get - { - return LazyLoad(ref _PageBreakParentWithTable, "@PageBreakParentWithTable"); - } - } + // keep the table's parent with the table (if at all possible, don't break the table from the parent) + private LazyLoad _PageBreakParentWithTable; // B2020-101: Add format flag for table pagination + public bool PageBreakParentWithTable => LazyLoad(ref _PageBreakParentWithTable, "@PageBreakParentWithTable"); - // when needed to fit an entire step on a page, PROMS will print the step at 7 lines per inch instead of the standard 6 lines per inch - private LazyLoad _CompressSteps; + // when needed to fit an entire step on a page, PROMS will print the step at 7 lines per inch instead of the standard 6 lines per inch + private LazyLoad _CompressSteps; public bool CompressSteps { get @@ -3676,168 +2222,78 @@ namespace VEPROMS.CSLA.Library // use the STExtraSpace value (defined for each step type) at the top of page // when that step/sub-step type is the first step part on the page private LazyLoad _DoSTExtraAtTop; - public bool DoSTExtraAtTop - { - get - { - return LazyLoad(ref _DoSTExtraAtTop, "@DoSTExtraAtTop"); - } - } + public bool DoSTExtraAtTop => LazyLoad(ref _DoSTExtraAtTop, "@DoSTExtraAtTop"); - // even if a step will fit on a page by itself, print as much of the step as logically possible on the current page - private LazyLoad _KeepStepsOnPage; - public bool KeepStepsOnPage - { - get - { - return LazyLoad(ref _KeepStepsOnPage, "@KeepStepsOnPage"); - } - } - private LazyLoad _NoOrphans1; - // B2017-154 No Orphans (single sub-step left over from previous page) No Children - // - Don't leave an orphan on the next page if the high level step and first sub-step will fit on the current page - // note: this was put in the V.C.Summ AP1000 plant - public bool NoOrphans1 - { - get - { - return LazyLoad(ref _NoOrphans1, "@NoOrphans1"); - } - } + // even if a step will fit on a page by itself, print as much of the step as logically possible on the current page + private LazyLoad _KeepStepsOnPage; + public bool KeepStepsOnPage => LazyLoad(ref _KeepStepsOnPage, "@KeepStepsOnPage"); + private LazyLoad _NoOrphans1; + // B2017-154 No Orphans (single sub-step left over from previous page) No Children + // - Don't leave an orphan on the next page if the high level step and first sub-step will fit on the current page + // note: this was put in the V.C.Summ AP1000 plant + public bool NoOrphans1 => LazyLoad(ref _NoOrphans1, "@NoOrphans1"); - // the format default setting as to whether each procedure section start on their own page - // The base format has this set to true - each section starts on a new page - private LazyLoad _BreakOnSections; - public bool BreakOnSections - { - get - { - return LazyLoad(ref _BreakOnSections, "@BreakOnSections"); - } - } + // the format default setting as to whether each procedure section start on their own page + // The base format has this set to true - each section starts on a new page + private LazyLoad _BreakOnSections; + public bool BreakOnSections => LazyLoad(ref _BreakOnSections, "@BreakOnSections"); - // will print the section number and title before printing the section text. used only with the PROMS - // step editor sections (not Word sections). section number and title will print only on the first page - // of the section. a check box on the section properties page turns printing of this on/off - private LazyLoad _ShowSectionTitles; - public bool ShowSectionTitles - { - get - { - return LazyLoad(ref _ShowSectionTitles, "@ShowSectionTitles"); - } - } + // will print the section number and title before printing the section text. used only with the PROMS + // step editor sections (not Word sections). section number and title will print only on the first page + // of the section. a check box on the section properties page turns printing of this on/off + private LazyLoad _ShowSectionTitles; + public bool ShowSectionTitles => LazyLoad(ref _ShowSectionTitles, "@ShowSectionTitles"); - // will print the defined section end message for single columns sections. - // the default setting is True - private LazyLoad _EndForSingle; - public bool EndForSingle - { - get - { - return LazyLoad(ref _EndForSingle, "@EndForSingle"); - } - } - // Special pagination case used in some background document formats. This will turn off the KeepStepsOnPage flag when a paragraph off of a High Level step was put on next page (IP2 bck: E-3/References), and a paragraph was writing into the footer (FR-H.1 step 2.2.3.1. KBR 10/14/14) - private LazyLoad _PaginateOnLowerStepLevel; - public bool PaginateOnLowerStepLevel - { - get - { - return LazyLoad(ref _PaginateOnLowerStepLevel, "@PaginateOnLowerStepLevel"); - } - } + // will print the defined section end message for single columns sections. + // the default setting is True + private LazyLoad _EndForSingle; + public bool EndForSingle => LazyLoad(ref _EndForSingle, "@EndForSingle"); + // Special pagination case used in some background document formats. This will turn off the KeepStepsOnPage flag when a paragraph off of a High Level step was put on next page (IP2 bck: E-3/References), and a paragraph was writing into the footer (FR-H.1 step 2.2.3.1. KBR 10/14/14) + private LazyLoad _PaginateOnLowerStepLevel; + public bool PaginateOnLowerStepLevel => LazyLoad(ref _PaginateOnLowerStepLevel, "@PaginateOnLowerStepLevel"); - // B2023-088: alarm format pagination - // Special pagination for Alarm procedures to keep substeps with the high level step - private LazyLoad _AlarmPagination; - public bool AlarmPagination - { - get - { - return LazyLoad(ref _AlarmPagination, "@AlarmPagination"); - } - } + // B2023-088: alarm format pagination + // Special pagination for Alarm procedures to keep substeps with the high level step + private LazyLoad _AlarmPagination; + public bool AlarmPagination => LazyLoad(ref _AlarmPagination, "@AlarmPagination"); - // For McGuire and Catawba, they use CustomSpacing which inserts a blank line before high level steps - // if we paginate on one of these blank lines, we want to skip that blank line so that there isn't an - // extra blank line at the top of the page. - private LazyLoad _CustomSpacing; - public bool CustomSpacing - { - get - { - return LazyLoad(ref _CustomSpacing, "@CustomSpacing"); - } - } + // For McGuire and Catawba, they use CustomSpacing which inserts a blank line before high level steps + // if we paginate on one of these blank lines, we want to skip that blank line so that there isn't an + // extra blank line at the top of the page. + private LazyLoad _CustomSpacing; + public bool CustomSpacing => LazyLoad(ref _CustomSpacing, "@CustomSpacing"); - // when set to False, a caluation for centering text is done with respect to the CPI defined for - // the font to better match the centering of the 16-bit VEPROMS application - private LazyLoad _PicaIgnoreFiveSixths; - public bool PicaIgnoreFiveSixths - { - get - { - return LazyLoad(ref _PicaIgnoreFiveSixths, "@PicaIgnoreFiveSixths"); - } - } + // when set to False, a caluation for centering text is done with respect to the CPI defined for + // the font to better match the centering of the 16-bit VEPROMS application + private LazyLoad _PicaIgnoreFiveSixths; + public bool PicaIgnoreFiveSixths => LazyLoad(ref _PicaIgnoreFiveSixths, "@PicaIgnoreFiveSixths"); - // keep sub-steps together - on a page by themselves - private LazyLoad _PutOnPageByItself; - public bool PutOnPageByItself - { - get - { - return LazyLoad(ref _PutOnPageByItself, "@PutOnPageByItself"); - } - } + // keep sub-steps together - on a page by themselves + private LazyLoad _PutOnPageByItself; + public bool PutOnPageByItself => LazyLoad(ref _PutOnPageByItself, "@PutOnPageByItself"); - // If a high level step, the 16bit code uses the value of the extra space - // from the high level step format regardless of what type of high level step it is: - // Added check for UseSTExtraRealValue, if set, we want to use what is set for the specific step type - private LazyLoad _UseSTExtraRealValue; - public bool UseSTExtraRealValue - { - get - { - return LazyLoad(ref _UseSTExtraRealValue, "@UseSTExtraRealValue"); - } - } + // If a high level step, the 16bit code uses the value of the extra space + // from the high level step format regardless of what type of high level step it is: + // Added check for UseSTExtraRealValue, if set, we want to use what is set for the specific step type + private LazyLoad _UseSTExtraRealValue; + public bool UseSTExtraRealValue => LazyLoad(ref _UseSTExtraRealValue, "@UseSTExtraRealValue"); - // Causes step tabs to be built according to the actual level, with respect to the section level and the step level (i.e. sub-sections count as a level) - private LazyLoad _TieTabToLevel; - public bool TieTabToLevel - { - get - { - return LazyLoad(ref _TieTabToLevel, "@TieTabToLevel"); - } - } + // Causes step tabs to be built according to the actual level, with respect to the section level and the step level (i.e. sub-sections count as a level) + private LazyLoad _TieTabToLevel; + public bool TieTabToLevel => LazyLoad(ref _TieTabToLevel, "@TieTabToLevel"); - // C2026-003 (for Vogtle Units 3&4) Adds the continuous action tag to a high level RNO - // only when it as a tab and the parent is an AER step that is not tagged as a continuous action - // Use this with the setting of CASPrintMacro and CASEditTag on the RNO step type TabData definition - private LazyLoad _AddContActTagToHighLevelRNOWhenIncludedOnCAS; - public bool AddContActTagToHighLevelRNOWhenIncludedOnCAS - { - get - { - return LazyLoad(ref _AddContActTagToHighLevelRNOWhenIncludedOnCAS, "@AddContActTagToHighLevelRNOWhenIncludedOnCAS"); - } - } + // C2026-003 (for Vogtle Units 3&4) Adds the continuous action tag to a high level RNO + // only when it as a tab and the parent is an AER step that is not tagged as a continuous action + // Use this with the setting of CASPrintMacro and CASEditTag on the RNO step type TabData definition + private LazyLoad _AddContActTagToHighLevelRNOWhenIncludedOnCAS; + public bool AddContActTagToHighLevelRNOWhenIncludedOnCAS => LazyLoad(ref _AddContActTagToHighLevelRNOWhenIncludedOnCAS, "@AddContActTagToHighLevelRNOWhenIncludedOnCAS"); - // treat sub-sections and High Level Steps as if they are at the same procedure structure level. This is used with the TieTabToLevel flag - private LazyLoad _SubSectAndHighSameLevel; - public bool SubSectAndHighSameLevel - { - get - { - return LazyLoad(ref _SubSectAndHighSameLevel, "@SubSectAndHighSameLevel"); - } - } + // treat sub-sections and High Level Steps as if they are at the same procedure structure level. This is used with the TieTabToLevel flag + private LazyLoad _SubSectAndHighSameLevel; + public bool SubSectAndHighSameLevel => LazyLoad(ref _SubSectAndHighSameLevel, "@SubSectAndHighSameLevel"); - // compress only part of the step (i.e. a sub-step) so that the entire step can fit on a page - private LazyLoad _PartialStepCompression; + // compress only part of the step (i.e. a sub-step) so that the entire step can fit on a page + private LazyLoad _PartialStepCompression; public bool PartialStepCompression { get @@ -3851,44 +2307,20 @@ namespace VEPROMS.CSLA.Library } // remove the ".0" from a bottom continue message private LazyLoad _VirtualDotInHLSTab; - public bool VirtualDotInHLSTab - { - get - { - return LazyLoad(ref _VirtualDotInHLSTab, "@VirtualDotInHLSTab"); - } - } - // was put in for NSP's Cautions and Notes which are not boxed but formatted differently than other non-boxed Cautions and Notes, allow to specify a starting column and width where the Note/Caution step types are defined - private LazyLoad _NullBox; - public bool NullBox - { - get - { - return LazyLoad(ref _NullBox, "@NullBox"); - } - } + public bool VirtualDotInHLSTab => LazyLoad(ref _VirtualDotInHLSTab, "@VirtualDotInHLSTab"); + // was put in for NSP's Cautions and Notes which are not boxed but formatted differently than other non-boxed Cautions and Notes, allow to specify a starting column and width where the Note/Caution step types are defined + private LazyLoad _NullBox; + public bool NullBox => LazyLoad(ref _NullBox, "@NullBox"); - // turns on the ability to add Notes and Cautions off of a Section title in the PROMS step editor - private LazyLoad _AllowNoteCautionAdd; - public bool AllowNoteCautionAdd - { - get - { - return LazyLoad(ref _AllowNoteCautionAdd, "@AllowNoteCautionAdd"); - } - } + // turns on the ability to add Notes and Cautions off of a Section title in the PROMS step editor + private LazyLoad _AllowNoteCautionAdd; + public bool AllowNoteCautionAdd => LazyLoad(ref _AllowNoteCautionAdd, "@AllowNoteCautionAdd"); - // F2024-037 reset the seq sub-step numbering if the parent is an un-numbered high level step - // F2024-049 changed to specify the level, to change to, via the format file (Generic EOP and Vogtle 3&4) - private LazyLoad _ResetSeqNumberingAfterUnnumberedHLS; - public int? ResetSeqNumberingAfterUnnumberedHLS - { - get - { - return LazyLoad(ref _ResetSeqNumberingAfterUnnumberedHLS, "@ResetSeqNumberingAfterUnnumberedHLS"); - } - } - } + // F2024-037 reset the seq sub-step numbering if the parent is an un-numbered high level step + // F2024-049 changed to specify the level, to change to, via the format file (Generic EOP and Vogtle 3&4) + private LazyLoad _ResetSeqNumberingAfterUnnumberedHLS; + public int? ResetSeqNumberingAfterUnnumberedHLS => LazyLoad(ref _ResetSeqNumberingAfterUnnumberedHLS, "@ResetSeqNumberingAfterUnnumberedHLS"); + } #endregion - StepSectionLayoutData #region Separator public class Separator : vlnFormatItem @@ -3897,25 +2329,12 @@ namespace VEPROMS.CSLA.Library //the placement setting for the separator words used for OR the sub-steps and the Explicit And sub-steps private LazyLoad _Location; - public int? Location - { - get - { - return LazyLoad(ref _Location, "@Location"); - //return LazyLoad(ref _SeparatorLocation, "@SeparatorLocation"); - } - } + public int? Location => LazyLoad(ref _Location, "@Location"); - // the font specifications for the separator text for OR the sub-steps and the Explicit And sub-steps - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null ? _Font = new VE_Font(base.XmlNode) : _Font); - } - } - } + // the font specifications for the separator text for OR the sub-steps and the Explicit And sub-steps + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + } #endregion - Separator #region StepSectionPrintData public class StepSectionPrintData : vlnFormatItem @@ -3929,98 +2348,44 @@ namespace VEPROMS.CSLA.Library // when set to True - will put 1 line between the box line and step text resulting in // no extra line between the box and top/bottom of step. private LazyLoad _DiffContActBox; - public bool DiffContActBox - { - get - { - return LazyLoad(ref _DiffContActBox, "@DiffContActBox"); - } - } - // will allow the drawing of a box round substeps that have a defined box - private LazyLoad _ContActBoxOnSubSteps; - public bool ContActBoxOnSubSteps - { - get - { - return LazyLoad(ref _ContActBoxOnSubSteps, "@ContActBoxOnSubSteps"); - } - } - // this will print the defined string after the last RNO for a step or sub-step - // some plants print a string of a couple spaces to add an extra blank line instead - private LazyLoad _RNOSepString; - public string RNOSepString - { - get - { - return LazyLoad(ref _RNOSepString, "@RNOSepString"); - } - } + public bool DiffContActBox => LazyLoad(ref _DiffContActBox, "@DiffContActBox"); + // will allow the drawing of a box round substeps that have a defined box + private LazyLoad _ContActBoxOnSubSteps; + public bool ContActBoxOnSubSteps => LazyLoad(ref _ContActBoxOnSubSteps, "@ContActBoxOnSubSteps"); + // this will print the defined string after the last RNO for a step or sub-step + // some plants print a string of a couple spaces to add an extra blank line instead + private LazyLoad _RNOSepString; + public string RNOSepString => LazyLoad(ref _RNOSepString, "@RNOSepString"); - // specify the length of the RNO separator. if not set, then code uses length of RNOSepString. if no RNOSepString then the code creates an empty RNO separtor. - private LazyLoad _RNOSepLineLength; - public float? RNOSepLineLength - { - get - { - return LazyLoad(ref _RNOSepLineLength, "@RNOSepLineLength"); - } - } - // will print the defined string between each High Level Step type. Used in the Long Form Deviation format - private LazyLoad _HLStpSeparatorString; - public string HLStpSeparatorString - { - get - { - return LazyLoad(ref _HLStpSeparatorString, "@HLStpSeparatorString"); - } - } + // specify the length of the RNO separator. if not set, then code uses length of RNOSepString. if no RNOSepString then the code creates an empty RNO separtor. + private LazyLoad _RNOSepLineLength; + public float? RNOSepLineLength => LazyLoad(ref _RNOSepLineLength, "@RNOSepLineLength"); + // will print the defined string between each High Level Step type. Used in the Long Form Deviation format + private LazyLoad _HLStpSeparatorString; + public string HLStpSeparatorString => LazyLoad(ref _HLStpSeparatorString, "@HLStpSeparatorString"); - // will print the defined string between each High Level RNO Step type. Used in the Long Form Deviation format - private LazyLoad _HLRNOStpSeparatorString; - public string HLRNOStpSeparatorString - { - get - { - return LazyLoad(ref _HLRNOStpSeparatorString, "@HLRNOStpSeparatorString"); - } - } + // will print the defined string between each High Level RNO Step type. Used in the Long Form Deviation format + private LazyLoad _HLRNOStpSeparatorString; + public string HLRNOStpSeparatorString => LazyLoad(ref _HLRNOStpSeparatorString, "@HLRNOStpSeparatorString"); - // turns on the ability to enter a procedure set revision number (string) on the Working Draft properties page - private LazyLoad _UseXtraRevNumber; - public bool UseXtraRevNumber - { - get - { - return LazyLoad(ref _UseXtraRevNumber, "@UseXtraRevNumber"); - } - } + // turns on the ability to enter a procedure set revision number (string) on the Working Draft properties page + private LazyLoad _UseXtraRevNumber; + public bool UseXtraRevNumber => LazyLoad(ref _UseXtraRevNumber, "@UseXtraRevNumber"); - // Don't all step text to print past right margin. put in for Point Beach's Background document - private LazyLoad _LimitWidToPageWid; - public bool LimitWidToPageWid - { - get - { - return LazyLoad(ref _LimitWidToPageWid, "@LimitWidToPageWid"); - } - } - // add the parent tab to the step or sub-step tab - private LazyLoad _CombinedTabIncludeParenTabs; - public bool CombinedTabIncludeParenTabs - { - get - { - return LazyLoad(ref _CombinedTabIncludeParenTabs, "@CombinedTabIncludeParenTabs"); - } - } + // Don't all step text to print past right margin. put in for Point Beach's Background document + private LazyLoad _LimitWidToPageWid; + public bool LimitWidToPageWid => LazyLoad(ref _LimitWidToPageWid, "@LimitWidToPageWid"); + // add the parent tab to the step or sub-step tab + private LazyLoad _CombinedTabIncludeParenTabs; + public bool CombinedTabIncludeParenTabs => LazyLoad(ref _CombinedTabIncludeParenTabs, "@CombinedTabIncludeParenTabs"); - // a list of hard coded tab placement adjustments per step level - private LeftJustifyList _LeftJustifyList; + // a list of hard coded tab placement adjustments per step level + private LeftJustifyList _LeftJustifyList; public LeftJustifyList LeftJustifyList { get { - return (_LeftJustifyList == null) ? _LeftJustifyList = new LeftJustifyList(SelectNodes("LeftJustifyList/LeftJustify")) : _LeftJustifyList; + return _LeftJustifyList ?? (_LeftJustifyList = new LeftJustifyList(SelectNodes("LeftJustifyList/LeftJustify"))); } set { _LeftJustifyList = value; } } @@ -4040,24 +2405,12 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } // represents the step level in which to use the LeftJustify Size value private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); - // the LeftJustify value - private LazyLoad _Size; - public float? Size - { - get - { - return LazyLoad(ref _Size, "@Size"); - } - } - } + // the LeftJustify value + private LazyLoad _Size; + public float? Size => LazyLoad(ref _Size, "@Size"); + } #endregion - LeftJustify #endregion - LeftJustifyList #endregion - StepSectionPrintData @@ -4069,68 +2422,34 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } public SeqTabFmt() : base() { } // index number of each SeqTabFmt item in the SequentialTabFormat list private LazyLoad _Index; - [Description("SeqTab Index")] - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } + [Description("SeqTab Index")] + public int? Index => LazyLoad(ref _Index, "@Index"); - // the token representing the type of tab to use. ex: {numeric} for a number, {alpha} for a letter - private LazyLoad _TabToken; - public string TabToken - { - get - { - return LazyLoad(ref _TabToken, "@TabToken"); - } - } + // the token representing the type of tab to use. ex: {numeric} for a number, {alpha} for a letter + private LazyLoad _TabToken; + public string TabToken => LazyLoad(ref _TabToken, "@TabToken"); - // the formatting definition for that tab (usually uses the "{seq}" token). defines if the tab ends with a period, closed parenthesis, etc. - // this format setting is also used for printing - we currently ignore the format setting for PrintTabFormat - private LazyLoad _TabFormat; - public string TabFormat - { - get - { - return LazyLoad(ref _TabFormat, "@TabFormat"); - } - } + // the formatting definition for that tab (usually uses the "{seq}" token). defines if the tab ends with a period, closed parenthesis, etc. + // this format setting is also used for printing - we currently ignore the format setting for PrintTabFormat + private LazyLoad _TabFormat; + public string TabFormat => LazyLoad(ref _TabFormat, "@TabFormat"); - // the formatting definition for that tab. defines if the tab ends with a period, closed parenthesis, etc. - // - we currently ignore this format setting when printing and use the value of TabFormat instead. - // leaving it this way in case we find a need to have different tab formats for editor and printing - private LazyLoad _PrintTabFormat; - public string PrintTabFormat - { - get - { - return LazyLoad(ref _TabFormat, "@PrintTabFormat"); - } - } + // the formatting definition for that tab. defines if the tab ends with a period, closed parenthesis, etc. + // - we currently ignore this format setting when printing and use the value of TabFormat instead. + // leaving it this way in case we find a need to have different tab formats for editor and printing +#pragma warning disable 169 + private readonly LazyLoad _PrintTabFormat; +#pragma warning disable 169 + public string PrintTabFormat => LazyLoad(ref _TabFormat, "@PrintTabFormat"); - // when the tab is built with parent tab information, don't trim the parent tab (don't remove the surrounding spaces before building the tab - private LazyLoad _DontTrimParentTabBeforeAppending; // B2019-011 for Barakah Alarm format - public bool DontTrimParentTabBeforeAppending - { - get - { - return LazyLoad(ref _DontTrimParentTabBeforeAppending, "@DontTrimParentTabBeforeAppending"); - } - } - public override string GetPDDisplayName() - { return string.Format("Index [{0}]", Index); } - public override string GetPDDescription() - { return string.Format("Sequential Tab Format Index '{0}' Format '{1}'", Index, TabFormat); } - public override string GetPDCategory() - { return "Sequential Tab Formatting"; } - public override string ToString() - { - return TabFormat; - } - } + // when the tab is built with parent tab information, don't trim the parent tab (don't remove the surrounding spaces before building the tab + private LazyLoad _DontTrimParentTabBeforeAppending; // B2019-011 for Barakah Alarm format + public bool DontTrimParentTabBeforeAppending => LazyLoad(ref _DontTrimParentTabBeforeAppending, "@DontTrimParentTabBeforeAppending"); + public override string GetPDDisplayName() => string.Format("Index [{0}]", Index); + public override string GetPDDescription() => string.Format("Sequential Tab Format Index '{0}' Format '{1}'", Index, TabFormat); + public override string GetPDCategory() => "Sequential Tab Formatting"; + public override string ToString() => TabFormat; + } # endregion - SeqTabFmt #region SeqTabFmtList [TypeConverter(typeof(vlnIndexedListConverter))] @@ -4164,7 +2483,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - return (_TableOfContentsData == null ? _TableOfContentsData = new TableOfContentsData(SelectSingleNode("TableOfContentsData")) : _TableOfContentsData); + return (_TableOfContentsData ?? (_TableOfContentsData = new TableOfContentsData(SelectSingleNode("TableOfContentsData")))); } } @@ -4176,7 +2495,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - return (_ContinuousActionSummaryData == null ? _ContinuousActionSummaryData = new ConitnuousActionSummaryData(SelectSingleNode("ConitnuousActionSummaryData")) : _ContinuousActionSummaryData); + return (_ContinuousActionSummaryData ?? (_ContinuousActionSummaryData = new ConitnuousActionSummaryData(SelectSingleNode("ConitnuousActionSummaryData")))); } } } @@ -4189,95 +2508,41 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } // positon of the section number from the left margin private LazyLoad _TofCSecNumPos; - public float? TofCSecNumPos - { - get - { - return LazyLoad(ref _TofCSecNumPos, "@TofCSecNumPos"); - } - } - // position of the section title from the left margin - private LazyLoad _TofCSecTitlePos; - public float? TofCSecTitlePos - { - get - { - return LazyLoad(ref _TofCSecTitlePos, "@TofCSecTitlePos"); - } - } + public float? TofCSecNumPos => LazyLoad(ref _TofCSecNumPos, "@TofCSecNumPos"); + // position of the section title from the left margin + private LazyLoad _TofCSecTitlePos; + public float? TofCSecTitlePos => LazyLoad(ref _TofCSecTitlePos, "@TofCSecTitlePos"); - // length of the section title before wrapping onto the next line - private LazyLoad _TofCSecTitleLen; - public int? TofCSecTitleLen - { - get - { - return LazyLoad(ref _TofCSecTitleLen, "@TofCSecTitleLen"); - } - } + // length of the section title before wrapping onto the next line + private LazyLoad _TofCSecTitleLen; + public int? TofCSecTitleLen => LazyLoad(ref _TofCSecTitleLen, "@TofCSecTitleLen"); - // positon of the the section's starting page number - private LazyLoad _TofCPageNumPos; - public float? TofCPageNumPos - { - get - { - return LazyLoad(ref _TofCPageNumPos, "@TofCPageNumPos"); - } - } + // positon of the the section's starting page number + private LazyLoad _TofCPageNumPos; + public float? TofCPageNumPos => LazyLoad(ref _TofCPageNumPos, "@TofCPageNumPos"); - // the character used for the spaces between the section title and the page number - i.e. leader dots - private LazyLoad _TofCSpaceChar; - public string TofCSpaceChar - { - get - { - return LazyLoad(ref _TofCSpaceChar, "@TofCSpaceChar"); - } - } + // the character used for the spaces between the section title and the page number - i.e. leader dots + private LazyLoad _TofCSpaceChar; + public string TofCSpaceChar => LazyLoad(ref _TofCSpaceChar, "@TofCSpaceChar"); - // the line spaces between each item on the table of contents - private LazyLoad _TofCLineSpacing; - public float? TofCLineSpacing - { - get - { - return LazyLoad(ref _TofCLineSpacing, "@TofCLineSpacing"); - } - } + // the line spaces between each item on the table of contents + private LazyLoad _TofCLineSpacing; + public float? TofCLineSpacing => LazyLoad(ref _TofCLineSpacing, "@TofCLineSpacing"); - // specify how many section / sub-sections to include on the TOC page - private LazyLoad _TofCNumLevels; - public int? TofCNumLevels - { - get - { - return LazyLoad(ref _TofCNumLevels, "@TofCNumLevels"); - } - } + // specify how many section / sub-sections to include on the TOC page + private LazyLoad _TofCNumLevels; + public int? TofCNumLevels => LazyLoad(ref _TofCNumLevels, "@TofCNumLevels"); - // specify after which section level to start indenting the entries on the TOC page - private LazyLoad _TofCStartIndentAfterLevel; - public int? TofCStartIndentAfterLevel - { - get - { - return LazyLoad(ref _TofCStartIndentAfterLevel, "@TofCStartIndentAfterLevel"); - } - } + // specify after which section level to start indenting the entries on the TOC page + private LazyLoad _TofCStartIndentAfterLevel; + public int? TofCStartIndentAfterLevel => LazyLoad(ref _TofCStartIndentAfterLevel, "@TofCStartIndentAfterLevel"); - // flag to underline the first level section titles - private LazyLoad _TofCUnderlineFirstLevelTitle; - public bool TofCUnderlineFirstLevelTitle - { - get - { - return LazyLoad(ref _TofCUnderlineFirstLevelTitle, "@TofCUnderlineFirstLevelTitle"); - } - } + // flag to underline the first level section titles + private LazyLoad _TofCUnderlineFirstLevelTitle; + public bool TofCUnderlineFirstLevelTitle => LazyLoad(ref _TofCUnderlineFirstLevelTitle, "@TofCUnderlineFirstLevelTitle"); - // specify the page number alignment with respect to the page number position - default is left justify - private LazyLoad _TofCPageNumAlign; + // specify the page number alignment with respect to the page number position - default is left justify + private LazyLoad _TofCPageNumAlign; public string TofCPageNumAlign { get @@ -4300,43 +2565,19 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } // specify the line spacing to be just for the sub-sections entries private LazyLoad _TofCLineSpacingSub; - public int? TofCLineSpacingSub - { - get - { - return LazyLoad(ref _TofCLineSpacingSub, "@TofCLineSpacingSub"); - } - } - // if the Group Heading (defined in section's properties automation tab) is also part of the section number, - // remove it the Group Heading text from the section number - VEGP1, VEGP2 - private LazyLoad _TofCRemoveGrpNameInSects; - public bool TofCRemoveGrpNameInSects - { - get - { - return LazyLoad(ref _TofCRemoveGrpNameInSects, "@TofCRemoveGrpNameInSects"); - } - } + public int? TofCLineSpacingSub => LazyLoad(ref _TofCLineSpacingSub, "@TofCLineSpacingSub"); + // if the Group Heading (defined in section's properties automation tab) is also part of the section number, + // remove it the Group Heading text from the section number - VEGP1, VEGP2 + private LazyLoad _TofCRemoveGrpNameInSects; + public bool TofCRemoveGrpNameInSects => LazyLoad(ref _TofCRemoveGrpNameInSects, "@TofCRemoveGrpNameInSects"); - // C2021-015: Barakah High Level Steps in Table of Contents - // if set in the Step Properties pannel - private LazyLoad _TofCAllowHLS; - public bool TofCAllowHLS - { - get - { - return LazyLoad(ref _TofCAllowHLS, "@TofCAllowHLS"); - } - } - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null) ? _Font = new VE_Font(base.XmlNode) : _Font; - } - } - } + // C2021-015: Barakah High Level Steps in Table of Contents + // if set in the Step Properties pannel + private LazyLoad _TofCAllowHLS; + public bool TofCAllowHLS => LazyLoad(ref _TofCAllowHLS, "@TofCAllowHLS"); + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + } #endregion - TableOfContentsData #region ConitnuousActionSummary @@ -4346,43 +2587,19 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } // include the section number and title for the sections that contains continuous action steps private LazyLoad _IncludeSectionNumAndTitle; - public bool IncludeSectionNumAndTitle - { - get - { - return LazyLoad(ref _IncludeSectionNumAndTitle, "@IncludeSectionNumAndTitle"); - } - } + public bool IncludeSectionNumAndTitle => LazyLoad(ref _IncludeSectionNumAndTitle, "@IncludeSectionNumAndTitle"); - //F2025-038 default (in base format) is True. The lable "SECTION" will precede the section number an title - private LazyLoad _IncludeSectionLabel; - public bool IncludeSectionLabel - { - get - { - return LazyLoad(ref _IncludeSectionLabel, "@IncludeSectionLabel"); - } - } - //F2026-001 default (in base format) is False. Put in for Vogtle Units 3 & 4. - // this will add the parent sub-step tab if the parent is not identified as a continueous action step - private LazyLoad _AddParentTabToSubStepTab; - public bool AddParentTabToSubStepTab - { - get - { - return LazyLoad(ref _AddParentTabToSubStepTab, "@AddParentTabToSubStepTab"); - } - } - // the font and font styles to use for the continuous action summary - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null) ? _Font = new VE_Font(base.XmlNode) : _Font; - } - } - } + //F2025-038 default (in base format) is True. The lable "SECTION" will precede the section number an title + private LazyLoad _IncludeSectionLabel; + public bool IncludeSectionLabel => LazyLoad(ref _IncludeSectionLabel, "@IncludeSectionLabel"); + //F2026-001 default (in base format) is False. Put in for Vogtle Units 3 & 4. + // this will add the parent sub-step tab if the parent is not identified as a continueous action step + private LazyLoad _AddParentTabToSubStepTab; + public bool AddParentTabToSubStepTab => LazyLoad(ref _AddParentTabToSubStepTab, "@AddParentTabToSubStepTab"); + // the font and font styles to use for the continuous action summary + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + } #endregion - ConitnuousActionSummary #endregion - AccSectionDataAll @@ -4396,60 +2613,25 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } // represents the section level private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } - // the column adjustment (indent) inwhich to print the section number for that level of section (sub-section) - private LazyLoad _SecNumPositionAdj; - public float? SecNumPositionAdj - { - get - { - return LazyLoad(ref _SecNumPositionAdj, "@SecNumPositionAdj"); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); + // the column adjustment (indent) inwhich to print the section number for that level of section (sub-section) + private LazyLoad _SecNumPositionAdj; + public float? SecNumPositionAdj => LazyLoad(ref _SecNumPositionAdj, "@SecNumPositionAdj"); - // the column adjustment (indent) inwhich to print the section title for that level of section (sub-section) - private LazyLoad _SecTitlePositionAdj; - public float? SecTitlePositionAdj - { - get - { - return LazyLoad(ref _SecTitlePositionAdj, "@SecTitlePositionAdj"); - } - } - // adjustment (indent) for the high level steps for that level of section (sub-section) - private LazyLoad _ColSByLevel; - public float? ColSByLevel - { - get - { - return LazyLoad(ref _ColSByLevel, "@ColSByLevel"); - } - } + // the column adjustment (indent) inwhich to print the section title for that level of section (sub-section) + private LazyLoad _SecTitlePositionAdj; + public float? SecTitlePositionAdj => LazyLoad(ref _SecTitlePositionAdj, "@SecTitlePositionAdj"); + // adjustment (indent) for the high level steps for that level of section (sub-section) + private LazyLoad _ColSByLevel; + public float? ColSByLevel => LazyLoad(ref _ColSByLevel, "@ColSByLevel"); - // adjustment for the width of the high level steps for that level of section (sub-section) - private LazyLoad _WidSAdjByLevel; - public float? WidSAdjByLevel - { - get - { - return LazyLoad(ref _WidSAdjByLevel, "@WidSAdjByLevel"); - } - } - public override string GetPDDisplayName() - { return string.Format("[{0}]", Index); } - public override string GetPDCategory() - { return "Meta Section Values"; } - public override string ToString() - { - return String.Format("{0}, {1}, {2}, {3}", SecNumPositionAdj, SecTitlePositionAdj, ColSByLevel, WidSAdjByLevel); - } - } + // adjustment for the width of the high level steps for that level of section (sub-section) + private LazyLoad _WidSAdjByLevel; + public float? WidSAdjByLevel => LazyLoad(ref _WidSAdjByLevel, "@WidSAdjByLevel"); + public override string GetPDDisplayName() => string.Format("[{0}]", Index); + public override string GetPDCategory() => "Meta Section Values"; + public override string ToString() => String.Format("{0}, {1}, {2}, {3}", SecNumPositionAdj, SecTitlePositionAdj, ColSByLevel, WidSAdjByLevel); + } #endregion - MetaSection @@ -4482,150 +2664,64 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } // translated to a step type number - this number is used to allow the BASE format settting in the Plant formats private LazyLoad _Index; - [Description("Step Index")] - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } + [Description("Step Index")] + public int? Index => LazyLoad(ref _Index, "@Index"); - // text description of the step part type (ex. High, Caution, Note) - private LazyLoad _Type; - public string Type - { - get - { - return LazyLoad(ref _Type, "@Type"); - } - } - // the step type from which settings are inherited - private LazyLoad _ParentType; - public string ParentType - { - get - { - return LazyLoad(ref _ParentType, "@ParentType"); - } - } - // user cannot directly edit the text in step type - usually auto generated text like TITLEWITHTEXTBELOW used in background documents - private LazyLoad _ReadOnly; - public bool ReadOnly - { - get - { - return LazyLoad(ref _ReadOnly, "@ReadOnly"); - } - } + // text description of the step part type (ex. High, Caution, Note) + private LazyLoad _Type; + public string Type => LazyLoad(ref _Type, "@Type"); + // the step type from which settings are inherited + private LazyLoad _ParentType; + public string ParentType => LazyLoad(ref _ParentType, "@ParentType"); + // user cannot directly edit the text in step type - usually auto generated text like TITLEWITHTEXTBELOW used in background documents + private LazyLoad _ReadOnly; + public bool ReadOnly => LazyLoad(ref _ReadOnly, "@ReadOnly"); - // Less space between text and bottom line of Caution Box - private LazyLoad _NoYBxAdjust; // F2021-038: SHE/SHEA less space after top line & before bottom line - public bool NoYBxAdjust - { - get - { - return LazyLoad(ref _NoYBxAdjust, "@NoYBxAdjust"); - } - } - //private LazyLoad _SeparateWarning; // KBR: To be used for Proms Express to separate out warnings from notes/cautions on ribbon, etc - NO CODE TO SUPPORT THIS YET AND IS NOT SET IN PROMS EXPRESS FORMATS - //public bool SeparateWarning - //{ - // get - // { - // return LazyLoad(ref _SeparateWarning, "@SeparateWarning"); - // } - //} + // Less space between text and bottom line of Caution Box + private LazyLoad _NoYBxAdjust; // F2021-038: SHE/SHEA less space after top line & before bottom line + public bool NoYBxAdjust => LazyLoad(ref _NoYBxAdjust, "@NoYBxAdjust"); - // when set to Truen the step type will not appear in the insert step or sub-step lists. used to turn off (remove) the availability of step types that are not used or needed by the customer - private LazyLoad _Inactive; - public bool Inactive - { - get - { - return LazyLoad(ref _Inactive, "@Inactive"); - } - } + // when set to Truen the step type will not appear in the insert step or sub-step lists. used to turn off (remove) the availability of step types that are not used or needed by the customer + private LazyLoad _Inactive; + public bool Inactive => LazyLoad(ref _Inactive, "@Inactive"); - // F2018-022 Added step type flag to append a ".0" to the end of the high level step - // - put in for Westinghouse single column format (wst1) - // - used when a high level step is used as a section number and title - private LazyLoad _AppendDotZero; - public bool AppendDotZero - { - get - { - return LazyLoad(ref _AppendDotZero, "@AppendDotZero"); - } - } - // F2019-069: Barakah Hold Point - set xoffset to parent's tab - // put in for BNPP (Barakah). the Hold Point (note type) needed indented the same as the high level step - // that it apples to, instead of centering it on the page like a normal Note type - private LazyLoad _ColUseParentTab; - public bool ColUseParentTab - { - get - { - return LazyLoad(ref _ColUseParentTab, "@ColUseParentTab"); - } - } + // F2018-022 Added step type flag to append a ".0" to the end of the high level step + // - put in for Westinghouse single column format (wst1) + // - used when a high level step is used as a section number and title + private LazyLoad _AppendDotZero; + public bool AppendDotZero => LazyLoad(ref _AppendDotZero, "@AppendDotZero"); + // F2019-069: Barakah Hold Point - set xoffset to parent's tab + // put in for BNPP (Barakah). the Hold Point (note type) needed indented the same as the high level step + // that it apples to, instead of centering it on the page like a normal Note type + private LazyLoad _ColUseParentTab; + public bool ColUseParentTab => LazyLoad(ref _ColUseParentTab, "@ColUseParentTab"); - // this will override the ColS format setting for the specific step type - private LazyLoad _ColOverride; - public float? ColOverride - { - get - { - return LazyLoad(ref _ColOverride, "@ColOverride"); - } - } + // this will override the ColS format setting for the specific step type + private LazyLoad _ColOverride; + public float? ColOverride => LazyLoad(ref _ColOverride, "@ColOverride"); - // this will override the WidS format setting for the specific step type - private LazyLoad _WidthOverride; - public string WidthOverride - { - get - { - return LazyLoad(ref _WidthOverride, "@WidthOverride"); - } - } + // this will override the WidS format setting for the specific step type + private LazyLoad _WidthOverride; + public string WidthOverride => LazyLoad(ref _WidthOverride, "@WidthOverride"); - // Separtor text that is printed beween consecutive step items of this type - // ex: "-OR-" may be printed between two consecutive OR sub-step types - private LazyLoad _Sep; - public string Sep - { - get - { - return LazyLoad(ref _Sep, "@Sep"); - } - } + // Separtor text that is printed beween consecutive step items of this type + // ex: "-OR-" may be printed between two consecutive OR sub-step types + private LazyLoad _Sep; + public string Sep => LazyLoad(ref _Sep, "@Sep"); - // a text string that is placed before the text of this step type. - // Used in the Checklist formats to draw lines (for a table) when printed. - // Also used to add a step text designator character before step text - private LazyLoad _Prefix; - public string Prefix - { - get - { - return LazyLoad(ref _Prefix, "@Prefix"); - } - } - // a text string that is placed after the text of this step type. Used in the Checklist formats to draw lines (for a table) when printed. - private LazyLoad _Suffix; - public string Suffix - { - get - { - return LazyLoad(ref _Suffix, "@Suffix"); - } - } + // a text string that is placed before the text of this step type. + // Used in the Checklist formats to draw lines (for a table) when printed. + // Also used to add a step text designator character before step text + private LazyLoad _Prefix; + public string Prefix => LazyLoad(ref _Prefix, "@Prefix"); + // a text string that is placed after the text of this step type. Used in the Checklist formats to draw lines (for a table) when printed. + private LazyLoad _Suffix; + public string Suffix => LazyLoad(ref _Suffix, "@Suffix"); - // F2019-069: Barakah Hold Point - allow for default text (for Barakah it is 'Hold Point') - //whenever this step type is added to a step, - //this text field will automatically be populated with this text - private LazyLoad _DefaultText; + // F2019-069: Barakah Hold Point - allow for default text (for Barakah it is 'Hold Point') + //whenever this step type is added to a step, + //this text field will automatically be populated with this text + private LazyLoad _DefaultText; public string DefaultText { get @@ -5089,7 +3185,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - if (PlantFormat.IgnoreUCF) return (_Font == null) ? _Font = new VE_Font(base.XmlNode) : _Font; + if (PlantFormat.IgnoreUCF) return _Font ?? (_Font = new VE_Font(XmlNode)); if (_Font != null) return (_Font); VE_Font vef = GetUCFFontAsVE_Font(); if (vef != null) @@ -5097,7 +3193,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } _Font = vef; return vef; } - return (_Font == null) ? _Font = new VE_Font(base.XmlNode) : _Font; + return _Font ?? (_Font = new VE_Font(XmlNode)); } } private StepLayoutData _StepLayoutData; @@ -5105,7 +3201,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - return (_StepLayoutData == null) ? _StepLayoutData = new StepLayoutData(base.XmlNode) : _StepLayoutData; + return _StepLayoutData ?? (_StepLayoutData = new StepLayoutData(XmlNode)); } } private StepEditData _StepEditData; @@ -5113,7 +3209,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - return (_StepEditData == null) ? _StepEditData = new StepEditData(base.XmlNode) : _StepEditData; + return _StepEditData ?? (_StepEditData = new StepEditData(XmlNode)); } } private StepPrintData _StepPrintData; @@ -5121,7 +3217,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - return (_StepPrintData == null) ? _StepPrintData = new StepPrintData(base.XmlNode) : _StepPrintData; + return _StepPrintData ?? (_StepPrintData = new StepPrintData(XmlNode)); } } private TabData _TabData; @@ -5129,7 +3225,7 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } { get { - return (_TabData == null) ? _TabData = new TabData(base.XmlNode) : _TabData; + return _TabData ?? (_TabData = new TabData(XmlNode)); } } public override string ToString() @@ -5166,15 +3262,6 @@ public LeftJustifyList(XmlNodeList xmlNodeList) : base(xmlNodeList) { } [TypeConverter(typeof(vlnIndexedListConverter))] public class StepDataList : vlnIndexedFormatList { -//public new StepData this[int index] -//{ -// get -// { -// foreach (StepData stepData in this) -// if (stepData.Index == index) return stepData; -// return null; -// } -//} public override vlnIndexedFormatList InheritedList { get @@ -5197,19 +3284,6 @@ public StepData this[string type] return null; } } -// the following was commented out because it uses the vlnFormat version of the code that indexes the list. -//public StepData this[int index] -//{ -// get -// { -// foreach (StepData stepData in this) -// if (stepData.Index == index) return stepData; -// StepDataList ttlParent = (StepDataList)InheritedList; //Check Inherited Value -// if (ttlParent != null) -// return ttlParent[index]; -// return null; -// } -//} public StepDataList(XmlNodeList xmlNodeList, IFormatOrFormatInfo myFormat) : base(xmlNodeList, myFormat) { } private StepData _HLS; public StepData HLS @@ -5330,32 +3404,6 @@ public StepData Substep return null; } } -// EmbeddedObject has been commented out, 'Equations' are separate top level items. -// This code was left here in case Equations , and other OLE objects, end up -// under the EmbeddedObject: - -// EmbeddedObject has inheritted types that represent OLE objects. -// The first of these is 'Equation'. Another that may be implemented later is Image. -// This is a special case, since only 'Equation' exists on initial development of -// embedded objects, 'skip' the embedded object layer when creating the list and -// go right to the equations. -//private StepData _EmbeddedObject; -//public StepData EmbeddedObject -//{ -// get -// { -// if (_EmbeddedObject != null) return _EmbeddedObject; -// foreach (StepData sd in this) -// { -// if (sd.Type == "EmbeddedObject") -// { -// _Equation = sd; -// return sd; -// } -// } -// return null; -// } -//} private StepData _Equation; public StepData Equation // equation has a parent of embedded object. { @@ -5404,45 +3452,21 @@ public StepData Equation // equation has a parent of embedded object. // add extra spacing before this step type private LazyLoad _STExtraSpace; - public int? STExtraSpace - { - get - { - return LazyLoad(ref _STExtraSpace, "StepLayoutData/@STExtraSpace"); - } - } + public int? STExtraSpace => LazyLoad(ref _STExtraSpace, "StepLayoutData/@STExtraSpace"); - // the number referencing the definition of a box around that step type - used for Caution and Note boxes - private LazyLoad _STBoxindex; - public int? STBoxindex - { - get - { - return LazyLoad(ref _STBoxindex, "StepLayoutData/@STBoxindex"); - } - } + // the number referencing the definition of a box around that step type - used for Caution and Note boxes + private LazyLoad _STBoxindex; + public int? STBoxindex => LazyLoad(ref _STBoxindex, "StepLayoutData/@STBoxindex"); - // will add a blank line after every N number of items - private LazyLoad _EveryNLines; - public int? EveryNLines - { - get - { - return LazyLoad(ref _EveryNLines, "StepLayoutData/@EveryNLines"); - } - } + // will add a blank line after every N number of items + private LazyLoad _EveryNLines; + public int? EveryNLines => LazyLoad(ref _EveryNLines, "StepLayoutData/@EveryNLines"); - // position the step item to start in the same column as it's parent - private LazyLoad _AlignWithParentTab; - public bool AlignWithParentTab - { - get - { - return LazyLoad(ref _AlignWithParentTab, "StepLayoutData/@AlignWithParentTab"); - } - } + // position the step item to start in the same column as it's parent + private LazyLoad _AlignWithParentTab; + public bool AlignWithParentTab => LazyLoad(ref _AlignWithParentTab, "StepLayoutData/@AlignWithParentTab"); - } + } #endregion #region StepEditData [TypeConverter(typeof(ExpandableObjectConverter))] @@ -5453,33 +3477,15 @@ public StepData Equation // equation has a parent of embedded object. { } private TypeMenu _TypeMenu; - public TypeMenu TypeMenu - { - get - { - return (_TypeMenu == null) ? _TypeMenu = new TypeMenu(base.XmlNode) : _TypeMenu; - } - } + public TypeMenu TypeMenu => _TypeMenu ?? (_TypeMenu = new TypeMenu(XmlNode)); - // list of actions defining what can be added to this step type (ex. addingNext, addingPrev, addingNote, addingCaution, addingTable) - private LazyLoad _AcTable; - public E_AccStep? AcTable - { - get - { - return LazyLoad(ref _AcTable, "StepEditData/@AcTable"); - } - } - // specify if this step type can be selected in the PROMS Search module - private LazyLoad _Searchable; - public bool Searchable - { - get - { - return LazyLoad(ref _Searchable, "StepEditData/@Searchable"); - } - } - } + // list of actions defining what can be added to this step type (ex. addingNext, addingPrev, addingNote, addingCaution, addingTable) + private LazyLoad _AcTable; + public E_AccStep? AcTable => LazyLoad(ref _AcTable, "StepEditData/@AcTable"); + // specify if this step type can be selected in the PROMS Search module + private LazyLoad _Searchable; + public bool Searchable => LazyLoad(ref _Searchable, "StepEditData/@Searchable"); + } #endregion #region StepPrintData @@ -5492,42 +3498,19 @@ public StepData Equation // equation has a parent of embedded object. } // allows a Horizontal adjustment (the tab and the text) of the step type when printed private LazyLoad _PosAdjust; - public float? PosAdjust - { - get - { - return LazyLoad(ref _PosAdjust, "StepPrintData/@PosAdjust"); - } - } + public float? PosAdjust => LazyLoad(ref _PosAdjust, "StepPrintData/@PosAdjust"); - // when printing, if this HLS uses a smart template (checklist formats) this value is used to determine when to split across 2 lines - private LazyLoad _HLSLength; - public int? HLSLength - { - get - { - return LazyLoad(ref _HLSLength, "StepPrintData/@HLSLength"); - } - } - // used to set the text justification when it is something other than Left Justified - private LazyLoad _Justify; - public string Justify - { - get - { - return LazyLoad(ref _Justify, "StepPrintData/@Justify"); - } - } - // B2022-003: BNPP Alarms (BNPPalr) - This will add a blank line after the sub of the sub-step - private LazyLoad _BlankAfterSubWithSub; - public bool BlankAfterSubWithSub // B2022-003: BNPP Alarms (BNPPalr) - incorrect line spacing for substeps off substeps. - { - get - { - return LazyLoad(ref _BlankAfterSubWithSub, "StepPrintData/@BlankAfterSubWithSub"); - } - } - } + // when printing, if this HLS uses a smart template (checklist formats) this value is used to determine when to split across 2 lines + private LazyLoad _HLSLength; + public int? HLSLength => LazyLoad(ref _HLSLength, "StepPrintData/@HLSLength"); + // used to set the text justification when it is something other than Left Justified + private LazyLoad _Justify; + public string Justify => LazyLoad(ref _Justify, "StepPrintData/@Justify"); + // B2022-003: BNPP Alarms (BNPPalr) - This will add a blank line after the sub of the sub-step + private LazyLoad _BlankAfterSubWithSub; + public bool BlankAfterSubWithSub // B2022-003: BNPP Alarms (BNPPalr) - incorrect line spacing for substeps off substeps. +=> LazyLoad(ref _BlankAfterSubWithSub, "StepPrintData/@BlankAfterSubWithSub"); + } #endregion #region TypeMenu @@ -5540,62 +3523,26 @@ public StepData Equation // equation has a parent of embedded object. } // This controls whether or not a step or sub-step type appears in the Insert and Search options for the user to select private LazyLoad _InMenu; - public bool InMenu - { - get - { - return LazyLoad(ref _InMenu, "StepEditData/TypeMenu/@InMenu"); - } - } - // RNOs are a specal case. This controls whether or not a RNO type appears in the Insert and Search options for the user to select - private LazyLoad _RnoInMenu; - public bool RnoInMenu - { - get - { - return LazyLoad(ref _RnoInMenu, "StepEditData/TypeMenu/@RnoInMenu"); - } - } + public bool InMenu => LazyLoad(ref _InMenu, "StepEditData/TypeMenu/@InMenu"); + // RNOs are a specal case. This controls whether or not a RNO type appears in the Insert and Search options for the user to select + private LazyLoad _RnoInMenu; + public bool RnoInMenu => LazyLoad(ref _RnoInMenu, "StepEditData/TypeMenu/@RnoInMenu"); - // The name of the step/sub-step type that appears in step/substep menus and lists. - // This allows us to override the default name - private LazyLoad _MenuItem; - public string MenuItem - { - get - { - return LazyLoad(ref _MenuItem, "StepEditData/TypeMenu/@MenuItem"); - } - } + // The name of the step/sub-step type that appears in step/substep menus and lists. + // This allows us to override the default name + private LazyLoad _MenuItem; + public string MenuItem => LazyLoad(ref _MenuItem, "StepEditData/TypeMenu/@MenuItem"); - // used to define an alternative menu name for when the sub-step type is used in an RNO (right column) - private LazyLoad _RnoMenuItem; - public string RnoMenuItem - { - get - { - return LazyLoad(ref _RnoMenuItem, "StepEditData/TypeMenu/@RnoMenuItem"); - } - } - // text to appear for the reason why a step/sub-step type cannot be changed - private LazyLoad _NoChgReason; - public string NoChgReason - { - get - { - return LazyLoad(ref _NoChgReason, "StepEditData/TypeMenu/@NoChgReason"); - } - } - // use with the Caution and Note sub-step types - specifes which other Cautions and Note types the current Caution or Note could be changed to via Step Properties - private LazyLoad _AlternateNameList; - public string AlternateNameList - { - get - { - return LazyLoad(ref _AlternateNameList, "StepEditData/TypeMenu/@AlternateNameList"); - } - } - } + // used to define an alternative menu name for when the sub-step type is used in an RNO (right column) + private LazyLoad _RnoMenuItem; + public string RnoMenuItem => LazyLoad(ref _RnoMenuItem, "StepEditData/TypeMenu/@RnoMenuItem"); + // text to appear for the reason why a step/sub-step type cannot be changed + private LazyLoad _NoChgReason; + public string NoChgReason => LazyLoad(ref _NoChgReason, "StepEditData/TypeMenu/@NoChgReason"); + // use with the Caution and Note sub-step types - specifes which other Cautions and Note types the current Caution or Note could be changed to via Step Properties + private LazyLoad _AlternateNameList; + public string AlternateNameList => LazyLoad(ref _AlternateNameList, "StepEditData/TypeMenu/@AlternateNameList"); + } #endregion #region Bullet [TypeConverter(typeof(ExpandableObjectConverter))] @@ -5607,22 +3554,16 @@ public StepData Equation // equation has a parent of embedded object. // - When using a bullet for multiple Cautions/Notes, use the font size of the Caution/Note text instead of the tab. // all the formats that use this specify the font and font size the the Font setting (below) private LazyLoad _Separate; - public bool Separate - { - get - { - return LazyLoad(ref _Separate, "TabData/Bullet/@Separate"); - } - } - // defines a font to use for the bullet character - private VE_Font _Font; + public bool Separate => LazyLoad(ref _Separate, "TabData/Bullet/@Separate"); + // defines a font to use for the bullet character + private VE_Font _Font; public VE_Font Font { get { if (_Font == null) { - XmlNode xn = vlnFormatDocument.LookupSingleStepNode(base.XmlNode, "Bullet[Font]"); + XmlNode xn = vlnFormatDocument.LookupSingleStepNode(XmlNode, "Bullet[Font]"); _Font = new VE_Font(xn); } return _Font; @@ -5642,219 +3583,99 @@ public StepData Equation // equation has a parent of embedded object. // list of one or more print macros to print with the step tab (used for a checkoff or inital line next to step number) private MacroList _MacroList; - public MacroList MacroList - { - get - { - return _MacroList == null ? _MacroList = new MacroList(SelectNodes("TabData/MacroList/Macro")) : _MacroList; - } - } + public MacroList MacroList => _MacroList ?? (_MacroList = new MacroList(SelectNodes("TabData/MacroList/Macro"))); - // Used to define a designator character to appear in the Step Editor for when the printed character is a macro - // F2022-024 used with the Time Critial Step type (used in Robinson EOP/AOP format) - // this will put the character asigned in the Time Critial Step format defination next to the step tab on the edit screen - // When this step is printed, a macro named Clock (genmac format file) is used instead to print a clock symbol - private LazyLoad _MacroEditTag; - public string MacroEditTag - { - get - { - return LazyLoad(ref _MacroEditTag, "TabData/@MacroEditTag"); - } - } + // Used to define a designator character to appear in the Step Editor for when the printed character is a macro + // F2022-024 used with the Time Critial Step type (used in Robinson EOP/AOP format) + // this will put the character asigned in the Time Critial Step format defination next to the step tab on the edit screen + // When this step is printed, a macro named Clock (genmac format file) is used instead to print a clock symbol + private LazyLoad _MacroEditTag; + public string MacroEditTag => LazyLoad(ref _MacroEditTag, "TabData/@MacroEditTag"); - // defines the formatting of the step tab on the edit screen - private LazyLoad _IdentEdit; - public string IdentEdit - { - get - { - return LazyLoad(ref _IdentEdit, "TabData/@IdentEdit"); - } - } - // defines the formatting of the step tab when printed - private LazyLoad _IdentPrint; - public string IdentPrint - { - get - { - return LazyLoad(ref _IdentPrint, "TabData/@Ident"); - } - } + // defines the formatting of the step tab on the edit screen + private LazyLoad _IdentEdit; + public string IdentEdit => LazyLoad(ref _IdentEdit, "TabData/@IdentEdit"); + // defines the formatting of the step tab when printed + private LazyLoad _IdentPrint; + public string IdentPrint => LazyLoad(ref _IdentPrint, "TabData/@Ident"); - // used in background document formats - allows us to put the step number on one line, then the step text on the next line and it allows us to define prefix text used before each. - private LazyLoad _IdentAltPrint; - public string IdentAltPrint - { - get - { - return LazyLoad(ref _IdentAltPrint, "TabData/@IdentAltPrint"); - } - } + // used in background document formats - allows us to put the step number on one line, then the step text on the next line and it allows us to define prefix text used before each. + private LazyLoad _IdentAltPrint; + public string IdentAltPrint => LazyLoad(ref _IdentAltPrint, "TabData/@IdentAltPrint"); - // defines a step type's corresponding RNO tab seen in the PROMS Step Editor - private LazyLoad _RNOIdentEdit; - public string RNOIdentEdit - { - get - { - return LazyLoad(ref _RNOIdentEdit, "TabData/@RNOIdentEdit"); - } - } + // defines a step type's corresponding RNO tab seen in the PROMS Step Editor + private LazyLoad _RNOIdentEdit; + public string RNOIdentEdit => LazyLoad(ref _RNOIdentEdit, "TabData/@RNOIdentEdit"); - // defines a step type's corresponding RNO tab for the printed output - private LazyLoad _RNOIdent; - public string RNOIdent - { - get - { - return LazyLoad(ref _RNOIdent, "TabData/@RNOIdent"); - } - } - // this uses the same format item as RNOIdent - private LazyLoad _RNOIdentPrint; - public string RNOIdentPrint - { - get - { - return LazyLoad(ref _RNOIdentPrint, "TabData/@RNOIdent"); - } - } - // Adds a print macro for the high level RNO when the user want it to be a Continuous Action - // while the corresponding AER is not a continuous action - // C2026-003 used in RNO step definition for Vogtle 3&4 two column format - // use with AddContActTagToHighLevelRNOWhenIncludedOnCAS set to True in the format file's StpSectLayData - private LazyLoad _CASPrintMacro; - public string CASPrintMacro - { - get - { - return LazyLoad(ref _CASPrintMacro, "TabData/@CASPrintMacro"); - } - } - // Adds a character indicator in the step editor for the high level RNO when the user want it to be a Continuous Action - // while the corresponding AER is not a continuous action - // C2026-003 used in RNO step definition for Vogtle 3&4 two colmn format - // use with AddContActTagToHighLevelRNOWhenIncludedOnCAS set to True in the format file's StpSectLayData - private LazyLoad _CASEditTag; - public string CASEditTag - { - get - { - return LazyLoad(ref _CASEditTag, "TabData/@CASEditTag"); - } - } + // defines a step type's corresponding RNO tab for the printed output + private LazyLoad _RNOIdent; + public string RNOIdent => LazyLoad(ref _RNOIdent, "TabData/@RNOIdent"); + // this uses the same format item as RNOIdent + private LazyLoad _RNOIdentPrint; + public string RNOIdentPrint => LazyLoad(ref _RNOIdentPrint, "TabData/@RNOIdent"); + // Adds a print macro for the high level RNO when the user want it to be a Continuous Action + // while the corresponding AER is not a continuous action + // C2026-003 used in RNO step definition for Vogtle 3&4 two column format + // use with AddContActTagToHighLevelRNOWhenIncludedOnCAS set to True in the format file's StpSectLayData + private LazyLoad _CASPrintMacro; + public string CASPrintMacro => LazyLoad(ref _CASPrintMacro, "TabData/@CASPrintMacro"); + // Adds a character indicator in the step editor for the high level RNO when the user want it to be a Continuous Action + // while the corresponding AER is not a continuous action + // C2026-003 used in RNO step definition for Vogtle 3&4 two colmn format + // use with AddContActTagToHighLevelRNOWhenIncludedOnCAS set to True in the format file's StpSectLayData + private LazyLoad _CASEditTag; + public string CASEditTag => LazyLoad(ref _CASEditTag, "TabData/@CASEditTag"); - // don't use the defined macro when creating a step tab for the step type's RNO - private LazyLoad _RNOExcludeMacros; - public bool RNOExcludeMacros - { - get - { - return LazyLoad(ref _RNOExcludeMacros, "TabData/@RNOExcludeMacros"); - } - } + // don't use the defined macro when creating a step tab for the step type's RNO + private LazyLoad _RNOExcludeMacros; + public bool RNOExcludeMacros => LazyLoad(ref _RNOExcludeMacros, "TabData/@RNOExcludeMacros"); - // Don't Align Tabs for numeric tabs that can go to 2 digits - Default is False - we do align numeric tabs - // - used in the Indian Point Unit 2 Background format (IP2BCK) - private LazyLoad _NoTabAlign; - public bool NoTabAlign - { - get - { - return LazyLoad(ref _NoTabAlign, "TabData/@NoTabAlign"); - } - } + // Don't Align Tabs for numeric tabs that can go to 2 digits - Default is False - we do align numeric tabs + // - used in the Indian Point Unit 2 Background format (IP2BCK) + private LazyLoad _NoTabAlign; + public bool NoTabAlign => LazyLoad(ref _NoTabAlign, "TabData/@NoTabAlign"); - // used for Caution and Note steps, include the step number along with the Caution or Note tab - // was put in for V.C. Summer Units 3 & 4 formats - private LazyLoad _IncludeStepNum; - public bool IncludeStepNum - { - get - { - return LazyLoad(ref _IncludeStepNum, "TabData/@IncludeStepNum"); - } - } - // used for Caution and Note steps, include the section number along with the Caution or Note tab - // - used with IncludeStepNum - // was put in for V.C. Summer Units 3 & 4 formats - private LazyLoad _IncludeSectionNum; - public bool IncludeSectionNum - { - get - { - return LazyLoad(ref _IncludeSectionNum, "TabData/@IncludeSectionNum"); - } - } - // used to center justify the resulting Caution or Note tab within the defined Caution or Note box - private LazyLoad _Justify; - public string Justify - { - get - { - return LazyLoad(ref _Justify, "TabData/@Justify"); - } - } + // used for Caution and Note steps, include the step number along with the Caution or Note tab + // was put in for V.C. Summer Units 3 & 4 formats + private LazyLoad _IncludeStepNum; + public bool IncludeStepNum => LazyLoad(ref _IncludeStepNum, "TabData/@IncludeStepNum"); + // used for Caution and Note steps, include the section number along with the Caution or Note tab + // - used with IncludeStepNum + // was put in for V.C. Summer Units 3 & 4 formats + private LazyLoad _IncludeSectionNum; + public bool IncludeSectionNum => LazyLoad(ref _IncludeSectionNum, "TabData/@IncludeSectionNum"); + // used to center justify the resulting Caution or Note tab within the defined Caution or Note box + private LazyLoad _Justify; + public string Justify => LazyLoad(ref _Justify, "TabData/@Justify"); - // put in for V.C. Summer's Transition Caution Transition Note types - The text of these types contain a transtion link and is used for the Caution or Note tab of the "normal" Caution or Note - used with IsTransition TabData flag - private LazyLoad _UsePreviousStyle; - public bool UsePreviousStyle - { - get - { - return LazyLoad(ref _UsePreviousStyle, "TabData/@UsePreviousStyle"); - } - } + // put in for V.C. Summer's Transition Caution Transition Note types - The text of these types contain a transtion link and is used for the Caution or Note tab of the "normal" Caution or Note - used with IsTransition TabData flag + private LazyLoad _UsePreviousStyle; + public bool UsePreviousStyle => LazyLoad(ref _UsePreviousStyle, "TabData/@UsePreviousStyle"); - // The text of these types contain a transtion link and is used for the Caution or Note tab of the "normal" Caution or Note - private LazyLoad _IsTransition; - public bool IsTransition - { - get - { - return LazyLoad(ref _IsTransition, "TabData/@IsTransition"); - } - } + // The text of these types contain a transtion link and is used for the Caution or Note tab of the "normal" Caution or Note + private LazyLoad _IsTransition; + public bool IsTransition => LazyLoad(ref _IsTransition, "TabData/@IsTransition"); - // set a hard-coded with of the step tab - private LazyLoad _IdentWidth; - public float? IdentWidth - { - get - { - return LazyLoad(ref _IdentWidth, "TabData/@IdentWidth"); - } - } + // set a hard-coded with of the step tab + private LazyLoad _IdentWidth; + public float? IdentWidth => LazyLoad(ref _IdentWidth, "TabData/@IdentWidth"); - // adjustment for step type's RNO tab width - private LazyLoad _RNOAdjustTabSize; - public float? RNOAdjustTabSize - { - get - { - return LazyLoad(ref _RNOAdjustTabSize, "TabData/@RNOAdjustTabSize"); - } - } + // adjustment for step type's RNO tab width + private LazyLoad _RNOAdjustTabSize; + public float? RNOAdjustTabSize => LazyLoad(ref _RNOAdjustTabSize, "TabData/@RNOAdjustTabSize"); - // adjustment to the horizontal position of the step tab's print macro - private LazyLoad _MacroTabAdjust; - public float? MacroTabAdjust - { - get - { - return LazyLoad(ref _MacroTabAdjust, "TabData/@MacroTabAdjust"); - } - } - // specified font to use for the step tab - private VE_Font _Font; + // adjustment to the horizontal position of the step tab's print macro + private LazyLoad _MacroTabAdjust; + public float? MacroTabAdjust => LazyLoad(ref _MacroTabAdjust, "TabData/@MacroTabAdjust"); + // specified font to use for the step tab + private VE_Font _Font; public VE_Font Font { get { if (_Font == null) { - XmlNode xn = vlnFormatDocument.LookupSingleStepNode(base.XmlNode, "TabData[Font]"); + XmlNode xn = vlnFormatDocument.LookupSingleStepNode(XmlNode, "TabData[Font]"); _Font = new VE_Font(xn); } return _Font; @@ -5863,63 +3684,32 @@ public StepData Equation // equation has a parent of embedded object. // gets the step tab's bull information if so defined private Bullet _Bullet; - public Bullet Bullet - { - get - { - return (_Bullet == null) ? _Bullet = new Bullet(base.XmlNode) : _Bullet; - } - } + public Bullet Bullet => _Bullet ?? (_Bullet = new Bullet(XmlNode)); - // will prevent white space from being removed before and after the Tab text - // - only used when tab justification is Centered - private LazyLoad _NoTrim; - public bool NoTrim - { - get - { - return LazyLoad(ref _NoTrim, "TabData/@NoTrim"); - } - } + // will prevent white space from being removed before and after the Tab text + // - only used when tab justification is Centered + private LazyLoad _NoTrim; + public bool NoTrim => LazyLoad(ref _NoTrim, "TabData/@NoTrim"); - // use the entire section number when building the step tab - existing logic looked for the text "Attachmen" then used the letter/number that followed it - private LazyLoad _UseEntireSectionNum; - public bool UseEntireSectionNum - { - get - { - return LazyLoad(ref _UseEntireSectionNum, "TabData/@UseEntireSectionNum"); - } - } + // use the entire section number when building the step tab - existing logic looked for the text "Attachmen" then used the letter/number that followed it + private LazyLoad _UseEntireSectionNum; + public bool UseEntireSectionNum => LazyLoad(ref _UseEntireSectionNum, "TabData/@UseEntireSectionNum"); - // this will remove white space before/after the sequential tab value - // put in for Vogtal Units 3 & 4 formats for continuous action sub-steps - // they have tab value within parenthesis and for a single digit/letter we don't want the white steps before or after it - private LazyLoad _TrimSeqTabValue; - public bool TrimSeqTabValue - { - get - { - return LazyLoad(ref _TrimSeqTabValue, "TabData/@TrimSeqTabValue"); - } - } + // this will remove white space before/after the sequential tab value + // put in for Vogtal Units 3 & 4 formats for continuous action sub-steps + // they have tab value within parenthesis and for a single digit/letter we don't want the white steps before or after it + private LazyLoad _TrimSeqTabValue; + public bool TrimSeqTabValue => LazyLoad(ref _TrimSeqTabValue, "TabData/@TrimSeqTabValue"); - } + } #endregion StepTab #region MacroList [TypeConverter(typeof(vlnListConverter))] public class MacroList : vlnNamedFormatList { public MacroList(XmlNodeList xmlNodeList) : base(xmlNodeList, null) { } - public override vlnNamedFormatList InheritedList - { - get - { - - return null; - } - } - } + public override vlnNamedFormatList InheritedList => null; + } #endregion MacroList #region Macro [TypeConverter(typeof(ExpandableObjectConverter))] @@ -5930,16 +3720,10 @@ public StepData Equation // equation has a parent of embedded object. // used to identify the tab's print macro private LazyLoad _Name; - public string Name - { - get - { - return LazyLoad(ref _Name, "@Name"); - } - } + public string Name => LazyLoad(ref _Name, "@Name"); - // the name of the print macro defined in the format's corresponding SVG (genmac) file - private LazyLoad _MacroDef; + // the name of the print macro defined in the format's corresponding SVG (genmac) file + private LazyLoad _MacroDef; public string MacroDef { get @@ -5963,38 +3747,20 @@ public StepData Equation // equation has a parent of embedded object. // hard coded horizontal addjustment used before printing the macro private LazyLoad _MacroXOffSet; - public float? MacroXOffSet - { - get - { - return LazyLoad(ref _MacroXOffSet, "@MacroXOffSet"); - } - } + public float? MacroXOffSet => LazyLoad(ref _MacroXOffSet, "@MacroXOffSet"); - // a width adjustment to the print macro (usually a negative value) - private LazyLoad _SingleColWidthAdjust; - public float? SingleColWidthAdjust - { - get - { - return LazyLoad(ref _SingleColWidthAdjust, "@SingleColWidthAdjust"); - } - } + // a width adjustment to the print macro (usually a negative value) + private LazyLoad _SingleColWidthAdjust; + public float? SingleColWidthAdjust => LazyLoad(ref _SingleColWidthAdjust, "@SingleColWidthAdjust"); - // locate the macro along with the tab's offset. - // however, if the tab is more than 2 characters long, adjust so that it aligns with the - // last two characters, not the first 2. - private LazyLoad _LocWithXOff; - public bool? LocWithXOff - { - get - { - return LazyLoad(ref _LocWithXOff, "@LocWithXOff"); - } - } + // locate the macro along with the tab's offset. + // however, if the tab is more than 2 characters long, adjust so that it aligns with the + // last two characters, not the first 2. + private LazyLoad _LocWithXOff; + public bool? LocWithXOff => LazyLoad(ref _LocWithXOff, "@LocWithXOff"); - // Groupings is used to only have the macro if there are N or more of the type in the grouping. - private LazyLoad _Grouping; + // Groupings is used to only have the macro if there are N or more of the type in the grouping. + private LazyLoad _Grouping; public int? Grouping { get @@ -6052,254 +3818,105 @@ public StepData Equation // equation has a parent of embedded object. // used by the step type to reference which box to use (Cautions, Notes) private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } - // This was added to support 3 line box for VC Summer Units 3 & 4 Alarms. It is only checked in the 'double line' vlnbox.cs code! - private LazyLoad _NumLines; - public int? NumLines - { - get - { - return LazyLoad(ref _NumLines, "@NumLines"); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); + // This was added to support 3 line box for VC Summer Units 3 & 4 Alarms. It is only checked in the 'double line' vlnbox.cs code! + private LazyLoad _NumLines; + public int? NumLines => LazyLoad(ref _NumLines, "@NumLines"); - // the column where the box starts printing - private LazyLoad _Start; - public float? Start - { - get - { - return LazyLoad(ref _Start, "@Start"); - } - } + // the column where the box starts printing + private LazyLoad _Start; + public float? Start => LazyLoad(ref _Start, "@Start"); - // the column where to stop printing the box - private LazyLoad _End; - public float? End - { - get - { - return LazyLoad(ref _End, "@End"); - } - } + // the column where to stop printing the box + private LazyLoad _End; + public float? End => LazyLoad(ref _End, "@End"); - // column position to start printing the text that is inside the box - private LazyLoad _TxtStart; - public float? TxtStart - { - get - { - return LazyLoad(ref _TxtStart, "@TxtStart"); - } - } + // column position to start printing the text that is inside the box + private LazyLoad _TxtStart; + public float? TxtStart => LazyLoad(ref _TxtStart, "@TxtStart"); - // the length of the text before it wraps to the next line - private LazyLoad _TxtWidth; - public float? TxtWidth - { - get - { - return LazyLoad(ref _TxtWidth, "@TxtWidth"); - } - } + // the length of the text before it wraps to the next line + private LazyLoad _TxtWidth; + public float? TxtWidth => LazyLoad(ref _TxtWidth, "@TxtWidth"); - // an absolute position from the left margin where the Caution or Note tab text (box header) is placed within the drawn box - used for boxed Cautions and/or Notes - Caution or Note tab justification needs to be "Centered" - private LazyLoad _TabPos; - public float? TabPos - { - get - { - return LazyLoad(ref _TabPos, "@TabPos"); - } - } + // an absolute position from the left margin where the Caution or Note tab text (box header) is placed within the drawn box - used for boxed Cautions and/or Notes - Caution or Note tab justification needs to be "Centered" + private LazyLoad _TabPos; + public float? TabPos => LazyLoad(ref _TabPos, "@TabPos"); - // F2024-078 adjusts the the spacing before the Note/Caution tab - the space betwee the top of the box and the tab text - private LazyLoad _AdjSpB4Tab; - public float? AdjSpB4Tab - { - get - { - return LazyLoad(ref _AdjSpB4Tab, "@AdjSpB4Tab"); - } - } + // F2024-078 adjusts the the spacing before the Note/Caution tab - the space betwee the top of the box and the tab text + private LazyLoad _AdjSpB4Tab; + public float? AdjSpB4Tab => LazyLoad(ref _AdjSpB4Tab, "@AdjSpB4Tab"); - // F2024-078 adjusts the the spacing after the Note/Caution tab - the space betwee the tab text and the first line of of Note/Caution text - private LazyLoad _AdjSpAftTab; - public float? AdjSpAftTab - { - get - { - return LazyLoad(ref _AdjSpAftTab, "@AdjSpAftTab"); - } - } + // F2024-078 adjusts the the spacing after the Note/Caution tab - the space betwee the tab text and the first line of of Note/Caution text + private LazyLoad _AdjSpAftTab; + public float? AdjSpAftTab => LazyLoad(ref _AdjSpAftTab, "@AdjSpAftTab"); - // F2024-078 adjusts the the spacing after the last line of Note/Caution text - between the last line of text and the bottom of the box - private LazyLoad _AdjLastBlnkLn; - public float? AdjLastBlnkLn - { - get - { - return LazyLoad(ref _AdjLastBlnkLn, "@AdjLastBlnkLn"); - } - } + // F2024-078 adjusts the the spacing after the last line of Note/Caution text - between the last line of text and the bottom of the box + private LazyLoad _AdjLastBlnkLn; + public float? AdjLastBlnkLn => LazyLoad(ref _AdjLastBlnkLn, "@AdjLastBlnkLn"); - // this will adjust the line spacing when an extra thick line is used for a box, so that the text below the box doesn't hit up against the bottom of the box - private LazyLoad _ThickDouble; // F2021-026: Barakah single column 2 thick double lines around Warnings - public bool ThickDouble - { - get - { - return LazyLoad(ref _ThickDouble, "@ThickDouble"); - } - } + // this will adjust the line spacing when an extra thick line is used for a box, so that the text below the box doesn't hit up against the bottom of the box + private LazyLoad _ThickDouble; // F2021-026: Barakah single column 2 thick double lines around Warnings + public bool ThickDouble => LazyLoad(ref _ThickDouble, "@ThickDouble"); - // the character used for the Upper Right Corner of the box - private LazyLoad _BXURC; - public string BXURC - { - get - { - return LazyLoad(ref _BXURC, "@BXURC"); - } - } + // the character used for the Upper Right Corner of the box + private LazyLoad _BXURC; + public string BXURC => LazyLoad(ref _BXURC, "@BXURC"); - // the character used to drawn the Horizontal line of the box - private LazyLoad _BXHorz; - public string BXHorz - { - get - { - return LazyLoad(ref _BXHorz, "@BXHorz"); - } - } + // the character used to drawn the Horizontal line of the box + private LazyLoad _BXHorz; + public string BXHorz => LazyLoad(ref _BXHorz, "@BXHorz"); - // the character used for the Upper Left Corner of the box - private LazyLoad _BXULC; - public string BXULC - { - get - { - return LazyLoad(ref _BXULC, "@BXULC"); - } - } - // the character used for the vertcal lines of the left and right sides of the box - private LazyLoad _BXVert; - public string BXVert - { - get - { - return LazyLoad(ref _BXVert, "@BXVert"); - } - } + // the character used for the Upper Left Corner of the box + private LazyLoad _BXULC; + public string BXULC => LazyLoad(ref _BXULC, "@BXULC"); + // the character used for the vertcal lines of the left and right sides of the box + private LazyLoad _BXVert; + public string BXVert => LazyLoad(ref _BXVert, "@BXVert"); - // the character used for the left side that connect to a horizontal line - // (usually the char looks like a T that is rotated to the left 90 degrees) - private LazyLoad _BXMLS; - public string BXMLS - { - get - { - return LazyLoad(ref _BXMLS, "@BXMLS"); - } - } + // the character used for the left side that connect to a horizontal line + // (usually the char looks like a T that is rotated to the left 90 degrees) + private LazyLoad _BXMLS; + public string BXMLS => LazyLoad(ref _BXMLS, "@BXMLS"); - // the character used for the right side that connect to a horizontal line - // (usually the char looks like a T that is rotated to the right 90 degrees) - private LazyLoad _BXMRS; - public string BXMRS - { - get - { - return LazyLoad(ref _BXMRS, "@BXMRS"); - } - } + // the character used for the right side that connect to a horizontal line + // (usually the char looks like a T that is rotated to the right 90 degrees) + private LazyLoad _BXMRS; + public string BXMRS => LazyLoad(ref _BXMRS, "@BXMRS"); - // the character used for the Lower (bottom) Right Corner of the box - private LazyLoad _BXLRC; - public string BXLRC - { - get - { - return LazyLoad(ref _BXLRC, "@BXLRC"); - } - } + // the character used for the Lower (bottom) Right Corner of the box + private LazyLoad _BXLRC; + public string BXLRC => LazyLoad(ref _BXLRC, "@BXLRC"); - // the character used for the Lower (bottom) Left Corner of the box - private LazyLoad _BXLLC; - public string BXLLC - { - get - { - return LazyLoad(ref _BXLLC, "@BXLLC"); - } - } + // the character used for the Lower (bottom) Left Corner of the box + private LazyLoad _BXLLC; + public string BXLLC => LazyLoad(ref _BXLLC, "@BXLLC"); - // character used in the middle of the box an intersection of four cells - // - looks like a big plus sign - private LazyLoad _BXMID; - public string BXMID - { - get - { - return LazyLoad(ref _BXMID, "@BXMID"); - } - } + // character used in the middle of the box an intersection of four cells + // - looks like a big plus sign + private LazyLoad _BXMID; + public string BXMID => LazyLoad(ref _BXMID, "@BXMID"); - // character used for the Lower Horizontal line (bottom of the box) - private LazyLoad _BXLHorz; - public string BXLHorz - { - get - { - return LazyLoad(ref _BXLHorz, "@BXLHorz"); - } - } - // character use on the top line of the box that will connect to a horizontal line in the next row of the box - // - looks like a "T" character - private LazyLoad _BXUMID; - public string BXUMID - { - get - { - return LazyLoad(ref _BXUMID, "@BXUMID"); - } - } + // character used for the Lower Horizontal line (bottom of the box) + private LazyLoad _BXLHorz; + public string BXLHorz => LazyLoad(ref _BXLHorz, "@BXLHorz"); + // character use on the top line of the box that will connect to a horizontal line in the next row of the box + // - looks like a "T" character + private LazyLoad _BXUMID; + public string BXUMID => LazyLoad(ref _BXUMID, "@BXUMID"); - // character use on the bottom line of the box that will connect to a horizontal line in the row above- looks like an upside down "T" character - private LazyLoad _BXLMID; - public string BXLMID - { - get - { - return LazyLoad(ref _BXLMID, "@BXLMID"); - } - } - // a specific font to use for the box drawing characters - private VE_Font _Font; - public VE_Font Font - { - get - { - return (_Font == null) ? _Font = new VE_Font(base.XmlNode) : _Font; - } - } - public override string GetPDDisplayName() - { return string.Format("[{0}]", Index); } - public override string GetPDCategory() - { return "Box Definition"; } - public override string ToString() - { - return String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}", - BXURC, BXHorz, BXULC, BXVert, BXMLS, BXMRS, BXLRC, BXLLC, BXMID, BXLHorz, BXUMID, BXLMID); - } - // this return string is used in a Switch/Case statement to determin the visual style of the box when printing - public string BoxStyle + // character use on the bottom line of the box that will connect to a horizontal line in the row above- looks like an upside down "T" character + private LazyLoad _BXLMID; + public string BXLMID => LazyLoad(ref _BXLMID, "@BXLMID"); + // a specific font to use for the box drawing characters + private VE_Font _Font; + public VE_Font Font => _Font ?? (_Font = new VE_Font(XmlNode)); + public override string GetPDDisplayName() => string.Format("[{0}]", Index); + public override string GetPDCategory() => "Box Definition"; + public override string ToString() => String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}", + BXURC, BXHorz, BXULC, BXVert, BXMLS, BXMRS, BXLRC, BXLLC, BXMID, BXLHorz, BXUMID, BXLMID); + // this return string is used in a Switch/Case statement to determin the visual style of the box when printing + public string BoxStyle { get { @@ -6334,274 +3951,113 @@ public StepData Equation // equation has a parent of embedded object. public class TransData : vlnFormatItem { private TransTypeList _TransTypeList; - public TransTypeList TransTypeList - { - get - { - return (_TransTypeList == null || _TransTypeList.MaxIndex == 0) ? _TransTypeList = new TransTypeList(SelectNodes("TransTypeData/TransTypes"), MyFormat) : _TransTypeList; - } - } - public TransData(XmlNode xmlNode) : base(xmlNode) { } + public TransTypeList TransTypeList => (_TransTypeList == null || _TransTypeList.MaxIndex == 0) ? _TransTypeList = new TransTypeList(SelectNodes("TransTypeData/TransTypes"), MyFormat) : _TransTypeList; + public TransData(XmlNode xmlNode) : base(xmlNode) { } // a character that is placed before and after the procedure title that's in the transition text private LazyLoad _DelimiterForTransitionTitle; - public string DelimiterForTransitionTitle - { - get - { - return LazyLoad(ref _DelimiterForTransitionTitle, "@DelimiterForTransitionTitle"); - } - } + public string DelimiterForTransitionTitle => LazyLoad(ref _DelimiterForTransitionTitle, "@DelimiterForTransitionTitle"); - // used to clean up step/sub-step delimeters so they are all just periods in transitions and are removed when getting step/sub-step tab for some reports - private LazyLoad _StepSubstepDelimeter; - public string StepSubstepDelimeter - { - get - { - return LazyLoad(ref _StepSubstepDelimeter, "@StepSubstepDelimeter"); - } - } + // used to clean up step/sub-step delimeters so they are all just periods in transitions and are removed when getting step/sub-step tab for some reports + private LazyLoad _StepSubstepDelimeter; + public string StepSubstepDelimeter => LazyLoad(ref _StepSubstepDelimeter, "@StepSubstepDelimeter"); - // string to use between the first step and last step of the transition ("Through" vs "Thur" etc.) - private LazyLoad _ThroughString; - public string ThroughString - { - get - { - return LazyLoad(ref _ThroughString, "@ThroughString"); - } - } + // string to use between the first step and last step of the transition ("Through" vs "Thur" etc.) + private LazyLoad _ThroughString; + public string ThroughString => LazyLoad(ref _ThroughString, "@ThroughString"); - // this will uppercase the transition text - private LazyLoad _CapsTransitions; - public bool CapsTransitions - { - get - { - return LazyLoad(ref _CapsTransitions, "@CapsTransitions"); - } - } + // this will uppercase the transition text + private LazyLoad _CapsTransitions; + public bool CapsTransitions => LazyLoad(ref _CapsTransitions, "@CapsTransitions"); - // this will uppercase the section title inside the transition - private LazyLoad _CapsTransitionsSection; - public bool CapsTransitionsSection - { - get - { - return LazyLoad(ref _CapsTransitionsSection, "@CapsTransitionsSection"); - } - } + // this will uppercase the section title inside the transition + private LazyLoad _CapsTransitionsSection; + public bool CapsTransitionsSection => LazyLoad(ref _CapsTransitionsSection, "@CapsTransitionsSection"); - // this will underline the transsition text - private LazyLoad _Underline; - public bool Underline - { - get - { - return LazyLoad(ref _Underline, "@Underline"); - } - } + // this will underline the transsition text + private LazyLoad _Underline; + public bool Underline => LazyLoad(ref _Underline, "@Underline"); - // add the high level step number to the sub-step tab in the transition - private LazyLoad _TStepNoFlag; - public bool TStepNoFlag - { - get - { - return LazyLoad(ref _TStepNoFlag, "@TStepNoFlag"); - } - } + // add the high level step number to the sub-step tab in the transition + private LazyLoad _TStepNoFlag; + public bool TStepNoFlag => LazyLoad(ref _TStepNoFlag, "@TStepNoFlag"); - // will uppercase AND in And transition type - private LazyLoad _UpcaseTranAnd; - public bool UpcaseTranAnd - { - get - { - return LazyLoad(ref _UpcaseTranAnd, "@UpcaseTranAnd"); - } - } + // will uppercase AND in And transition type + private LazyLoad _UpcaseTranAnd; + public bool UpcaseTranAnd => LazyLoad(ref _UpcaseTranAnd, "@UpcaseTranAnd"); - // will uppercase the first letter of each word in the transition - private LazyLoad _Cap1stCharTrans; - public bool Cap1stCharTrans - { - get - { - return LazyLoad(ref _Cap1stCharTrans, "@Cap1stCharTrans"); - } - } + // will uppercase the first letter of each word in the transition + private LazyLoad _Cap1stCharTrans; + public bool Cap1stCharTrans => LazyLoad(ref _Cap1stCharTrans, "@Cap1stCharTrans"); - // Title Case section title in the transition - private LazyLoad _Cap1stCharTransSection; - public bool Cap1stCharTransSection - { - get - { - return LazyLoad(ref _Cap1stCharTransSection, "@Cap1stCharTransSection"); - } - } - // Title Case Section Number in the transition - private LazyLoad _Cap1stCharTransSectionNumber; - public bool Cap1stCharTransSectionNumber - { - get - { - return LazyLoad(ref _Cap1stCharTransSectionNumber, "@Cap1stCharTransSectionNumber"); - } - } + // Title Case section title in the transition + private LazyLoad _Cap1stCharTransSection; + public bool Cap1stCharTransSection => LazyLoad(ref _Cap1stCharTransSection, "@Cap1stCharTransSection"); + // Title Case Section Number in the transition + private LazyLoad _Cap1stCharTransSectionNumber; + public bool Cap1stCharTransSectionNumber => LazyLoad(ref _Cap1stCharTransSectionNumber, "@Cap1stCharTransSectionNumber"); - // put parenthesis around section title - private LazyLoad _ParensAroundSectionTitle; - public bool ParensAroundSectionTitle - { - get - { - return LazyLoad(ref _ParensAroundSectionTitle, "@ParensAroundSectionTitle"); - } - } + // put parenthesis around section title + private LazyLoad _ParensAroundSectionTitle; + public bool ParensAroundSectionTitle => LazyLoad(ref _ParensAroundSectionTitle, "@ParensAroundSectionTitle"); - // turns on the option to add a page number to the transition BUT only for transition types 1, 2, and 4 - private LazyLoad _UseTransitionModifier; - public bool UseTransitionModifier - { - get - { - return LazyLoad(ref _UseTransitionModifier, "@UseTransitionModifier"); - } - } + // turns on the option to add a page number to the transition BUT only for transition types 1, 2, and 4 + private LazyLoad _UseTransitionModifier; + public bool UseTransitionModifier => LazyLoad(ref _UseTransitionModifier, "@UseTransitionModifier"); - // will include a page number with the transitions - will not turn on option box to add a the page number - private LazyLoad _UseSpecificTransitionModifier; - public bool UseSpecificTransitionModifier - { - get - { - return LazyLoad(ref _UseSpecificTransitionModifier, "@UseSpecificTransitionModifier"); - } - } + // will include a page number with the transitions - will not turn on option box to add a the page number + private LazyLoad _UseSpecificTransitionModifier; + public bool UseSpecificTransitionModifier => LazyLoad(ref _UseSpecificTransitionModifier, "@UseSpecificTransitionModifier"); - // the specific page number is always printed even if it is next or previous page, instead of using the 'Next Page' or 'Previous Page' text - private LazyLoad _UseSpecificPageNo; - public bool UseSpecificPageNo - { - get - { - return LazyLoad(ref _UseSpecificPageNo, "@UseSpecificPageNo"); - } - } + // the specific page number is always printed even if it is next or previous page, instead of using the 'Next Page' or 'Previous Page' text + private LazyLoad _UseSpecificPageNo; + public bool UseSpecificPageNo => LazyLoad(ref _UseSpecificPageNo, "@UseSpecificPageNo"); - // indclude the section number and section title when the {Sect Hdr} transition format token is used - set to False if we only want the section number - private LazyLoad _UseSecTitles; - public bool UseSecTitles - { - get - { - return LazyLoad(ref _UseSecTitles, "@UseSecTitles"); - } - } + // indclude the section number and section title when the {Sect Hdr} transition format token is used - set to False if we only want the section number + private LazyLoad _UseSecTitles; + public bool UseSecTitles => LazyLoad(ref _UseSecTitles, "@UseSecTitles"); - // turn on the section selection list for transitions that use the default steps section - private LazyLoad _DoSectionTransitions; - public bool DoSectionTransitions - { - get - { - return LazyLoad(ref _DoSectionTransitions, "@DoSectionTransitions"); - } - } - // having a default step section specified is not required for transitions with section information - private LazyLoad _NoDefaultSectReq; - public bool NoDefaultSectReq - { - get - { - return LazyLoad(ref _NoDefaultSectReq, "@NoDefaultSectReq"); - } - } + // turn on the section selection list for transitions that use the default steps section + private LazyLoad _DoSectionTransitions; + public bool DoSectionTransitions => LazyLoad(ref _DoSectionTransitions, "@DoSectionTransitions"); + // having a default step section specified is not required for transitions with section information + private LazyLoad _NoDefaultSectReq; + public bool NoDefaultSectReq => LazyLoad(ref _NoDefaultSectReq, "@NoDefaultSectReq"); - // replace spaces with hard spaces in procedure number - private LazyLoad _HardSpTranProcNumb; - public bool HardSpTranProcNumb - { - get - { - return LazyLoad(ref _HardSpTranProcNumb, "@HardSpTranProcNumb"); - } - } + // replace spaces with hard spaces in procedure number + private LazyLoad _HardSpTranProcNumb; + public bool HardSpTranProcNumb => LazyLoad(ref _HardSpTranProcNumb, "@HardSpTranProcNumb"); - // replaces the frist occurence of a space to a hard space - private LazyLoad _XchngTranSpForHard; - public bool XchngTranSpForHard - { - get - { - return LazyLoad(ref _XchngTranSpForHard, "@XchngTranSpForHard"); - } - } + // replaces the frist occurence of a space to a hard space + private LazyLoad _XchngTranSpForHard; + public bool XchngTranSpForHard => LazyLoad(ref _XchngTranSpForHard, "@XchngTranSpForHard"); - // Bold all of the transition text - private LazyLoad _BoldTransition; - public bool BoldTransition - { - get - { - return LazyLoad(ref _BoldTransition, "@BoldTransition"); - } - } + // Bold all of the transition text + private LazyLoad _BoldTransition; + public bool BoldTransition => LazyLoad(ref _BoldTransition, "@BoldTransition"); - // Bold the transition if it's not in a high level step - private LazyLoad _BoldTransitionExceptHLS; - public bool BoldTransitionExceptHLS - { - get - { - return LazyLoad(ref _BoldTransitionExceptHLS, "@BoldTransitionExceptHLS"); - } - } + // Bold the transition if it's not in a high level step + private LazyLoad _BoldTransitionExceptHLS; + public bool BoldTransitionExceptHLS => LazyLoad(ref _BoldTransitionExceptHLS, "@BoldTransitionExceptHLS"); - // B2017-269 Don't bold transition if a high level step or font for step is bold - private LazyLoad _BoldTransitionExceptBoldHLS; - public bool BoldTransitionExceptBoldHLS - { - get - { - return LazyLoad(ref _BoldTransitionExceptBoldHLS, "@BoldTransitionExceptBoldHLS"); - } - } + // B2017-269 Don't bold transition if a high level step or font for step is bold + private LazyLoad _BoldTransitionExceptBoldHLS; + public bool BoldTransitionExceptBoldHLS => LazyLoad(ref _BoldTransitionExceptBoldHLS, "@BoldTransitionExceptBoldHLS"); - // remove the "s" in "Procedure Steps" (section title) when transition references only one step - private LazyLoad _AdjustStepTransitionText; - public bool AdjustStepTransitionText - { - get - { - return LazyLoad(ref _AdjustStepTransitionText, "@AdjustStepTransitionText"); - } - } + // remove the "s" in "Procedure Steps" (section title) when transition references only one step + private LazyLoad _AdjustStepTransitionText; + public bool AdjustStepTransitionText => LazyLoad(ref _AdjustStepTransitionText, "@AdjustStepTransitionText"); - // remove the parent/child unit designators from the procedure number in the transition references - private LazyLoad _ProcLevelPCPC; - public bool ProcLevelPCPC // B2022-004: Remove Proc PC/PC token from transition text - { - get - { - return LazyLoad(ref _ProcLevelPCPC, "@ProcLevelPCPC"); - } - } + // remove the parent/child unit designators from the procedure number in the transition references + private LazyLoad _ProcLevelPCPC; + public bool ProcLevelPCPC // B2022-004: Remove Proc PC/PC token from transition text +=> LazyLoad(ref _ProcLevelPCPC, "@ProcLevelPCPC"); - // F2024-030 for Vogtle Units 3 & 4, added KeepOnePCPCTag flag to keep one of the PC/PC tokens when editing - // keep one of the parent/child unit designators in the transition reference - private LazyLoad _KeepOnePCPCTag; - public bool KeepOnePCPCTag - { - get - { - return LazyLoad(ref _KeepOnePCPCTag, "@KeepOnePCPCTag"); - } - } - } + // F2024-030 for Vogtle Units 3 & 4, added KeepOnePCPCTag flag to keep one of the PC/PC tokens when editing + // keep one of the parent/child unit designators in the transition reference + private LazyLoad _KeepOnePCPCTag; + public bool KeepOnePCPCTag => LazyLoad(ref _KeepOnePCPCTag, "@KeepOnePCPCTag"); + } #endregion TransData #region TransType [TypeConverter(typeof(ExpandableObjectConverter))] @@ -6612,77 +4068,36 @@ public StepData Equation // equation has a parent of embedded object. // allows us to re-define a default transition (from BASE format) and create new transition types private LazyLoad _Index; - public int? Index - { - get - { - return LazyLoad(ref _Index, "@Index"); - } - } + public int? Index => LazyLoad(ref _Index, "@Index"); - // Holdover from 16bit, used to define whether transitions are range (types 2 & 3). - // This is used in the logic for transitions with page numbers. This gets defined as "Type" in the code for the transition class. - // NOTE: the TransType you see in the code is actually the index into the list of transition definitions for given format. - private LazyLoad _Type; - public int? Type - { - get - { - return LazyLoad(ref _Type, "@TransType"); - } - } + // Holdover from 16bit, used to define whether transitions are range (types 2 & 3). + // This is used in the logic for transitions with page numbers. This gets defined as "Type" in the code for the transition class. + // NOTE: the TransType you see in the code is actually the index into the list of transition definitions for given format. + private LazyLoad _Type; + public int? Type => LazyLoad(ref _Type, "@TransType"); - // defines the contents that including in a Transition type. - private LazyLoad _TransFormat; - public string TransFormat - { - get - { - return LazyLoad(ref _TransFormat, "@TransFormat"); - } - } + // defines the contents that including in a Transition type. + private LazyLoad _TransFormat; + public string TransFormat => LazyLoad(ref _TransFormat, "@TransFormat"); - // defines what procedure information is selectable in the User Interface used to select a transition type to insert in the procedure text - private LazyLoad _TransUI; - public E_TransUI? TransUI - { - get - { - return LazyLoad(ref _TransUI, "@TransUI"); - } - } + // defines what procedure information is selectable in the User Interface used to select a transition type to insert in the procedure text + private LazyLoad _TransUI; + public E_TransUI? TransUI => LazyLoad(ref _TransUI, "@TransUI"); - // defines what is shown in list of transition types, on the User Interface used to select a transition type to insert in the procedure text - private LazyLoad _TransMenu; - public string TransMenu - { - get - { - return LazyLoad(ref _TransMenu, "@TransMenu"); - } - } + // defines what is shown in list of transition types, on the User Interface used to select a transition type to insert in the procedure text + private LazyLoad _TransMenu; + public string TransMenu => LazyLoad(ref _TransMenu, "@TransMenu"); - //B2019-072: For AEP, use PSI & SI for outside transition text. - // ex: UnitProcSetString ="{PSI:UNITCOM}-{SI:SETNAME}-{PSI:SETID|4023}-" will look for UNITCOM in - // the Procedure Specific Information, then SETNAME in the Set Specific Information (working draft), - // then the SETID in the Procedure Specific Information (or use 4023) if nothing is entered - private LazyLoad _UnitProcSetString; - public string UnitProcSetString - { - get - { - return LazyLoad(ref _UnitProcSetString, "@UnitProcSetString"); - } - } - public override string GetPDDisplayName() - { return string.Format("[{0}] - Type {1}", Index, Type); } - public override string GetPDCategory() - { return "Transition Type Data"; } - public override string ToString() - { - return string.Format("{0} - {1}", TransFormat, TransMenu); - } - } + //B2019-072: For AEP, use PSI & SI for outside transition text. + // ex: UnitProcSetString ="{PSI:UNITCOM}-{SI:SETNAME}-{PSI:SETID|4023}-" will look for UNITCOM in + // the Procedure Specific Information, then SETNAME in the Set Specific Information (working draft), + // then the SETID in the Procedure Specific Information (or use 4023) if nothing is entered + private LazyLoad _UnitProcSetString; + public string UnitProcSetString => LazyLoad(ref _UnitProcSetString, "@UnitProcSetString"); + public override string GetPDDisplayName() => string.Format("[{0}] - Type {1}", Index, Type); + public override string GetPDCategory() => "Transition Type Data"; + public override string ToString() => string.Format("{0} - {1}", TransFormat, TransMenu); + } #endregion TransType #region TransTypeList [TypeConverter(typeof(vlnIndexedListConverter))] @@ -6711,135 +4126,59 @@ public StepData Equation // equation has a parent of embedded object. //In a sequence of RO values, the unit appears with every value //(e.g., "25 gpm and 30 gpm" vs. "25 and 30 gpm") private LazyLoad _AllUnits; - public bool AllUnits - { - get - { - return LazyLoad(ref _AllUnits, "@AllUnits"); - } - } + public bool AllUnits => LazyLoad(ref _AllUnits, "@AllUnits"); - // If a R0 follows a "- " then it will be uppercased, THE "- " can be anywere in the text before the RO value - private LazyLoad _UpRoAftrDash; - public bool UpRoAftrDash - { - get - { - return LazyLoad(ref _UpRoAftrDash, "@UpRoAftrDash"); - } - } + // If a R0 follows a "- " then it will be uppercased, THE "- " can be anywere in the text before the RO value + private LazyLoad _UpRoAftrDash; + public bool UpRoAftrDash => LazyLoad(ref _UpRoAftrDash, "@UpRoAftrDash"); - // Put in for Wolf Creek, where the "- " should be right before the link for the RO to be uppercased. - private LazyLoad _UpRoImmAftrDashSpace; - public bool UpRoImmAftrDashSpace - { - get - { - return LazyLoad(ref _UpRoImmAftrDashSpace, "@UpRoImmAftrDashSpace"); - } - } + // Put in for Wolf Creek, where the "- " should be right before the link for the RO to be uppercased. + private LazyLoad _UpRoImmAftrDashSpace; + public bool UpRoImmAftrDashSpace => LazyLoad(ref _UpRoImmAftrDashSpace, "@UpRoImmAftrDashSpace"); - // Always uppercase the RO value units (PSI, GPM, etc.) - private LazyLoad _UpcaseAllRoUnits; - public bool UpcaseAllRoUnits - { - get - { - return LazyLoad(ref _UpcaseAllRoUnits, "@UpcaseAllRoUnits"); - } - } + // Always uppercase the RO value units (PSI, GPM, etc.) + private LazyLoad _UpcaseAllRoUnits; + public bool UpcaseAllRoUnits => LazyLoad(ref _UpcaseAllRoUnits, "@UpcaseAllRoUnits"); - // Forces the units for a RO to be uppercased for high level steps - private LazyLoad _CapHighRo; - public bool CapHighRo - { - get - { - return LazyLoad(ref _CapHighRo, "@CapHighRo"); - } - } + // Forces the units for a RO to be uppercased for high level steps + private LazyLoad _CapHighRo; + public bool CapHighRo => LazyLoad(ref _CapHighRo, "@CapHighRo"); - // uppercase ROs anywhere if no lower case text follows and an upper case letter immediately precedes the RO. - private LazyLoad _CapRoIfLastLower; - public bool CapRoIfLastLower - { - get - { - return LazyLoad(ref _CapRoIfLastLower, "@CapRoIfLastLower"); - } - } + // uppercase ROs anywhere if no lower case text follows and an upper case letter immediately precedes the RO. + private LazyLoad _CapRoIfLastLower; + public bool CapRoIfLastLower => LazyLoad(ref _CapRoIfLastLower, "@CapRoIfLastLower"); - // uppercase the RO, if it is a Setpoint type of RO, anywhere if no lower case text follows and an upper case letter immediately precedes the RO. - private LazyLoad _CapSPIfLastLower; - public bool CapSPIfLastLower - { - get - { - return LazyLoad(ref _CapSPIfLastLower, "@CapSPIfLastLower"); - } - } + // uppercase the RO, if it is a Setpoint type of RO, anywhere if no lower case text follows and an upper case letter immediately precedes the RO. + private LazyLoad _CapSPIfLastLower; + public bool CapSPIfLastLower => LazyLoad(ref _CapSPIfLastLower, "@CapSPIfLastLower"); - // Uppercase the RO Unit if the previous letter is uppercase - private LazyLoad _UpRoIfPrevUpper; - public bool UpRoIfPrevUpper - { - get - { - return LazyLoad(ref _UpRoIfPrevUpper, "@UpRoIfPrevUpper"); - } - } + // Uppercase the RO Unit if the previous letter is uppercase + private LazyLoad _UpRoIfPrevUpper; + public bool UpRoIfPrevUpper => LazyLoad(ref _UpRoIfPrevUpper, "@UpRoIfPrevUpper"); - // Underline all ROs, values and Units - private LazyLoad _UnderlineRo; - public bool UnderlineRo - { - get - { - return LazyLoad(ref _UnderlineRo, "@UnderlineRo"); - } - } + // Underline all ROs, values and Units + private LazyLoad _UnderlineRo; + public bool UnderlineRo => LazyLoad(ref _UnderlineRo, "@UnderlineRo"); - // Cap only the first letters of the units in a high level RO - // used in FLP (Turkey Point) format - private LazyLoad _CapFirstLetterInHighRO; - public bool CapFirstLetterInHighRO - { - get - { - return LazyLoad(ref _CapFirstLetterInHighRO, "@CapFirstLetterInHighRO"); - } - } + // Cap only the first letters of the units in a high level RO + // used in FLP (Turkey Point) format + private LazyLoad _CapFirstLetterInHighRO; + public bool CapFirstLetterInHighRO => LazyLoad(ref _CapFirstLetterInHighRO, "@CapFirstLetterInHighRO"); - // put in for Byron and Braidwood which has RO values containing non-PROMS procedure references as ROs. - // need to replace the unicode dash (\u8209?) with the dash character before the RO is resolved in order - // to retain the the upper and lower case lettering of the procedure number in the RO value (B2019-171) - private LazyLoad _DoSpaceDashBeforeROResolve; - public bool DoSpaceDashBeforeROResolve - { - get - { - return LazyLoad(ref _DoSpaceDashBeforeROResolve, "@DoSpaceDashBeforeROResolve"); - } - } - } + // put in for Byron and Braidwood which has RO values containing non-PROMS procedure references as ROs. + // need to replace the unicode dash (\u8209?) with the dash character before the RO is resolved in order + // to retain the the upper and lower case lettering of the procedure number in the RO value (B2019-171) + private LazyLoad _DoSpaceDashBeforeROResolve; + public bool DoSpaceDashBeforeROResolve => LazyLoad(ref _DoSpaceDashBeforeROResolve, "@DoSpaceDashBeforeROResolve"); + } #endregion RoData #endregion TransDataAll #region SupportClasses public class StepDataRetval { - private string _Name; - public string Name - { - get { return _Name; } - set { _Name = value; } - } - private int _Index; - public int Index - { - get { return _Index; } - set { _Index = value; } - } - public StepDataRetval(string name, int index) + public string Name { get; set; } + public int Index { get; set; } + public StepDataRetval(string name, int index) { Name = name; Index = index; diff --git a/PROMS/VEPROMS.CSLA.Library/Format/vlnFormat.cs b/PROMS/VEPROMS.CSLA.Library/Format/vlnFormat.cs index c7676e27..8748f16f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Format/vlnFormat.cs +++ b/PROMS/VEPROMS.CSLA.Library/Format/vlnFormat.cs @@ -12,47 +12,14 @@ namespace VEPROMS.CSLA.Library private static XmlElement mydocele; public vlnFormatDocument(IFormatOrFormatInfo myFormat) { - _MyFormat = myFormat; + MyFormat = myFormat; LoadXml(MyFormat.Data); - mydocele = this.DocumentElement; + mydocele = DocumentElement; } - private IFormatOrFormatInfo _MyFormat; - public IFormatOrFormatInfo MyFormat + + public IFormatOrFormatInfo MyFormat { get; set; } + public static XmlNode LookupSingleNode(XmlNode xmlNode, string path) { - get { return _MyFormat; } - set { _MyFormat = value; } - } - public static XmlNode LookupSingleNode(XmlNode xmlNode, string path) - { - //original: - //if (xmlNode == null) return null; - //XmlNode xn = xmlNode.SelectSingleNode(path); - //if (xn != null) return xn; - //if (xmlNode.Name == "Step") xn = LookupSingleStepNode(xmlNode, path); - //if (xn != null) return xn; - //if (path.StartsWith("Font")) return LookupSingleFontNode(xmlNode, path); - //return InheritLookup(xmlNode, path); -/* RHM 20090821 - - if (path.StartsWith("Font")) - { - XmlNode xn = null; - if (xmlNode != null) - { - xn = xmlNode.SelectSingleNode(path); - // RHM 2008-12-15 - Added logic to keep looking if a blank attribute is found - if (xn != null && xn is XmlAttribute && (xn as XmlAttribute).Value != "") return xn; - //if (xn != null) return xn; - } - else - { - xmlNode = LookupSingleNode(mydocele.FirstChild, "/PlantFormat/FormatData"); - } - if (path.Contains("Font")) Console.WriteLine("vlnFormatDocument.LookupSingleNode {0},{1}", xmlNode.Name == "Step" ? "Step." + xmlNode.Attributes["Type"].Value : xmlNode.Name, path); - return LookupSingleFontNode(xmlNode, path); - } - else - { - */ if (xmlNode == null) return null; XmlNode xn = xmlNode.SelectSingleNode(path); if (xmlNode.Name == "Box") return xn; // if box, don't do inheritance. @@ -72,7 +39,6 @@ namespace VEPROMS.CSLA.Library if (xn != null) return xn; if (path.StartsWith("Font")) return LookupSingleFontNode(xmlNode, path); // Then do Font Inheritance return InheritLookup(xmlNode, path, false); -// } } public static XmlNode LookupSingleFontNode(XmlNode xmlNode, string path) { @@ -108,29 +74,15 @@ namespace VEPROMS.CSLA.Library if (xmlNode == null) return null; XmlNode xn = xmlNode.SelectSingleNode(path); - XmlNode tmpNode = xmlNode; - XmlNode tmpNode2 = xmlNode; + XmlNode tmpNode2 = xmlNode; while (xn == null) //Walk-up the format tree to find a step node { - //if (path.Contains("Font")) Console.WriteLine("vlnFormatDocument.LookupSingleStepNode -> Loop {0},{1}", xmlNode.Name == "Step" ? "Step." + xmlNode.Attributes["Type"].Value : xmlNode.Name, path); - tmpNode = xmlNode; - // RHM 20090831 Try doing a lookup of the parent. If no parent, go back to the original and do an inheritance lookup - XmlAttribute attr = xmlNode.Attributes["ParentType"]; + //if (path.Contains("Font")) Console.WriteLine("vlnFormatDocument.LookupSingleStepNode -> Loop {0},{1}", xmlNode.Name == "Step" ? "Step." + xmlNode.Attributes["Type"].Value : xmlNode.Name, path); + // RHM 20090831 Try doing a lookup of the parent. If no parent, go back to the original and do an inheritance lookup + XmlAttribute attr = xmlNode.Attributes["ParentType"]; if (attr == null || attr.Value == string.Empty) // Cannot find ParentType so do an InheritanceLookup return InheritLookup(tmpNode2, path, true); - //return InheritLookup(xmlNode, path, false); xmlNode = xmlNode.ParentNode.SelectSingleNode(string.Format("Step[@Type='{0}']", xmlNode.Attributes["ParentType"].InnerText)); - // Based upon our current data - the following conditions are never met. - //if (xmlNode == null && path.StartsWith("Font")) - //{ - // //if (path.Contains("Font")) Console.WriteLine("vlnFormatDocument.LookupSingleStepNode -> Font {0},{1}", tmpNode.Name == "Step" ? "Step." + tmpNode.Attributes["Type"].Value : tmpNode.Name, path); - // return LookupSingleFontNode(tmpNode, path); - //} - //if (xmlNode == null) - //{ - // //if (path.Contains("Font")) Console.WriteLine("vlnFormatDocument.LookupSingleStepNode -> Font {0},{1}", tmpNode2.Name == "Step" ? "Step." + tmpNode2.Attributes["Type"].Value : tmpNode2.Name, path); - // return InheritLookup(tmpNode2, path, true); - //} xn = xmlNode.SelectSingleNode(path); } return xn; @@ -145,38 +97,20 @@ namespace VEPROMS.CSLA.Library } public static string Lookup(XmlNode xmlNode, string path) { - //if (xmlNode == null) return null; XmlNode xn = LookupSingleNode(xmlNode, path); - //if (xn == null) xn = InheritLookup(xmlNode, path); - if (xn == null) return null; - return xn.InnerText; - } - //public static string StepLookup(XmlNode xmlNode, string path) - //{ - // //if (xmlNode == null) return null; - // XmlNode xn = LookupSingleStepNode(xmlNode, path); - // //if (xn == null) xn = InheritLookup(xmlNode, path); - // if (xn == null) return null; - // return xn.InnerText; - //} - public static T EnumLookup(XmlNode xmlNode, string path) + return xn?.InnerText; + } + public static T EnumLookup(XmlNode xmlNode, string path) { string str = Lookup(xmlNode,path); - if (str == null) return default(T); - return (T)Enum.Parse(typeof(T), str); - } - public static int? IntLookup(XmlNode xmlNode, string path) + return str == null ? default : (T)Enum.Parse(typeof(T), str); + } + public static int? IntLookup(XmlNode xmlNode, string path) { - //if (xmlNode == null) return null; - //XmlNode xn = LookupSingleNode(xmlNode, path); - //if (xn == null) xn = InheritLookup(xmlNode, path); - //if (xn == null) return null; - //return int.Parse(xn.InnerText); string str = Lookup(xmlNode, path); - if (str == null) return null; - return int.Parse(str); - } - public static int SiblingCount(XmlNode xmlNode) + return str == null ? null : (int?)int.Parse(str); + } + public static int SiblingCount(XmlNode xmlNode) { int retval = 0; string nodeName = xmlNode.Name; @@ -189,7 +123,7 @@ namespace VEPROMS.CSLA.Library public static string Path(XmlNode xmlNode) { // Walk the path - string parentPath = (xmlNode.ParentNode == xmlNode.OwnerDocument ? "" : Path(xmlNode.ParentNode)); + string parentPath = xmlNode.ParentNode == xmlNode.OwnerDocument ? "" : Path(xmlNode.ParentNode); // Count Siblings with the Same Name int sibCount = SiblingCount(xmlNode); return string.Format("{0}/{1}[{2}]", parentPath, xmlNode.Name, sibCount); @@ -204,7 +138,7 @@ namespace VEPROMS.CSLA.Library string TransIndex = xmlNode.Attributes["Index"].Value; xPath = System.Text.RegularExpressions.Regex.Replace(xPath, @"\[[0-9]*\]$", @"[@Index='" + TransIndex + @"']"); } - vlnFormatDocument fd = (vlnFormatDocument)(xmlNode.OwnerDocument);//First Get the vlnFormatDocument - This also ties it to a FormatInfo object + vlnFormatDocument fd = (vlnFormatDocument)xmlNode.OwnerDocument;//First Get the vlnFormatDocument - This also ties it to a FormatInfo object while(fd.MyFormat.MyIParent != null) { fd = fd.MyFormat.MyIParent.PlantFormat.XmlDoc;// Get the parents vlnFormatDocument @@ -215,8 +149,8 @@ namespace VEPROMS.CSLA.Library else xp = fd.SelectSingleNode(xPath);// Get the related node if (xp != null) { - XmlNode xn = null; - if (stepLookup) + XmlNode xn; + if (stepLookup) { //if (path.Contains("Font")) Console.WriteLine("vlnFormatItem.SelectSingleNode {0},{1}", xp.Name == "Step" ? "Step." + xp.Attributes["Type"].Value : xp.Name, path); xn = LookupSingleStepNode(xp, path); @@ -233,7 +167,7 @@ namespace VEPROMS.CSLA.Library { if (xmlNode == null) return null;// No path to match string xPath = Path(xmlNode);// Build xPath from xmlNode - vlnFormatDocument fd = (vlnFormatDocument)(xmlNode.OwnerDocument);//First Get the vlnFormatDocument - This also ties it to a FormatInfo object + vlnFormatDocument fd = (vlnFormatDocument)xmlNode.OwnerDocument;//First Get the vlnFormatDocument - This also ties it to a FormatInfo object while (fd.MyFormat.MyIParent != null) { fd = fd.MyFormat.MyIParent.PlantFormat.XmlDoc;// Get the parents vlnFormatDocument @@ -256,100 +190,41 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(ExpandableObjectConverter))] public class vlnFormatItem { - public vlnFormatItem(XmlNode xmlNode) - { - _XmlNode = xmlNode; - } - public vlnFormatItem() { } - XmlNode _XmlNode; - internal XmlNode XmlNode - { - get { return _XmlNode; } - set { _XmlNode = value; } - } - private IFormatOrFormatInfo _MyFormat; + public vlnFormatItem(XmlNode xmlNode) => XmlNode = xmlNode; + public vlnFormatItem() { } + + internal XmlNode XmlNode { get; set; } + private IFormatOrFormatInfo _MyFormat; public IFormatOrFormatInfo MyFormat { get { if (_MyFormat == null) { - vlnFormatDocument doc = (XmlNode.OwnerDocument) as vlnFormatDocument; - if(doc != null) - _MyFormat = doc.MyFormat; - } + if (XmlNode.OwnerDocument is vlnFormatDocument doc) + _MyFormat = doc.MyFormat; + } return _MyFormat; } } - private IFormatOrFormatInfo _MyParentFormat; - public IFormatOrFormatInfo MyParentFormat + public IFormatOrFormatInfo MyParentFormat => MyFormat.MyIParent; + public virtual string GetPDDisplayName() => ToString(); + public virtual string GetPDName() => ToString(); + public virtual string GetPDDescription() => ToString(); + public virtual string GetPDCategory() => ToString(); + public XmlNodeList SelectNodes(string path) => vlnFormatDocument.LookupNodes(XmlNode, path); + public XmlNode SelectSingleNode(string path) { - get - { - return MyFormat.MyIParent; - } - } - public virtual string GetPDDisplayName() - { return ToString(); } - public virtual string GetPDName() - { return ToString(); } - public virtual string GetPDDescription() - { return ToString(); } - public virtual string GetPDCategory() - { return ToString(); } - public XmlNodeList SelectNodes(string path) - { - return vlnFormatDocument.LookupNodes(_XmlNode, path); - } - public XmlNode SelectSingleNode(string path) - { - //AdjustLookup(_XmlNode, path); //if(path.Contains("Font")) Console.WriteLine("vlnFormatItem.SelectSingleNode {0},{1}", _XmlNode.Name == "Step" ? "Step." + _XmlNode.Attributes["Type"].Value : _XmlNode.Name, path); - return vlnFormatDocument.LookupSingleNode(_XmlNode, path); + return vlnFormatDocument.LookupSingleNode(XmlNode, path); } - //public static string _LookUpNode; - //private static void AdjustLookup(XmlNode xmlNode,string path) - //{ - // if (xmlNode.Name == "Step") - // { - // XmlAttribute attr = xmlNode.Attributes["Type"]; - // if (attr != null) _LookUpNode = attr.Value; - // //Console.WriteLine("AdjustLookup Type = {0}/{1}", _LookUpNode, path); - // } - // else - // { - // //Console.WriteLine("AdjustLookup {0}", xmlNode.Name); - // } - //} - public XmlNode SelectSingleFontNode(string path) - { - return vlnFormatDocument.LookupSingleFontNode(_XmlNode, path); - } - public string Lookup(string path) - { - return vlnFormatDocument.Lookup(_XmlNode, path); - } - public string Lookup(string path, ref string local) - { - return (local != null? local : local = Lookup(path)); - } - //public string StepLookup(string path) - //{ - // return vlnFormatDocument.StepLookup(_XmlNode, path); - //} - public int? IntLookup(string path) - { - return vlnFormatDocument.IntLookup(_XmlNode, path); - } - public int? IntLookup(string path, ref int? local) - { - return (local != null ? local : local = IntLookup(path)); - } - public T EnumLookup(string path) - { - return vlnFormatDocument.EnumLookup(_XmlNode, path); - } - public bool LazyLoad(ref LazyLoad ll, string xPath) + public XmlNode SelectSingleFontNode(string path) => vlnFormatDocument.LookupSingleFontNode(XmlNode, path); + public string Lookup(string path) => vlnFormatDocument.Lookup(XmlNode, path); + public string Lookup(string path, ref string local) => local ?? (local = Lookup(path)); + public int? IntLookup(string path) => vlnFormatDocument.IntLookup(XmlNode, path); + public int? IntLookup(string path, ref int? local) => local != null ? local : local = IntLookup(path); + public T EnumLookup(string path) => vlnFormatDocument.EnumLookup(XmlNode, path); + public bool LazyLoad(ref LazyLoad ll, string xPath) { if (ll == null) { @@ -358,12 +233,9 @@ namespace VEPROMS.CSLA.Library } return ll.Value; } - protected static bool RetrieveBool(XmlNode xn) - { - return xn != null && xn.InnerText.ToUpper() == "TRUE"; - } - // a LaxyLoad that allows you to pass in the default setting - public bool LazyLoad(ref LazyLoad ll, string xPath, bool defaultReturn) + protected static bool RetrieveBool(XmlNode xn) => xn != null && xn.InnerText.ToUpper() == "TRUE"; + // a LazyLoad that allows you to pass in the default setting + public bool LazyLoad(ref LazyLoad ll, string xPath, bool defaultReturn) { if (ll == null) { @@ -372,12 +244,9 @@ namespace VEPROMS.CSLA.Library } return ll.Value; } - // if nothing is set for this node, then use the passed in default value - protected static bool RetrieveBool(XmlNode xn, bool defaultReturn) - { - return (xn != null) ? xn.InnerText.ToUpper() == "TRUE" : defaultReturn; - } - public string LazyLoad(ref LazyLoad ll, string xPath) + // if nothing is set for this node, then use the passed in default value + protected static bool RetrieveBool(XmlNode xn, bool defaultReturn) => (xn != null) ? xn.InnerText.ToUpper() == "TRUE" : defaultReturn; + public string LazyLoad(ref LazyLoad ll, string xPath) { if (ll == null) { @@ -386,16 +255,13 @@ namespace VEPROMS.CSLA.Library } return ll.Value; } - protected static string RetrieveString(XmlNode xn) - { - return xn != null ? xn.InnerText : null; - } - public string MyPath + protected static string RetrieveString(XmlNode xn) => xn?.InnerText; + public string MyPath { get { StringBuilder sb = new StringBuilder(); - XmlNode node = _XmlNode; + XmlNode node = XmlNode; string prefix = ""; while (node != null) { @@ -429,14 +295,13 @@ namespace VEPROMS.CSLA.Library int? value = null; if (xn != null) { - int iValue = 0; - if (!int.TryParse(xn.InnerText, out iValue)) - { - if (xn.InnerText == "") return null; - Console.WriteLine(string.Format("'{0}'\r\n'{1}'\r\n'{2}' could not be converted to int?", MyFormat.FullName, MyPath + "/" + xPath, xn.InnerText)); - throw (new Exception(string.Format("{0} = '{1}' could not be converted to int?", xPath, xn.InnerText))); - } - value = iValue; + if (!int.TryParse(xn.InnerText, out int iValue)) + { + if (xn.InnerText == "") return null; + Console.WriteLine(string.Format("'{0}'\r\n'{1}'\r\n'{2}' could not be converted to int?", MyFormat.FullName, MyPath + "/" + xPath, xn.InnerText)); + throw new Exception(string.Format("{0} = '{1}' could not be converted to int?", xPath, xn.InnerText)); + } + value = iValue; } return value; } @@ -445,13 +310,12 @@ namespace VEPROMS.CSLA.Library float? value = null; if (xn != null) { - float fValue = 0; - if (!float.TryParse(xn.InnerText, out fValue)) - { - Console.WriteLine(string.Format("'{0}'\r\n'{1}'\r\n'{2}' could not be converted to float?", MyFormat.FullName, MyPath + "/" + xPath, xn.InnerText)); - throw (new Exception(string.Format("{0} = '{1}' could not be converted to float?", xPath, xn.InnerText))); - } - value = fValue; + if (!float.TryParse(xn.InnerText, out float fValue)) + { + Console.WriteLine(string.Format("'{0}'\r\n'{1}'\r\n'{2}' could not be converted to float?", MyFormat.FullName, MyPath + "/" + xPath, xn.InnerText)); + throw new Exception(string.Format("{0} = '{1}' could not be converted to float?", xPath, xn.InnerText)); + } + value = fValue; } return value; } @@ -460,9 +324,8 @@ namespace VEPROMS.CSLA.Library { if (ll == null) { - XmlNode xn = this._XmlNode; - xn = SelectSingleNode(xPath); - if (xn == null) + XmlNode xn = SelectSingleNode(xPath); + if (xn == null) ll = new LazyLoad(null); else if (xn.Value == "")// No value specified - Use zero value if it is defined - GetName returns a null if it is not defined ll = new LazyLoad>(Enum.GetName(typeof(T), 0) != null ? (Nullable) Enum.Parse(typeof(T), "0") : null); @@ -497,17 +360,10 @@ namespace VEPROMS.CSLA.Library #region LazyLoad public class LazyLoad { - public LazyLoad(T value) - { - _Value = value; - } - private T _Value; - public T Value - { - get { return _Value; } - set { _Value = value; } - } - } + public LazyLoad(T value) => Value = value; + + public T Value { get; set; } + } #endregion #region vlnFormatList, new() public class vlnFormatList : List, ICustomTypeDescriptor @@ -522,9 +378,11 @@ namespace VEPROMS.CSLA.Library _XmlNodeList = value; foreach (XmlNode xn in _XmlNodeList) { - T tt = new T(); - tt.XmlNode = xn; - Add(tt); + T tt = new T + { + XmlNode = xn + }; + Add(tt); } } } @@ -546,7 +404,7 @@ namespace VEPROMS.CSLA.Library XmlNode node = _XmlNodeList[0]; // Get the first node in a list vlnFormatDocument doc = null; if (node != null) - doc = (node.OwnerDocument) as vlnFormatDocument; // Get the owner document as a vlnFormatDocument + doc = node.OwnerDocument as vlnFormatDocument; // Get the owner document as a vlnFormatDocument if (doc != null) _MyFormat = doc.MyFormat; // Get the Format associated with the vlnFormatDocument } @@ -557,36 +415,24 @@ namespace VEPROMS.CSLA.Library _MyFormat = value; } } - #region ICustomTypeDescriptor - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - public virtual PropertyDescriptorCollection GetProperties() + #region ICustomTypeDescriptor + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + public virtual PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); - // Iterate the list - int i = 0; - for (i = 0; i < this.Count; i++) + // Iterate the list + for (int i = 0; i < Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection pds.Add(new vlnPropertyDescriptor, T>(this, i)); @@ -601,13 +447,10 @@ namespace VEPROMS.CSLA.Library public class vlnIndexedFormatList : vlnFormatList, ICustomTypeDescriptor where T : vlnFormatItem,IVlnIndexedFormatItem, new() { - public vlnIndexedFormatList(XmlNodeList xmlNodeList,IFormatOrFormatInfo myFormat) : base(xmlNodeList) - { - MyFormat = myFormat; - } - public vlnIndexedFormatList() : base() { } - public virtual vlnIndexedFormatList InheritedList { get { return null; } } - public new T this[int index] + public vlnIndexedFormatList(XmlNodeList xmlNodeList, IFormatOrFormatInfo myFormat) : base(xmlNodeList) => MyFormat = myFormat; + public vlnIndexedFormatList() : base() { } + public virtual vlnIndexedFormatList InheritedList => null; + public new T this[int index] { get { @@ -620,8 +463,6 @@ namespace VEPROMS.CSLA.Library if (ttlParent != null) return ttlParent[index]; return null; - // None found - Can I find it in another format? - return null; } } public int MaxIndex @@ -657,36 +498,25 @@ namespace VEPROMS.CSLA.Library return max; } } - #region ICustomTypeDescriptor - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) + #region ICustomTypeDescriptor + public new string GetClassName() => TypeDescriptor.GetClassName(this, true); + public new AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public new string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public new TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public new EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public new PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public new object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public new EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - public virtual PropertyDescriptorCollection GetProperties() + public new EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public new object GetPropertyOwner(PropertyDescriptor pd) => this; + public new PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + public new virtual PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - int i = 0; - for (i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection pds.Add(new vlnPropertyDescriptor, T>(this, i)); @@ -701,14 +531,11 @@ namespace VEPROMS.CSLA.Library public class vlnNamedFormatList : vlnFormatList, ICustomTypeDescriptor where T : vlnFormatItem, IVlnNamedFormatItem, new() { - public vlnNamedFormatList(XmlNodeList xmlNodeList, IFormatOrFormatInfo myFormat) - : base(xmlNodeList) - { - MyFormat = myFormat; - } - public vlnNamedFormatList() : base() { } - public virtual vlnNamedFormatList InheritedList { get { return null; } } - public new T this[string name] + public vlnNamedFormatList(XmlNodeList xmlNodeList, IFormatOrFormatInfo myFormat) + : base(xmlNodeList) => MyFormat = myFormat; + public vlnNamedFormatList() : base() { } + public virtual vlnNamedFormatList InheritedList => null; + public T this[string name] { get { @@ -721,8 +548,6 @@ namespace VEPROMS.CSLA.Library if (ttlParent != null) return ttlParent[name]; return null; - // None found - Can I find it in another format? - return null; } } public new T this[int index] @@ -735,47 +560,27 @@ namespace VEPROMS.CSLA.Library if (ttlParent != null) return ttlParent[index]; return null; - // None found - Can I find it in another format? - return null; } } - public new int Count - { - get - { - return base.Count; - } - } - #region ICustomTypeDescriptor - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - public virtual PropertyDescriptorCollection GetProperties() + public new int Count => base.Count; + #region ICustomTypeDescriptor + public new string GetClassName() => TypeDescriptor.GetClassName(this, true); + public new AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public new string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public new TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public new EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public new PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public new object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public new EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public new EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public new object GetPropertyOwner(PropertyDescriptor pd) => this; + public new PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + public new virtual PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - int i = 0; - for (i = 0; i < this.Count; i++) + for (int i = 0; i < Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection pds.Add(new vlnPropertyDescriptor, T>(this, i)); @@ -793,16 +598,16 @@ namespace VEPROMS.CSLA.Library { private string Plural(string name) { - if (name.EndsWith("y")) return name.Substring(0, name.Length - 1) + "ies"; - if (name.EndsWith("ss")) return name + "es"; - else return name + "s"; + if (name.EndsWith("y")) return $"{name.Substring(0, name.Length - 1)}ies"; + if (name.EndsWith("ss")) return $"{name}es"; + else return $"{name}s"; } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is T) + if (destType == typeof(string) && value is T vart) { // Return department and department role separated by comma. - return ((T)value).Count.ToString() + " " + (((T)value).Count == 1 ? typeof(C).Name : Plural(typeof(C).Name)); + return $"{vart.Count} {(vart.Count == 1 ? typeof(C).Name : Plural(typeof(C).Name))}"; } return base.ConvertTo(context, culture, value, destType); } @@ -815,17 +620,16 @@ namespace VEPROMS.CSLA.Library { private string Plural(string name) { - if (name.EndsWith("y")) return name.Substring(0, name.Length - 1) + "ies"; - if (name.EndsWith("ss")) return name + "es"; - if (name.EndsWith("x")) return name + "es"; - else return name + "s"; - } + if (name.EndsWith("y")) return $"{name.Substring(0, name.Length - 1)}ies"; + if (name.EndsWith("ss")) return $"{name}es"; + return name.EndsWith("x") ? $"{name}es" : $"{name}s"; + } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is T) + if (destType == typeof(string) && value is T vart) { // Return department and department role separated by comma. - return ((T)value).MaxIndex.ToString() + " " + (((T)value).MaxIndex == 1 ? typeof(C).Name : Plural(typeof(C).Name)); + return $"{vart.MaxIndex} {(vart.MaxIndex == 1 ? typeof(C).Name : Plural(typeof(C).Name))}"; } return base.ConvertTo(context, culture, value, destType); } @@ -837,38 +641,23 @@ namespace VEPROMS.CSLA.Library where C : vlnFormatItem, new() { protected C _Item = null; - public vlnPropertyDescriptor(T itemList, int index) - : base("#" + index.ToString(), null) - { - _Item = itemList[index]; - } - public override bool CanResetValue(object component) - { return true; } - public override Type ComponentType - { get { return _Item.GetType(); } } - public override object GetValue(object component) - { return _Item; } - public override bool IsReadOnly - { get { return true; } } - public override Type PropertyType - { get { return _Item.GetType(); } } - public override void ResetValue(object component) + public vlnPropertyDescriptor(T itemList, int index) + : base("#" + index.ToString(), null) => _Item = itemList[index]; + public override bool CanResetValue(object component) => true; + public override Type ComponentType => _Item.GetType(); + public override object GetValue(object component) => _Item; + public override bool IsReadOnly => true; + public override Type PropertyType => _Item.GetType(); + public override void ResetValue(object component) { ;} - public override bool ShouldSerializeValue(object component) - { return true; } - public override void SetValue(object component, object value) + public override bool ShouldSerializeValue(object component) => true; + public override void SetValue(object component, object value) { /*_Item = value*/;} - //public override AttributeCollection Attributes - //{ get { return new AttributeCollection(null); } } - public override string DisplayName - { get { return _Item.GetPDDisplayName(); } } - public override string Description - { get { return _Item.GetPDDescription(); } } - public override string Name - { get { return _Item.GetPDName(); } } - public override string Category - { get { return _Item.GetPDCategory(); } } - } // Class + public override string DisplayName => _Item.GetPDDisplayName(); + public override string Description => _Item.GetPDDescription(); + public override string Name => _Item.GetPDName(); + public override string Category => _Item.GetPDCategory(); + } // Class #endregion } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Annotation.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Annotation.cs index 951a0cb2..d4f4a5bc 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Annotation.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Annotation.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,11 +35,8 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshAnnotations.Add(this); } - private void ClearRefreshList() - { - _RefreshAnnotations = new List(); - } - private void BuildRefreshList() + private void ClearRefreshList() => _RefreshAnnotations = new List(); + private void BuildRefreshList() { ClearRefreshList(); AddToRefreshList(_RefreshAnnotations); @@ -56,9 +51,10 @@ namespace VEPROMS.CSLA.Library } ClearRefreshList(); } - #endregion - #region Collection - private static List _CacheList = new List(); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(Annotation annotation) { if (!_CacheList.Contains(annotation)) _CacheList.Add(annotation); // In AddToCache @@ -67,7 +63,8 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(annotation)) _CacheList.Remove(annotation); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Annotation(s) from temporary _CacheList to _CacheByPrimaryKey @@ -92,16 +89,10 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private static int _nextAnnotationID = -1; - public static int NextAnnotationID - { - get { return _nextAnnotationID--; } - } - private int _AnnotationID; + public string ErrorMessage => _ErrorMessage; + private static int _nextAnnotationID = -1; + public static int NextAnnotationID => _nextAnnotationID--; + private int _AnnotationID; [System.ComponentModel.DataObjectField(true, true)] public int AnnotationID { @@ -280,40 +271,25 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyAnnotationType == null ? false : _MyAnnotationType.IsDirtyList(list)) || (_MyItem == null ? false : _MyItem.IsDirtyList(list)); + return base.IsDirty || (_MyAnnotationType != null && _MyAnnotationType.IsDirtyList(list)) || (_MyItem != null && _MyItem.IsDirtyList(list)); } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { if(list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyAnnotationType == null ? true : _MyAnnotationType.IsValidList(list)) && (_MyItem == null ? true : _MyItem.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyAnnotationType == null || _MyAnnotationType.IsValidList(list)) && (_MyItem == null || _MyItem.IsValidList(list)); } - // CSLATODO: Replace base Annotation.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Annotation - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check Annotation.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current Annotation - protected override object GetIdValue() - { - return MyAnnotationUnique; // Absolutely Unique ID - } - #endregion - #region ValidationRules - [NonSerialized] + // CSLATODO: Check Annotation.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current Annotation + protected override object GetIdValue() => MyAnnotationUnique; // Absolutely Unique ID + #endregion + #region ValidationRules + [NonSerialized] private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules { @@ -340,8 +316,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -362,16 +338,10 @@ namespace VEPROMS.CSLA.Library ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); - //ValidationRules.AddDependantProperty("x", "y"); _AnnotationExtension.AddValidationRules(ValidationRules); - // CSLATODO: Add other validation rules } - protected override void AddInstanceBusinessRules() - { - _AnnotationExtension.AddInstanceValidationRules(ValidationRules); - // CSLATODO: Add other validation rules - } - private static bool MyItemRequired(Annotation target, Csla.Validation.RuleArgs e) + protected override void AddInstanceBusinessRules() => _AnnotationExtension.AddInstanceValidationRules(ValidationRules); + private static bool MyItemRequired(Annotation target, Csla.Validation.RuleArgs e) { if (target._ItemID == 0 && target._MyItem == null) // Required field missing { @@ -389,98 +359,26 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AnnotationID, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(TypeID, ""); - //AuthorizationRules.AllowRead(RtfText, ""); - //AuthorizationRules.AllowRead(SearchText, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(TypeID, ""); - //AuthorizationRules.AllowWrite(RtfText, ""); - //AuthorizationRules.AllowWrite(SearchText, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - _AnnotationExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _AnnotationExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } private static int _AnnotationUnique = 0; - protected static int AnnotationUnique - { get { return ++_AnnotationUnique; } } - private int _MyAnnotationUnique = AnnotationUnique; - public int MyAnnotationUnique // Absolutely Unique ID - Editable - { get { return _MyAnnotationUnique; } } + protected static int AnnotationUnique => ++_AnnotationUnique; + private readonly int _MyAnnotationUnique = AnnotationUnique; + // Absolutely Unique ID - Editable + public int MyAnnotationUnique => _MyAnnotationUnique; + protected Annotation() {/* require use of factory methods */ AddToCache(this); } private bool _Disposed = false; - private static int _CountCreated = 0; + private static readonly 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; } } - ~Annotation() + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~Annotation() { _CountFinalized++; } @@ -504,8 +402,6 @@ namespace VEPROMS.CSLA.Library } public static Annotation New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Annotation"); try { return DataPortal.Create(); @@ -578,8 +474,6 @@ namespace VEPROMS.CSLA.Library } public static Annotation Get(int annotationID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Annotation"); try { Annotation tmp = GetCachedByPrimaryKey(annotationID); @@ -599,37 +493,29 @@ namespace VEPROMS.CSLA.Library { throw new DbCslaException("Error on Annotation.Get", ex); } - } - public static Annotation Get(SafeDataReader dr) - { - if (dr.Read()) return new Annotation(dr); - return null; - } - internal Annotation(SafeDataReader dr) - { - ReadData(dr); - } - public static void Delete(int annotationID) - { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); - try - { - DataPortal.Delete(new PKCriteria(annotationID)); - } - catch (Exception ex) - { - throw new DbCslaException("Error on Annotation.Delete", ex); - } - } + } + public static Annotation Get(SafeDataReader dr) + { + if (dr.Read()) return new Annotation(dr); + return null; + } + internal Annotation(SafeDataReader dr) + { + ReadData(dr); + } + public static void Delete(int annotationID) + { + try + { + DataPortal.Delete(new PKCriteria(annotationID)); + } + catch (Exception ex) + { + throw new DbCslaException("Error on Annotation.Delete", ex); + } + } public override Annotation Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Annotation"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Annotation"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Annotation"); try { BuildRefreshList(); @@ -650,14 +536,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _AnnotationID; - public int AnnotationID - { get { return _AnnotationID; } } - public PKCriteria(int annotationID) - { - _AnnotationID = annotationID; - } - } + private readonly int _AnnotationID; + public int AnnotationID => _AnnotationID; + public PKCriteria(int annotationID) => _AnnotationID = annotationID; + } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() @@ -728,7 +610,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Annotation.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -753,53 +635,61 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try - { - if (_MyAnnotationType != null) _MyAnnotationType.Update(); - if (_MyItem != null) _MyItem.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addAnnotation"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ItemID", ItemID); - cm.Parameters.AddWithValue("@TypeID", TypeID); - cm.Parameters.AddWithValue("@RtfText", _RtfText); - cm.Parameters.AddWithValue("@SearchText", _SearchText); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_AnnotationID = new SqlParameter("@newAnnotationID", SqlDbType.Int); - param_AnnotationID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AnnotationID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AnnotationID = (int)cm.Parameters["@newAnnotationID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - } - MarkOld(); - // update child objects - if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.SQLInsert", GetHashCode()); - } - catch (Exception ex) + { + _MyAnnotationType?.Update(); + _MyItem?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addAnnotation"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ItemID", ItemID); + cm.Parameters.AddWithValue("@TypeID", TypeID); + cm.Parameters.AddWithValue("@RtfText", _RtfText); + cm.Parameters.AddWithValue("@SearchText", _SearchText); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_AnnotationID = new SqlParameter("@newAnnotationID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AnnotationID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AnnotationID = (int)cm.Parameters["@newAnnotationID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } + } + + MarkOld(); + // update child objects + if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.SQLInsert", GetHashCode()); + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Annotation.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Annotation.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int annotationID, Item myItem, AnnotationType myAnnotationType, string rtfText, string searchText, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Add", 0); @@ -818,13 +708,17 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@Config", config); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); - // Output Calculated Columns - SqlParameter param_AnnotationID = new SqlParameter("@newAnnotationID", SqlDbType.Int); - param_AnnotationID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AnnotationID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_AnnotationID = new SqlParameter("@newAnnotationID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AnnotationID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -838,7 +732,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Annotation.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -861,47 +755,53 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.SQLUpdate", GetHashCode()); try - { - if (_MyAnnotationType != null) _MyAnnotationType.Update(); - if (_MyItem != null) _MyItem.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateAnnotation"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AnnotationID", _AnnotationID); - cm.Parameters.AddWithValue("@ItemID", ItemID); - cm.Parameters.AddWithValue("@TypeID", TypeID); - cm.Parameters.AddWithValue("@RtfText", _RtfText); - cm.Parameters.AddWithValue("@SearchText", _SearchText); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - } - } - MarkOld(); - // use the open connection to update child objects - } - catch (Exception ex) + { + _MyAnnotationType?.Update(); + _MyItem?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateAnnotation"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AnnotationID", _AnnotationID); + cm.Parameters.AddWithValue("@ItemID", ItemID); + cm.Parameters.AddWithValue("@TypeID", TypeID); + cm.Parameters.AddWithValue("@RtfText", _RtfText); + cm.Parameters.AddWithValue("@SearchText", _SearchText); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } + } + } + + MarkOld(); + // use the open connection to update child objects + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Annotation.SQLUpdate", ex); _ErrorMessage = ex.Message; @@ -910,18 +810,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, _MyAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); - else - _LastChanged = Annotation.Update(cn, ref _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); - MarkOld(); - } - } - [Transactional(TransactionalTypes.TransactionScope)] + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, _MyAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); + else + _LastChanged = Annotation.Update(cn, ref _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); + } + + MarkOld(); + } + } + public static byte[] Update(SqlConnection cn, ref int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Update", 0); @@ -942,10 +846,12 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -958,12 +864,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Annotation.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AnnotationID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Delete", GetHashCode()); @@ -988,7 +894,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Annotation.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int annotationID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Remove", 0); @@ -1029,24 +935,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _AnnotationID; + private readonly int _AnnotationID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int annotationID) - { - _AnnotationID = annotationID; - } - protected override void DataPortal_Execute() + public bool Exists => _exists; + public ExistsCommand(int annotationID) => _AnnotationID = annotationID; + protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1065,10 +965,10 @@ namespace VEPROMS.CSLA.Library } } } - #endregion - // Standard Default Code - #region extension - AnnotationExtension _AnnotationExtension = new AnnotationExtension(); + #endregion + // Standard Default Code + #region extension + readonly AnnotationExtension _AnnotationExtension = new AnnotationExtension(); [Serializable()] partial class AnnotationExtension : extensionBase { @@ -1076,17 +976,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] class extensionBase { - // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } - // Authorization Rules - public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) + // Default Values + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; + // Authorization Rules + public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } @@ -1113,57 +1007,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Annotation) + if (destType == typeof(string) && value is Annotation ann) { // Return the ToString value - return ((Annotation)value).ToString(); + return ann.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create AnnotationExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Annotation -// { -// partial class AnnotationExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAudit.cs index 83dc13c2..28928841 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -54,9 +52,10 @@ namespace VEPROMS.CSLA.Library } ClearRefreshList(); } - #endregion - #region Collection - private static List _CacheList = new List(); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(AnnotationAudit annotationAudit) { if (!_CacheList.Contains(annotationAudit)) _CacheList.Add(annotationAudit); // In AddToCache @@ -65,7 +64,8 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(annotationAudit)) _CacheList.Remove(annotationAudit); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move AnnotationAudit(s) from temporary _CacheList to _CacheByPrimaryKey @@ -90,16 +90,10 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } - private long _AuditID; + public string ErrorMessage => _ErrorMessage; + private static int _nextAuditID = -1; + public static int NextAuditID => _nextAuditID--; + private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID { @@ -275,43 +269,18 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base AnnotationAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AnnotationAudit - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check AnnotationAudit.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current AnnotationAudit - protected override object GetIdValue() - { - return MyAnnotationAuditUnique; // Absolutely Unique ID - } - #endregion - #region ValidationRules - [NonSerialized] + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + + // CSLATODO: Check AnnotationAudit.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current AnnotationAudit + protected override object GetIdValue() => MyAnnotationAuditUnique; // Absolutely Unique ID + #endregion + #region ValidationRules + [NonSerialized] private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules { @@ -336,8 +305,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -356,93 +325,15 @@ namespace VEPROMS.CSLA.Library ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 200)); - //ValidationRules.AddDependantProperty("x", "y"); _AnnotationAuditExtension.AddValidationRules(ValidationRules); - // CSLATODO: Add other validation rules - } - protected override void AddInstanceBusinessRules() - { - _AnnotationAuditExtension.AddInstanceValidationRules(ValidationRules); - // CSLATODO: Add other validation rules - } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(AnnotationID, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(TypeID, ""); - //AuthorizationRules.AllowRead(RtfText, ""); - //AuthorizationRules.AllowRead(SearchText, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(AnnotationID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(TypeID, ""); - //AuthorizationRules.AllowWrite(RtfText, ""); - //AuthorizationRules.AllowWrite(SearchText, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); - _AnnotationAuditExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _AnnotationAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } private static int _AnnotationAuditUnique = 0; - protected static int AnnotationAuditUnique - { get { return ++_AnnotationAuditUnique; } } - private int _MyAnnotationAuditUnique = AnnotationAuditUnique; - public int MyAnnotationAuditUnique // Absolutely Unique ID - Editable - { get { return _MyAnnotationAuditUnique; } } + protected static int AnnotationAuditUnique => ++_AnnotationAuditUnique; + private readonly int _MyAnnotationAuditUnique = AnnotationAuditUnique; + // Absolutely Unique ID - Editable + public int MyAnnotationAuditUnique => _MyAnnotationAuditUnique; protected AnnotationAudit() {/* require use of factory methods */ AddToCache(this); @@ -451,16 +342,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationAudit() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationAudit() { _CountFinalized++; } @@ -484,8 +371,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a AnnotationAudit"); try { return DataPortal.Create(); @@ -531,15 +416,13 @@ namespace VEPROMS.CSLA.Library tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { - tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; + tmp._ErrorMessage += $"\r\n\tFailure: {br.RuleName}"; } } return tmp; } public static AnnotationAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a AnnotationAudit"); try { AnnotationAudit tmp = GetCachedByPrimaryKey(auditID); @@ -559,20 +442,15 @@ namespace VEPROMS.CSLA.Library { throw new DbCslaException("Error on AnnotationAudit.Get", ex); } - } - public static AnnotationAudit Get(SafeDataReader dr) + } + public static AnnotationAudit Get(SafeDataReader dr) + { + if (dr.Read()) return new AnnotationAudit(dr); + return null; + } + internal AnnotationAudit(SafeDataReader dr) => ReadData(dr); + public static void Delete(long auditID) { - if (dr.Read()) return new AnnotationAudit(dr); - return null; - } - internal AnnotationAudit(SafeDataReader dr) - { - ReadData(dr); - } - public static void Delete(long auditID) - { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a AnnotationAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -584,12 +462,6 @@ namespace VEPROMS.CSLA.Library } public override AnnotationAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a AnnotationAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a AnnotationAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a AnnotationAudit"); try { BuildRefreshList(); @@ -609,14 +481,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; + } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() @@ -687,7 +555,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -712,49 +580,55 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addAnnotationAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@AnnotationID", _AnnotationID); - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@TypeID", _TypeID); - cm.Parameters.AddWithValue("@RtfText", _RtfText); - cm.Parameters.AddWithValue("@SearchText", _SearchText); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; - } - MarkOld(); - // update child objects - if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.SQLInsert", GetHashCode()); - } - catch (Exception ex) + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addAnnotationAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@AnnotationID", _AnnotationID); + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@TypeID", _TypeID); + cm.Parameters.AddWithValue("@RtfText", _RtfText); + cm.Parameters.AddWithValue("@SearchText", _SearchText); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } + } + + MarkOld(); + // update child objects + if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.SQLInsert", GetHashCode()); + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationAudit.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("AnnotationAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Add", 0); @@ -775,10 +649,12 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -792,7 +668,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -815,42 +691,46 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.SQLUpdate", GetHashCode()); try - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateAnnotationAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@AnnotationID", _AnnotationID); - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@TypeID", _TypeID); - cm.Parameters.AddWithValue("@RtfText", _RtfText); - cm.Parameters.AddWithValue("@SearchText", _SearchText); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - } - } - MarkOld(); - // use the open connection to update child objects - } - catch (Exception ex) + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateAnnotationAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@AnnotationID", _AnnotationID); + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@TypeID", _TypeID); + cm.Parameters.AddWithValue("@RtfText", _RtfText); + cm.Parameters.AddWithValue("@SearchText", _SearchText); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } + } + } + + MarkOld(); + // use the open connection to update child objects + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationAudit.SQLUpdate", ex); _ErrorMessage = ex.Message; @@ -859,18 +739,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - AnnotationAudit.Add(cn, ref _AuditID, _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, _DeleteStatus); - else - AnnotationAudit.Update(cn, ref _AuditID, _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, _DeleteStatus); - MarkOld(); - } - } - [Transactional(TransactionalTypes.TransactionScope)] + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + AnnotationAudit.Add(cn, ref _AuditID, _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, _DeleteStatus); + else + AnnotationAudit.Update(cn, ref _AuditID, _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, _DeleteStatus); + } + + MarkOld(); + } + } + public static void Update(SqlConnection cn, ref long auditID, int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Update", 0); @@ -905,12 +789,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Delete", GetHashCode()); @@ -935,7 +819,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Remove", 0); @@ -976,24 +860,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private long _AuditID; + private readonly long _AuditID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(long auditID) - { - _AuditID = auditID; - } - protected override void DataPortal_Execute() + public bool Exists => _exists; + public ExistsCommand(long auditID) => _AuditID = auditID; + protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1012,10 +890,10 @@ namespace VEPROMS.CSLA.Library } } } - #endregion - // Standard Default Code - #region extension - AnnotationAuditExtension _AnnotationAuditExtension = new AnnotationAuditExtension(); + #endregion + // Standard Default Code + #region extension + readonly AnnotationAuditExtension _AnnotationAuditExtension = new AnnotationAuditExtension(); [Serializable()] partial class AnnotationAuditExtension : extensionBase { @@ -1052,49 +930,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationAudit) + if (destType == typeof(string) && value is AnnotationAudit audit) { // Return the ToString value - return ((AnnotationAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create AnnotationAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class AnnotationAudit -// { -// partial class AnnotationAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfo.cs index 60dd29ae..8efdce6e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,15 +26,13 @@ namespace VEPROMS.CSLA.Library public partial class AnnotationAuditInfo : ReadOnlyBase, IDisposable { public event AnnotationAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } - #region Log4Net - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Collection - private static List _CacheList = new List(); + private void OnChange() => Changed?.Invoke(this); + #region Log4Net + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(AnnotationAuditInfo annotationAuditInfo) { if (!_CacheList.Contains(annotationAuditInfo)) _CacheList.Add(annotationAuditInfo); // In AddToCache @@ -45,7 +41,8 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(annotationAuditInfo)) _CacheList.Remove(annotationAuditInfo); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move AnnotationAuditInfo(s) from temporary _CacheList to _CacheByPrimaryKey @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - protected AnnotationAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } + public string ErrorMessage => _ErrorMessage; + protected AnnotationAudit _Editable; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -180,50 +164,33 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base AnnotationAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AnnotationAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check AnnotationAuditInfo.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current AnnotationAuditInfo - protected override object GetIdValue() - { - return MyAnnotationAuditInfoUnique; // Absolutely Unique ID - } - #endregion - #region Factory Methods + // CSLATODO: Check AnnotationAuditInfo.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current AnnotationAuditInfo + protected override object GetIdValue() => MyAnnotationAuditInfoUnique; // Absolutely Unique ID + #endregion + #region Factory Methods private static int _AnnotationAuditInfoUnique = 0; - private static int AnnotationAuditInfoUnique - { get { return ++_AnnotationAuditInfoUnique; } } - private int _MyAnnotationAuditInfoUnique = AnnotationAuditInfoUnique; - public int MyAnnotationAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyAnnotationAuditInfoUnique; } } + private static int AnnotationAuditInfoUnique => ++_AnnotationAuditInfoUnique; + private readonly int _MyAnnotationAuditInfoUnique = AnnotationAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyAnnotationAuditInfoUnique => _MyAnnotationAuditInfoUnique; protected AnnotationAuditInfo() {/* require use of factory methods */ AddToCache(this); } - private bool _Disposed = false; + 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; } } - ~AnnotationAuditInfo() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationAuditInfo() { _CountFinalized++; } @@ -267,8 +234,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a AnnotationAudit"); try { AnnotationAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -307,14 +272,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; + } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAuditInfo.ReadData", GetHashCode()); @@ -374,10 +335,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationAuditInfo.DataPortal_Fetch", ex); } } - #endregion - // Standard Refresh - #region extension - AnnotationAuditInfoExtension _AnnotationAuditInfoExtension = new AnnotationAuditInfoExtension(); + #endregion + // Standard Refresh + #region extension + readonly AnnotationAuditInfoExtension _AnnotationAuditInfoExtension = new AnnotationAuditInfoExtension(); [Serializable()] partial class AnnotationAuditInfoExtension : extensionBase { } [Serializable()] @@ -393,10 +354,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationAuditInfo) + if (destType == typeof(string) && value is AnnotationAuditInfo info) { // Return the ToString value - return ((AnnotationAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfoList.cs index a804a4fe..50da1e24 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (AnnotationAuditInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationAuditInfoList() { _CountFinalized++; } @@ -97,25 +90,6 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on AnnotationAuditInfoList.Get", ex); } } - /// - /// Reset the list of all AnnotationAuditInfo. - /// - public static void Reset() - { - _AnnotationAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static AnnotationAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on AnnotationAuditInfoList.Get", ex); - // } - //} private AnnotationAuditInfoList() { /* require use of factory methods */ } #endregion @@ -149,41 +123,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,8 +168,7 @@ namespace VEPROMS.CSLA.Library /// public partial class AnnotationAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private AnnotationAuditInfo Item { get { return (AnnotationAuditInfo)_Item; } } - public AnnotationAuditInfoListPropertyDescriptor(AnnotationAuditInfoList collection, int index) : base(collection, index) { ;} + public AnnotationAuditInfoListPropertyDescriptor(AnnotationAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion #region Converter @@ -214,10 +176,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationAuditInfoList) + if (destType == typeof(string) && value is AnnotationAuditInfoList list) { // Return department and department role separated by comma. - return ((AnnotationAuditInfoList)value).Items.Count.ToString() + " AnnotationAudits"; + return $"{list.Items.Count} AnnotationAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfo.cs index 203e1f5d..65e1d386 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,28 +26,21 @@ namespace VEPROMS.CSLA.Library public partial class AnnotationInfo : ReadOnlyBase, IDisposable { public static event AnnotationInfoEvent InfoChanged; - internal void OnInfoChanged(AnnotationInfo annotationInfo) - { - if (InfoChanged != null) - InfoChanged(this); - } - internal static void StaticOnInfoChanged() - { - if (InfoChanged != null) - InfoChanged(null); - } - public event AnnotationInfoEvent Changed; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping paramater for CSLA support")] + internal void OnInfoChanged(AnnotationInfo annotationInfo) => InfoChanged?.Invoke(this); + internal static void StaticOnInfoChanged() => InfoChanged?.Invoke(null); + public event AnnotationInfoEvent Changed; private void OnChange() { - if (Changed != null) - Changed(this); - OnInfoChanged(this); + Changed?.Invoke(this); + OnInfoChanged(this); } #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Collection - private static List _CacheList = new List(); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(AnnotationInfo annotationInfo) { if (!_CacheList.Contains(annotationInfo)) _CacheList.Add(annotationInfo); // In AddToCache @@ -58,7 +49,8 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(annotationInfo)) _CacheList.Remove(annotationInfo); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move AnnotationInfo(s) from temporary _CacheList to _CacheByPrimaryKey @@ -87,21 +79,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - protected Annotation _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } + public string ErrorMessage => _ErrorMessage; + protected Annotation _Editable; private int _AnnotationID; [System.ComponentModel.DataObjectField(true, true)] public int AnnotationID @@ -197,32 +176,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base AnnotationInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AnnotationInfo - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check AnnotationInfo.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current AnnotationInfo - protected override object GetIdValue() - { - return MyAnnotationInfoUnique; // Absolutely Unique ID - } - #endregion - #region Factory Methods - private static int _AnnotationInfoUnique = 0; - private static int AnnotationInfoUnique - { get { return ++_AnnotationInfoUnique; } } - private int _MyAnnotationInfoUnique = AnnotationInfoUnique; - public int MyAnnotationInfoUnique // Absolutely Unique ID - Info - { get { return _MyAnnotationInfoUnique; } } + // CSLATODO: Check AnnotationInfo.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current AnnotationInfo + protected override object GetIdValue() => MyAnnotationInfoUnique; // Absolutely Unique ID + #endregion + #region Factory Methods + private static int _AnnotationInfoUnique = 0; + private static int AnnotationInfoUnique => ++_AnnotationInfoUnique; + private readonly int _MyAnnotationInfoUnique = AnnotationInfoUnique; + // Absolutely Unique ID - Info + public int MyAnnotationInfoUnique => _MyAnnotationInfoUnique; protected AnnotationInfo() {/* require use of factory methods */ AddToCache(this); @@ -231,16 +197,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationInfo() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationInfo() { _CountFinalized++; } @@ -256,11 +218,8 @@ namespace VEPROMS.CSLA.Library if (listAnnotationInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AnnotationID.ToString()); // remove the list } - public virtual Annotation Get() - { - return _Editable = Annotation.Get(_AnnotationID); - } - public static void Refresh(Annotation tmp) + public virtual Annotation Get() => _Editable = Annotation.Get(_AnnotationID); + public static void Refresh(Annotation tmp) { string key = tmp.AnnotationID.ToString(); ConvertListToDictionary(); @@ -272,18 +231,18 @@ namespace VEPROMS.CSLA.Library { if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for old value + MyItem?.RefreshItemAnnotations(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for new value + MyItem?.RefreshItemAnnotations(); // Update List for new value if (_TypeID != tmp.TypeID) { - if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for old value + MyAnnotationType?.RefreshAnnotationTypeAnnotations(); // Update List for old value _TypeID = tmp.TypeID; // Update the value } _MyAnnotationType = null; // Reset list so that the next line gets a new list - if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for new value + MyAnnotationType?.RefreshAnnotationTypeAnnotations(); // Update List for new value _RtfText = tmp.RtfText; _SearchText = tmp.SearchText; _Config = tmp.Config; @@ -304,11 +263,11 @@ namespace VEPROMS.CSLA.Library { if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for old value + MyItem?.RefreshItemAnnotations(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemAnnotations(); // Update List for new value + MyItem?.RefreshItemAnnotations(); // Update List for new value _RtfText = tmp.RtfText; _SearchText = tmp.SearchText; _Config = tmp.Config; @@ -329,11 +288,11 @@ namespace VEPROMS.CSLA.Library { if (_TypeID != tmp.TypeID) { - if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for old value + MyAnnotationType?.RefreshAnnotationTypeAnnotations(); // Update List for old value _TypeID = tmp.TypeID; // Update the value } _MyAnnotationType = null; // Reset list so that the next line gets a new list - if (MyAnnotationType != null) MyAnnotationType.RefreshAnnotationTypeAnnotations(); // Update List for new value + MyAnnotationType?.RefreshAnnotationTypeAnnotations(); // Update List for new value _RtfText = tmp.RtfText; _SearchText = tmp.SearchText; _Config = tmp.Config; @@ -344,8 +303,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationInfo Get(int annotationID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Annotation"); try { AnnotationInfo tmp = GetCachedByPrimaryKey(annotationID); @@ -384,14 +341,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _AnnotationID; - public int AnnotationID - { get { return _AnnotationID; } } - public PKCriteria(int annotationID) - { - _AnnotationID = annotationID; - } - } + private readonly int _AnnotationID; + public int AnnotationID => _AnnotationID; + public PKCriteria(int annotationID) => _AnnotationID = annotationID; + } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationInfo.ReadData", GetHashCode()); @@ -449,10 +402,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationInfo.DataPortal_Fetch", ex); } } - #endregion - // Standard Refresh - #region extension - AnnotationInfoExtension _AnnotationInfoExtension = new AnnotationInfoExtension(); + #endregion + // Standard Refresh + #region extension + readonly AnnotationInfoExtension _AnnotationInfoExtension = new AnnotationInfoExtension(); [Serializable()] partial class AnnotationInfoExtension : extensionBase { } [Serializable()] @@ -468,10 +421,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationInfo) + if (destType == typeof(string) && value is AnnotationInfo info) { // Return the ToString value - return ((AnnotationInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfoList.cs index 9ac0b0da..d7d62d4f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (AnnotationInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationInfoList() { _CountFinalized++; } @@ -97,25 +90,6 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on AnnotationInfoList.Get", ex); } } - /// - /// Reset the list of all AnnotationInfo. - /// - public static void Reset() - { - _AnnotationInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static AnnotationInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on AnnotationInfoList.Get", ex); - // } - //} public static AnnotationInfoList GetByTypeID(int typeID) { try @@ -139,8 +113,8 @@ namespace VEPROMS.CSLA.Library tmp.AddEvents(); return tmp; } - catch (Exception ex) - { + catch (Exception) + { return new AnnotationInfoList();// B2017-246 If an exception return an empty list } } @@ -180,11 +154,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class TypeIDCriteria { - public TypeIDCriteria(int typeID) - { - _TypeID = typeID; - } - private int _TypeID; + public TypeIDCriteria(int typeID) => _TypeID = typeID; + private int _TypeID; public int TypeID { get { return _TypeID; } @@ -224,11 +195,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -265,41 +233,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -321,7 +278,6 @@ namespace VEPROMS.CSLA.Library /// public partial class AnnotationInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private AnnotationInfo Item { get { return (AnnotationInfo)_Item; } } public AnnotationInfoListPropertyDescriptor(AnnotationInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +286,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationInfoList) + if (destType == typeof(string) && value is AnnotationInfoList list) { // Return department and department role separated by comma. - return ((AnnotationInfoList)value).Items.Count.ToString() + " Annotations"; + return $"{list.Items.Count} Annotations"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationType.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationType.cs index 913453ef..f6f225b5 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationType.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationType.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -69,9 +67,10 @@ namespace VEPROMS.CSLA.Library } ClearRefreshList(); } - #endregion - #region Collection - private static List _CacheList = new List(); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(AnnotationType annotationType) { if (!_CacheList.Contains(annotationType)) _CacheList.Add(annotationType); // In AddToCache @@ -80,8 +79,10 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(annotationType)) _CacheList.Remove(annotationType); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); - private static Dictionary> _CacheByName = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByName = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move AnnotationType(s) from temporary _CacheList to _CacheByPrimaryKey @@ -115,16 +116,10 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private static int _nextTypeID = -1; - public static int NextTypeID - { - get { return _nextTypeID--; } - } - private int _TypeID; + public string ErrorMessage => _ErrorMessage; + private static int _nextTypeID = -1; + public static int NextTypeID => _nextTypeID--; + private int _TypeID; [System.ComponentModel.DataObjectField(true, true)] public int TypeID { @@ -262,10 +257,6 @@ namespace VEPROMS.CSLA.Library return _AnnotationTypeAnnotations; } } - public void Reset_AnnotationTypeAnnotations() - { - _AnnotationTypeAnnotationCount = -1; - } public override bool IsDirty { get @@ -280,40 +271,25 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_AnnotationTypeAnnotations == null ? false : _AnnotationTypeAnnotations.IsDirtyList(list)); + return base.IsDirty || (_AnnotationTypeAnnotations != null && _AnnotationTypeAnnotations.IsDirtyList(list)); } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { if(list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_AnnotationTypeAnnotations == null ? true : _AnnotationTypeAnnotations.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_AnnotationTypeAnnotations == null || _AnnotationTypeAnnotations.IsValidList(list)); } - // CSLATODO: Replace base AnnotationType.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AnnotationType - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check AnnotationType.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current AnnotationType - protected override object GetIdValue() - { - return MyAnnotationTypeUnique; // Absolutely Unique ID - } - #endregion - #region ValidationRules - [NonSerialized] + // CSLATODO: Check AnnotationType.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current AnnotationType + protected override object GetIdValue() => MyAnnotationTypeUnique; // Absolutely Unique ID + #endregion + #region ValidationRules + [NonSerialized] private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules { @@ -339,8 +315,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -362,92 +338,14 @@ namespace VEPROMS.CSLA.Library _AnnotationTypeExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - protected override void AddInstanceBusinessRules() - { - _AnnotationTypeExtension.AddInstanceValidationRules(ValidationRules); - // CSLATODO: Add other validation rules - } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(TypeID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - _AnnotationTypeExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _AnnotationTypeExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _AnnotationTypeAnnotationCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - #endregion - #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } - private static int _AnnotationTypeUnique = 0; - protected static int AnnotationTypeUnique - { get { return ++_AnnotationTypeUnique; } } - private int _MyAnnotationTypeUnique = AnnotationTypeUnique; - public int MyAnnotationTypeUnique // Absolutely Unique ID - Editable - { get { return _MyAnnotationTypeUnique; } } + #endregion + #region Factory Methods + public int CurrentEditLevel => EditLevel; + private static int _AnnotationTypeUnique = 0; + protected static int AnnotationTypeUnique => ++_AnnotationTypeUnique; + private readonly int _MyAnnotationTypeUnique = AnnotationTypeUnique; + // Absolutely Unique ID - Editable + public int MyAnnotationTypeUnique => _MyAnnotationTypeUnique; protected AnnotationType() {/* require use of factory methods */ AddToCache(this); @@ -456,16 +354,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationType() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationType() { _CountFinalized++; } @@ -501,8 +395,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationType New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a AnnotationType"); try { return DataPortal.Create(); @@ -568,8 +460,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationType Get(int typeID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a AnnotationType"); try { AnnotationType tmp = GetCachedByPrimaryKey(typeID); @@ -592,8 +482,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationType GetByName(string name) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a AnnotationType"); try { AnnotationType tmp = GetCachedByName(name); @@ -618,8 +506,6 @@ namespace VEPROMS.CSLA.Library // doesn't exist, create it (fix B2016-083) public static AnnotationType GetByNameOrCreate(string name) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a AnnotationType"); try { AnnotationType tmp = GetCachedByName(name); @@ -655,8 +541,6 @@ namespace VEPROMS.CSLA.Library } public static void Delete(int typeID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a AnnotationType"); try { DataPortal.Delete(new PKCriteria(typeID)); @@ -668,12 +552,6 @@ namespace VEPROMS.CSLA.Library } public override AnnotationType Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a AnnotationType"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a AnnotationType"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a AnnotationType"); try { BuildRefreshList(); @@ -693,25 +571,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _TypeID; - public int TypeID - { get { return _TypeID; } } - public PKCriteria(int typeID) - { - _TypeID = typeID; - } - } + private readonly int _TypeID; + public int TypeID => _TypeID; + public PKCriteria(int typeID) => _TypeID = typeID; + } [Serializable()] private class NameCriteria { - private string _Name; - public string Name - { get { return _Name; } } - public NameCriteria(string name) - { - _Name = name; - } - } + private readonly string _Name; + public string Name => _Name; + public NameCriteria(string name) => _Name = name; + } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() @@ -821,7 +691,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationType.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -846,49 +716,57 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addAnnotationType"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_TypeID = new SqlParameter("@newTypeID", SqlDbType.Int); - param_TypeID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_TypeID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _TypeID = (int)cm.Parameters["@newTypeID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - } - MarkOld(); - // update child objects - if (_AnnotationTypeAnnotations != null) _AnnotationTypeAnnotations.Update(this); - if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.SQLInsert", GetHashCode()); - } - catch (Exception ex) + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addAnnotationType"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_TypeID = new SqlParameter("@newTypeID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_TypeID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _TypeID = (int)cm.Parameters["@newTypeID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } + } + + MarkOld(); + // update child objects + _AnnotationTypeAnnotations?.Update(this); + if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.SQLInsert", GetHashCode()); + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationType.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("AnnotationType.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int typeID, string name, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Add", 0); @@ -904,13 +782,17 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@Config", config); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); - // Output Calculated Columns - SqlParameter param_TypeID = new SqlParameter("@newTypeID", SqlDbType.Int); - param_TypeID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_TypeID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_TypeID = new SqlParameter("@newTypeID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_TypeID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -924,7 +806,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationType.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -947,43 +829,49 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.SQLUpdate", GetHashCode()); try - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateAnnotationType"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@TypeID", _TypeID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - } - } - MarkOld(); - // use the open connection to update child objects - if (_AnnotationTypeAnnotations != null) _AnnotationTypeAnnotations.Update(this); - } - catch (Exception ex) + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateAnnotationType"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@TypeID", _TypeID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } + } + } + + MarkOld(); + // use the open connection to update child objects + _AnnotationTypeAnnotations?.Update(this); + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationType.SQLUpdate", ex); _ErrorMessage = ex.Message; @@ -992,19 +880,23 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = AnnotationType.Add(cn, ref _TypeID, _Name, _Config, _DTS, _UserID); - else - _LastChanged = AnnotationType.Update(cn, ref _TypeID, _Name, _Config, _DTS, _UserID, ref _LastChanged); - MarkOld(); - } - if (_AnnotationTypeAnnotations != null) _AnnotationTypeAnnotations.Update(this); + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = AnnotationType.Add(cn, ref _TypeID, _Name, _Config, _DTS, _UserID); + else + _LastChanged = AnnotationType.Update(cn, ref _TypeID, _Name, _Config, _DTS, _UserID, ref _LastChanged); + } + + MarkOld(); + } + _AnnotationTypeAnnotations?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int typeID, string name, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Update", 0); @@ -1022,10 +914,12 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -1038,12 +932,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationType.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_TypeID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_TypeID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Delete", GetHashCode()); @@ -1068,7 +959,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationType.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int typeID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Remove", 0); @@ -1109,24 +1000,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _TypeID; + private readonly int _TypeID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int typeID) - { - _TypeID = typeID; - } - protected override void DataPortal_Execute() + public bool Exists => _exists; + public ExistsCommand(int typeID) => _TypeID = typeID; + protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1145,10 +1030,10 @@ namespace VEPROMS.CSLA.Library } } } - #endregion - // Standard Default Code - #region extension - AnnotationTypeExtension _AnnotationTypeExtension = new AnnotationTypeExtension(); + #endregion + // Standard Default Code + #region extension + readonly AnnotationTypeExtension _AnnotationTypeExtension = new AnnotationTypeExtension(); [Serializable()] partial class AnnotationTypeExtension : extensionBase { @@ -1156,17 +1041,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] class extensionBase { - // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } - // Authorization Rules - public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) + // Default Values + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; + // Authorization Rules + public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } @@ -1193,57 +1072,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationType) + if (destType == typeof(string) && value is AnnotationType type) { // Return the ToString value - return ((AnnotationType)value).ToString(); + return type.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create AnnotationTypeExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class AnnotationType -// { -// partial class AnnotationTypeExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotation.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotation.cs index 82292ba7..e8b59720 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotation.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotation.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,12 +28,9 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private int _AnnotationID; + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + private int _AnnotationID; [System.ComponentModel.DataObjectField(true, true)] public int AnnotationID { @@ -219,25 +213,22 @@ namespace VEPROMS.CSLA.Library return _Item_UserID; } } - // CSLATODO: Check AnnotationTypeAnnotation.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current AnnotationTypeAnnotation - protected override object GetIdValue() - { - return MyAnnotationTypeAnnotationUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base AnnotationTypeAnnotation.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AnnotationTypeAnnotation - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty + // CSLATODO: Check AnnotationTypeAnnotation.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current AnnotationTypeAnnotation + protected override object GetIdValue() => MyAnnotationTypeAnnotationUnique; // Absolutely Unique ID + // CSLATODO: Replace base AnnotationTypeAnnotation.ToString function as necessary + /// + /// Overrides Base ToString + /// + /// A string representation of current AnnotationTypeAnnotation + //public override string ToString() + //{ + // return base.ToString(); + //} + public override bool IsDirty { get { @@ -251,18 +242,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyItem == null ? false : _MyItem.IsDirtyList(list)); + return base.IsDirty || (_MyItem != null && _MyItem.IsDirtyList(list)); } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { if(list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyItem == null ? true : _MyItem.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyItem == null || _MyItem.IsValidList(list)); } #endregion #region ValidationRules @@ -292,8 +280,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -324,81 +312,17 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AnnotationID, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowRead(RtfText, ""); - //AuthorizationRules.AllowWrite(RtfText, ""); - //AuthorizationRules.AllowRead(SearchText, ""); - //AuthorizationRules.AllowWrite(SearchText, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - #endregion - #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } - private static int _AnnotationTypeAnnotationUnique = 0; - private static int AnnotationTypeAnnotationUnique - { get { return ++_AnnotationTypeAnnotationUnique; } } - private int _MyAnnotationTypeAnnotationUnique = AnnotationTypeAnnotationUnique; - public int MyAnnotationTypeAnnotationUnique // Absolutely Unique ID - Editable FK - { get { return _MyAnnotationTypeAnnotationUnique; } } - internal static AnnotationTypeAnnotation New(Item myItem) - { - return new AnnotationTypeAnnotation(myItem); - } - internal static AnnotationTypeAnnotation Get(SafeDataReader dr) - { - return new AnnotationTypeAnnotation(dr); - } - public AnnotationTypeAnnotation() + #endregion + #region Factory Methods + public int CurrentEditLevel => EditLevel; + private static int _AnnotationTypeAnnotationUnique = 0; + private static int AnnotationTypeAnnotationUnique => ++_AnnotationTypeAnnotationUnique; + private readonly int _MyAnnotationTypeAnnotationUnique = AnnotationTypeAnnotationUnique; + // Absolutely Unique ID - Editable FK + public int MyAnnotationTypeAnnotationUnique => _MyAnnotationTypeAnnotationUnique; + internal static AnnotationTypeAnnotation New(Item myItem) => new AnnotationTypeAnnotation(myItem); + internal static AnnotationTypeAnnotation Get(SafeDataReader dr) => new AnnotationTypeAnnotation(dr); + public AnnotationTypeAnnotation() { MarkAsChild(); _AnnotationID = Annotation.NextAnnotationID; @@ -425,16 +349,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationTypeAnnotation() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationTypeAnnotation() { _CountFinalized++; } @@ -472,35 +392,48 @@ namespace VEPROMS.CSLA.Library MarkOld(); } internal void Insert(AnnotationType myAnnotationType) - { - // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, myAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); - MarkOld(); - } - internal void Update(AnnotationType myAnnotationType) - { - // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Annotation.Update(cn, ref _AnnotationID, _ItemID, myAnnotationType.TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); - MarkOld(); - } - internal void DeleteSelf(AnnotationType myAnnotationType) - { - // if we're not dirty then don't update the database - if (!this.IsDirty) return; - // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Annotation.Remove(cn, _AnnotationID); - MarkNew(); - } - #endregion - // Standard Default Code - #region extension - AnnotationTypeAnnotationExtension _AnnotationTypeAnnotationExtension = new AnnotationTypeAnnotationExtension(); + { + // if we're not dirty then don't update the database + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, myAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); + } + + MarkOld(); + } + internal void Update(AnnotationType myAnnotationType) + { + // if we're not dirty then don't update the database + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Annotation.Update(cn, ref _AnnotationID, _ItemID, myAnnotationType.TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); + } + + MarkOld(); + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping paramater for CSLA support")] + internal void DeleteSelf(AnnotationType myAnnotationType) + { + // if we're not dirty then don't update the database + if (!IsDirty) return; + // if we're new then don't update the database + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Annotation.Remove(cn, _AnnotationID); + } + + MarkNew(); + } + #endregion + // Standard Default Code + #region extension + readonly AnnotationTypeAnnotationExtension _AnnotationTypeAnnotationExtension = new AnnotationTypeAnnotationExtension(); [Serializable()] partial class AnnotationTypeAnnotationExtension : extensionBase { @@ -508,17 +441,11 @@ namespace VEPROMS.CSLA.Library [Serializable()] class extensionBase { - // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } - // Authorization Rules - public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) + // Default Values + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; + // Authorization Rules + public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } @@ -545,57 +472,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationTypeAnnotation) + if (destType == typeof(string) && value is AnnotationTypeAnnotation ann) { // Return the ToString value - return ((AnnotationTypeAnnotation)value).ToString(); + return ann.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create AnnotationTypeAnnotationExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class AnnotationTypeAnnotation -// { -// partial class AnnotationTypeAnnotationExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotations.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotations.cs index a067cb67..745fb60a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotations.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeAnnotations.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public AnnotationTypeAnnotation this[Annotation myAnnotation] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public AnnotationTypeAnnotation this[Annotation myAnnotation] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public AnnotationTypeAnnotation GetItem(Annotation myAnnotation) + public new System.Collections.Generic.IList Items => base.Items; + public AnnotationTypeAnnotation GetItem(Annotation myAnnotation) { foreach (AnnotationTypeAnnotation annotation in this) if (annotation.AnnotationID == myAnnotation.AnnotationID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public AnnotationTypeAnnotation Add(Item myItem) // One to Many { AnnotationTypeAnnotation annotation = AnnotationTypeAnnotation.New(myItem); - this.Add(annotation); + Add(annotation); return annotation; } public void Remove(Annotation myAnnotation) @@ -103,10 +95,6 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid - { - get { return IsValidList(new List()); } - } public bool IsValidList(List list) { // run through all the child objects @@ -137,20 +125,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return (hasBrokenRules?.BrokenRules); } } - #endregion - #region Factory Methods - internal static AnnotationTypeAnnotations New() - { - return new AnnotationTypeAnnotations(); - } - internal static AnnotationTypeAnnotations Get(SafeDataReader dr) - { - return new AnnotationTypeAnnotations(dr); - } - public static AnnotationTypeAnnotations GetByTypeID(int typeID) + #endregion + #region Factory Methods + internal static AnnotationTypeAnnotations New() => new AnnotationTypeAnnotations(); + internal static AnnotationTypeAnnotations Get(SafeDataReader dr) => new AnnotationTypeAnnotations(dr); + public static AnnotationTypeAnnotations GetByTypeID(int typeID) { try { @@ -161,11 +143,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on AnnotationTypeAnnotations.GetByTypeID", ex); } } - private AnnotationTypeAnnotations() - { - MarkAsChild(); - } - internal AnnotationTypeAnnotations(SafeDataReader dr) + private AnnotationTypeAnnotations() => MarkAsChild(); + internal AnnotationTypeAnnotations(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +153,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationTypeAnnotations() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationTypeAnnotations() { _CountFinalized++; } @@ -198,19 +173,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(AnnotationTypeAnnotation.Get(dr)); - this.RaiseListChangedEvents = true; + Add(AnnotationTypeAnnotation.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class TypeIDCriteria { - public TypeIDCriteria(int typeID) - { - _TypeID = typeID; - } - private int _TypeID; + public TypeIDCriteria(int typeID) => _TypeID = typeID; + private int _TypeID; public int TypeID { get { return _TypeID; } @@ -219,7 +191,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(TypeIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationTypeAnnotations.DataPortal_FetchTypeID", GetHashCode()); try { @@ -233,7 +205,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new AnnotationTypeAnnotation(dr)); + while (dr.Read()) Add(new AnnotationTypeAnnotation(dr)); } } } @@ -243,11 +215,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("AnnotationTypeAnnotations.DataPortal_FetchTypeID", ex); throw new DbCslaException("AnnotationTypeAnnotations.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(AnnotationType annotationType) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +238,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection AnnotationTypeAnnotationsPropertyDescriptor pd = new AnnotationTypeAnnotationsPropertyDescriptor(this, i); @@ -325,7 +286,6 @@ namespace VEPROMS.CSLA.Library /// public partial class AnnotationTypeAnnotationsPropertyDescriptor : vlnListPropertyDescriptor { - private AnnotationTypeAnnotation Item { get { return (AnnotationTypeAnnotation)_Item; } } public AnnotationTypeAnnotationsPropertyDescriptor(AnnotationTypeAnnotations collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +294,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationTypeAnnotations) + if (destType == typeof(string) && value is AnnotationTypeAnnotations ann) { // Return department and department role separated by comma. - return ((AnnotationTypeAnnotations)value).Items.Count.ToString() + " Annotations"; + return $"{ann.Items.Count} Annotations"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfo.cs index 9aeb05cc..cb98a9c5 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Linq; @@ -30,15 +28,13 @@ namespace VEPROMS.CSLA.Library public partial class AnnotationTypeInfo : ReadOnlyBase, IDisposable { public event AnnotationTypeInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } - #region Log4Net - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Collection - private static List _CacheList = new List(); + private void OnChange() => Changed?.Invoke(this); + #region Log4Net + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(AnnotationTypeInfo annotationTypeInfo) { if (!_CacheList.Contains(annotationTypeInfo)) _CacheList.Add(annotationTypeInfo); // In AddToCache @@ -47,7 +43,8 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(annotationTypeInfo)) _CacheList.Remove(annotationTypeInfo); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move AnnotationTypeInfo(s) from temporary _CacheList to _CacheByPrimaryKey @@ -76,21 +73,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - protected AnnotationType _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } + public string ErrorMessage => _ErrorMessage; + protected AnnotationType _Editable; private int _TypeID; [System.ComponentModel.DataObjectField(true, true)] public int TypeID @@ -186,32 +170,19 @@ namespace VEPROMS.CSLA.Library foreach (AnnotationTypeInfo tmp in _CacheByPrimaryKey[_TypeID.ToString()]) tmp._AnnotationTypeAnnotationCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base AnnotationTypeInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AnnotationTypeInfo - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check AnnotationTypeInfo.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current AnnotationTypeInfo - protected override object GetIdValue() - { - return MyAnnotationTypeInfoUnique; // Absolutely Unique ID - } - #endregion - #region Factory Methods - private static int _AnnotationTypeInfoUnique = 0; - private static int AnnotationTypeInfoUnique - { get { return ++_AnnotationTypeInfoUnique; } } - private int _MyAnnotationTypeInfoUnique = AnnotationTypeInfoUnique; - public int MyAnnotationTypeInfoUnique // Absolutely Unique ID - Info - { get { return _MyAnnotationTypeInfoUnique; } } + // CSLATODO: Check AnnotationTypeInfo.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current AnnotationTypeInfo + protected override object GetIdValue() => MyAnnotationTypeInfoUnique; // Absolutely Unique ID + #endregion + #region Factory Methods + private static int _AnnotationTypeInfoUnique = 0; + private static int AnnotationTypeInfoUnique => ++_AnnotationTypeInfoUnique; + private readonly int _MyAnnotationTypeInfoUnique = AnnotationTypeInfoUnique; + // Absolutely Unique ID - Info + public int MyAnnotationTypeInfoUnique => _MyAnnotationTypeInfoUnique; protected AnnotationTypeInfo() {/* require use of factory methods */ AddToCache(this); @@ -220,16 +191,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationTypeInfo() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationTypeInfo() { _CountFinalized++; } @@ -245,11 +212,8 @@ namespace VEPROMS.CSLA.Library if (listAnnotationTypeInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(TypeID.ToString()); // remove the list } - public virtual AnnotationType Get() - { - return _Editable = AnnotationType.Get(_TypeID); - } - public static void Refresh(AnnotationType tmp) + public virtual AnnotationType Get() => _Editable = AnnotationType.Get(_TypeID); + public static void Refresh(AnnotationType tmp) { string key = tmp.TypeID.ToString(); ConvertListToDictionary(); @@ -268,8 +232,6 @@ namespace VEPROMS.CSLA.Library } public static AnnotationTypeInfo Get(int typeID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a AnnotationType"); try { AnnotationTypeInfo tmp = GetCachedByPrimaryKey(typeID); @@ -308,14 +270,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _TypeID; - public int TypeID - { get { return _TypeID; } } - public PKCriteria(int typeID) - { - _TypeID = typeID; - } - } + private readonly int _TypeID; + public int TypeID => _TypeID; + public PKCriteria(int typeID) => _TypeID = typeID; + } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationTypeInfo.ReadData", GetHashCode()); @@ -373,10 +331,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("AnnotationTypeInfo.DataPortal_Fetch", ex); } } - #endregion - // Standard Refresh - #region extension - AnnotationTypeInfoExtension _AnnotationTypeInfoExtension = new AnnotationTypeInfoExtension(); + #endregion + // Standard Refresh + #region extension + readonly AnnotationTypeInfoExtension _AnnotationTypeInfoExtension = new AnnotationTypeInfoExtension(); [Serializable()] partial class AnnotationTypeInfoExtension : extensionBase { } [Serializable()] @@ -392,10 +350,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationTypeInfo) + if (destType == typeof(string) && value is AnnotationTypeInfo info) { // Return the ToString value - return ((AnnotationTypeInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfoList.cs index a7a13130..56787c25 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AnnotationTypeInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -27,19 +25,14 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(AnnotationTypeInfoListConverter))] public partial class AnnotationTypeInfoList : ReadOnlyListBase, ICustomTypeDescriptor, IDisposable { - public static event AnnotationTypeInfoListEvent ListChanged; - private static void OnListChanged() - { - if (ListChanged != null) - ListChanged(); - } - #region Log4Net - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + public new static event AnnotationTypeInfoListEvent ListChanged; + private static void OnListChanged() => ListChanged?.Invoke(); + #region Log4Net + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (AnnotationTypeInfo tmp in this) { @@ -58,16 +51,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AnnotationTypeInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AnnotationTypeInfoList() { _CountFinalized++; } @@ -105,26 +94,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on AnnotationTypeInfoList.Get", ex); } } - /// - /// Reset the list of all AnnotationTypeInfo. - /// - public static void Reset() - { - _AnnotationTypeInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static AnnotationTypeInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on AnnotationTypeInfoList.Get", ex); - // } - //} - private AnnotationTypeInfoList() + /// + /// Reset the list of all AnnotationTypeInfo. + /// + public static void Reset() => _AnnotationTypeInfoList = null; + private AnnotationTypeInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -157,41 +131,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -213,7 +176,6 @@ namespace VEPROMS.CSLA.Library /// public partial class AnnotationTypeInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private AnnotationTypeInfo Item { get { return (AnnotationTypeInfo)_Item; } } public AnnotationTypeInfoListPropertyDescriptor(AnnotationTypeInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -222,10 +184,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AnnotationTypeInfoList) + if (destType == typeof(string) && value is AnnotationTypeInfoList list) { // Return department and department role separated by comma. - return ((AnnotationTypeInfoList)value).Items.Count.ToString() + " AnnotationTypes"; + return list.Items.Count.ToString() + " AnnotationTypes"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Assignment.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Assignment.cs index a9eb3a2e..7c3b7c46 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Assignment.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Assignment.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -57,9 +55,10 @@ namespace VEPROMS.CSLA.Library } ClearRefreshList(); } - #endregion - #region Collection - private static List _CacheList = new List(); + #endregion + #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _CacheList = new List(); protected static void AddToCache(Assignment assignment) { if (!_CacheList.Contains(assignment)) _CacheList.Add(assignment); // In AddToCache @@ -68,7 +67,8 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(assignment)) _CacheList.Remove(assignment); // In RemoveFromCache } - private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Assignment(s) from temporary _CacheList to _CacheByPrimaryKey @@ -93,16 +93,10 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private static int _nextAID = -1; - public static int NextAID - { - get { return _nextAID--; } - } - private int _AID; + public string ErrorMessage => _ErrorMessage; + private static int _nextAID = -1; + public static int NextAID => _nextAID--; + private int _AID; [System.ComponentModel.DataObjectField(true, true)] public int AID { @@ -310,40 +304,17 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)) || (_MyGroup == null ? false : _MyGroup.IsDirtyList(list)) || (_MyRole == null ? false : _MyRole.IsDirtyList(list)); + return base.IsDirty || (_MyFolder != null && _MyFolder.IsDirtyList(list)) || (_MyGroup != null && _MyGroup.IsDirtyList(list)) || (_MyRole != null && _MyRole.IsDirtyList(list)); } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - if(list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; - list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)) && (_MyGroup == null ? true : _MyGroup.IsValidList(list)) && (_MyRole == null ? true : _MyRole.IsValidList(list)); - } - // CSLATODO: Replace base Assignment.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Assignment - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check Assignment.GetIdValue to assure that the ID returned is unique - /// - /// Overrides Base GetIdValue - Used internally by CSLA to determine equality - /// - /// A Unique ID for the current Assignment - protected override object GetIdValue() - { - return MyAssignmentUnique; // Absolutely Unique ID - } - #endregion - #region ValidationRules - [NonSerialized] + // CSLATODO: Check Assignment.GetIdValue to assure that the ID returned is unique + /// + /// Overrides Base GetIdValue - Used internally by CSLA to determine equality + /// + /// A Unique ID for the current Assignment + protected override object GetIdValue() => MyAssignmentUnique; // Absolutely Unique ID + #endregion + #region ValidationRules + [NonSerialized] private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules { @@ -371,8 +342,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -389,16 +360,11 @@ namespace VEPROMS.CSLA.Library ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UsrID", 100)); - //ValidationRules.AddDependantProperty("x", "y"); _AssignmentExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - protected override void AddInstanceBusinessRules() - { - _AssignmentExtension.AddInstanceValidationRules(ValidationRules); - // CSLATODO: Add other validation rules - } - private static bool StartDateValid(Assignment target, Csla.Validation.RuleArgs e) + protected override void AddInstanceBusinessRules() => _AssignmentExtension.AddInstanceValidationRules(ValidationRules); + private static bool StartDateValid(Assignment target, Csla.Validation.RuleArgs e) { try { @@ -451,80 +417,14 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AID, ""); - //AuthorizationRules.AllowRead(GID, ""); - //AuthorizationRules.AllowRead(RID, ""); - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(GID, ""); - //AuthorizationRules.AllowWrite(RID, ""); - //AuthorizationRules.AllowWrite(FolderID, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - _AssignmentExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _AssignmentExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - #endregion - #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } - private static int _AssignmentUnique = 0; - protected static int AssignmentUnique - { get { return ++_AssignmentUnique; } } - private int _MyAssignmentUnique = AssignmentUnique; - public int MyAssignmentUnique // Absolutely Unique ID - Editable - { get { return _MyAssignmentUnique; } } + #endregion + #region Factory Methods + public int CurrentEditLevel => EditLevel; + private static int _AssignmentUnique = 0; + protected static int AssignmentUnique => ++_AssignmentUnique; + private readonly int _MyAssignmentUnique = AssignmentUnique; + // Absolutely Unique ID - Editable + public int MyAssignmentUnique => _MyAssignmentUnique; protected Assignment() {/* require use of factory methods */ AddToCache(this); @@ -533,16 +433,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~Assignment() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~Assignment() { _CountFinalized++; } @@ -566,8 +462,6 @@ namespace VEPROMS.CSLA.Library } public static Assignment New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Assignment"); try { return DataPortal.Create(); @@ -640,8 +534,6 @@ namespace VEPROMS.CSLA.Library } public static Assignment Get(int aid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Assignment"); try { Assignment tmp = GetCachedByPrimaryKey(aid); @@ -667,14 +559,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Assignment(dr); return null; } - internal Assignment(SafeDataReader dr) + internal Assignment(SafeDataReader dr) => ReadData(dr); + public static void Delete(int aid) { - ReadData(dr); - } - public static void Delete(int aid) - { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Assignment"); try { DataPortal.Delete(new PKCriteria(aid)); @@ -686,12 +573,6 @@ namespace VEPROMS.CSLA.Library } public override Assignment Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Assignment"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Assignment"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Assignment"); try { BuildRefreshList(); @@ -711,14 +592,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _AID; - public int AID - { get { return _AID; } } - public PKCriteria(int aid) - { - _AID = aid; - } - } + private readonly int _AID; + public int AID => _AID; + public PKCriteria(int aid) => _AID = aid; + } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() @@ -790,7 +667,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Assignment.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -815,54 +692,62 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try - { - if (_MyFolder != null) _MyFolder.Update(); - if (_MyGroup != null) _MyGroup.Update(); - if (_MyRole != null) _MyRole.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addAssignment"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@GID", GID); - cm.Parameters.AddWithValue("@RID", RID); - cm.Parameters.AddWithValue("@FolderID", FolderID); - cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); - cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_AID = new SqlParameter("@newAID", SqlDbType.Int); - param_AID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AID = (int)cm.Parameters["@newAID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - } - MarkOld(); - // update child objects - if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.SQLInsert", GetHashCode()); - } - catch (Exception ex) + { + _MyFolder?.Update(); + _MyGroup?.Update(); + _MyRole?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addAssignment"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@GID", GID); + cm.Parameters.AddWithValue("@RID", RID); + cm.Parameters.AddWithValue("@FolderID", FolderID); + cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); + cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_AID = new SqlParameter("@newAID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AID = (int)cm.Parameters["@newAID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } + } + + MarkOld(); + // update child objects + if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.SQLInsert", GetHashCode()); + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Assignment.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Assignment.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int aid, Group myGroup, Role myRole, Folder myFolder, SmartDate startDate, SmartDate endDate, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Add", 0); @@ -881,13 +766,17 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@EndDate", endDate.DBValue); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); - // Output Calculated Columns - SqlParameter param_AID = new SqlParameter("@newAID", SqlDbType.Int); - param_AID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_AID = new SqlParameter("@newAID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -901,7 +790,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Assignment.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -924,48 +813,54 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.SQLUpdate", GetHashCode()); try - { - if (_MyFolder != null) _MyFolder.Update(); - if (_MyGroup != null) _MyGroup.Update(); - if (_MyRole != null) _MyRole.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) - { - using (SqlCommand cm = cn.CreateCommand()) - { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateAssignment"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AID", _AID); - cm.Parameters.AddWithValue("@GID", GID); - cm.Parameters.AddWithValue("@RID", RID); - cm.Parameters.AddWithValue("@FolderID", FolderID); - cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); - cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - } - } - MarkOld(); - // use the open connection to update child objects - } - catch (Exception ex) + { + _MyFolder?.Update(); + _MyGroup?.Update(); + _MyRole?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) + { + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateAssignment"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AID", _AID); + cm.Parameters.AddWithValue("@GID", GID); + cm.Parameters.AddWithValue("@RID", RID); + cm.Parameters.AddWithValue("@FolderID", FolderID); + cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); + cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } + } + } + + MarkOld(); + // use the open connection to update child objects + } + catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Assignment.SQLUpdate", ex); _ErrorMessage = ex.Message; @@ -974,18 +869,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) - { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, _MyRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); - else - _LastChanged = Assignment.Update(cn, ref _AID, _GID, _RID, _FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); - MarkOld(); - } - } - [Transactional(TransactionalTypes.TransactionScope)] + { + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, _MyRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + else + _LastChanged = Assignment.Update(cn, ref _AID, _GID, _RID, _FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + } + + MarkOld(); + } + } + public static byte[] Update(SqlConnection cn, ref int aid, int gid, int rid, int folderID, SmartDate startDate, SmartDate endDate, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Update", 0); @@ -1006,10 +905,12 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure @@ -1022,12 +923,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Assignment.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_AID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Delete", GetHashCode()); @@ -1052,7 +950,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Assignment.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int aid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Remove", 0); @@ -1093,24 +991,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _AID; + private readonly int _AID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int aid) - { - _AID = aid; - } - protected override void DataPortal_Execute() + public bool Exists => _exists; + public ExistsCommand(int aid) => _AID = aid; + protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1129,10 +1021,10 @@ namespace VEPROMS.CSLA.Library } } } - #endregion - // Standard Default Code - #region extension - AssignmentExtension _AssignmentExtension = new AssignmentExtension(); + #endregion + // Standard Default Code + #region extension + readonly AssignmentExtension _AssignmentExtension = new AssignmentExtension(); [Serializable()] partial class AssignmentExtension : extensionBase { @@ -1140,21 +1032,12 @@ namespace VEPROMS.CSLA.Library [Serializable()] class extensionBase { - // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } - // Authorization Rules - public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) + // Default Values + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; + // Authorization Rules + public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } @@ -1181,61 +1064,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Assignment) + if (destType == typeof(string) && value is Assignment assignmnt) { // Return the ToString value - return ((Assignment)value).ToString(); + return assignmnt.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create AssignmentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Assignment -// { -// partial class AssignmentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfo.cs index 2a11cca5..c957c688 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class AssignmentInfo : ReadOnlyBase, IDisposable { public event AssignmentInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(AssignmentInfo assignmentInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(assignmentInfo)) _CacheList.Remove(assignmentInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Assignment _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _AID; [System.ComponentModel.DataObjectField(true, true)] public int AID @@ -195,15 +179,6 @@ namespace VEPROMS.CSLA.Library return _UsrID; } } - // CSLATODO: Replace base AssignmentInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AssignmentInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check AssignmentInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality @@ -216,11 +191,10 @@ namespace VEPROMS.CSLA.Library #endregion #region Factory Methods private static int _AssignmentInfoUnique = 0; - private static int AssignmentInfoUnique - { get { return ++_AssignmentInfoUnique; } } - private int _MyAssignmentInfoUnique = AssignmentInfoUnique; - public int MyAssignmentInfoUnique // Absolutely Unique ID - Info - { get { return _MyAssignmentInfoUnique; } } + private static int AssignmentInfoUnique => ++_AssignmentInfoUnique; + private readonly int _MyAssignmentInfoUnique = AssignmentInfoUnique; + // Absolutely Unique ID - Info + public int MyAssignmentInfoUnique => _MyAssignmentInfoUnique; protected AssignmentInfo() {/* require use of factory methods */ AddToCache(this); @@ -229,15 +203,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~AssignmentInfo() { _CountFinalized++; @@ -254,10 +224,7 @@ namespace VEPROMS.CSLA.Library if (listAssignmentInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AID.ToString()); // remove the list } - public virtual Assignment Get() - { - return _Editable = Assignment.Get(_AID); - } + public virtual Assignment Get() => _Editable = Assignment.Get(_AID); public static void Refresh(Assignment tmp) { string key = tmp.AID.ToString(); @@ -270,25 +237,25 @@ namespace VEPROMS.CSLA.Library { if (_GID != tmp.GID) { - if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for old value + MyGroup?.RefreshGroupAssignments(); // Update List for old value _GID = tmp.GID; // Update the value } _MyGroup = null; // Reset list so that the next line gets a new list - if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for new value + MyGroup?.RefreshGroupAssignments(); // Update List for new value if (_RID != tmp.RID) { - if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for old value + MyRole?.RefreshRoleAssignments(); // Update List for old value _RID = tmp.RID; // Update the value } _MyRole = null; // Reset list so that the next line gets a new list - if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for new value + MyRole?.RefreshRoleAssignments(); // Update List for new value if (_FolderID != tmp.FolderID) { - if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for old value + MyFolder?.RefreshFolderAssignments(); // Update List for old value _FolderID = tmp.FolderID; // Update the value } _MyFolder = null; // Reset list so that the next line gets a new list - if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for new value + MyFolder?.RefreshFolderAssignments(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _DTS = tmp.DTS; @@ -308,18 +275,18 @@ namespace VEPROMS.CSLA.Library { if (_GID != tmp.GID) { - if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for old value + MyGroup?.RefreshGroupAssignments(); // Update List for old value _GID = tmp.GID; // Update the value } _MyGroup = null; // Reset list so that the next line gets a new list - if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for new value + MyGroup?.RefreshGroupAssignments(); // Update List for new value if (_RID != tmp.RID) { - if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for old value + MyRole?.RefreshRoleAssignments(); // Update List for old value _RID = tmp.RID; // Update the value } _MyRole = null; // Reset list so that the next line gets a new list - if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for new value + MyRole?.RefreshRoleAssignments(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _DTS = tmp.DTS; @@ -339,18 +306,18 @@ namespace VEPROMS.CSLA.Library { if (_RID != tmp.RID) { - if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for old value + MyRole?.RefreshRoleAssignments(); // Update List for old value _RID = tmp.RID; // Update the value } _MyRole = null; // Reset list so that the next line gets a new list - if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for new value + MyRole?.RefreshRoleAssignments(); // Update List for new value if (_FolderID != tmp.FolderID) { - if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for old value + MyFolder?.RefreshFolderAssignments(); // Update List for old value _FolderID = tmp.FolderID; // Update the value } _MyFolder = null; // Reset list so that the next line gets a new list - if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for new value + MyFolder?.RefreshFolderAssignments(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _DTS = tmp.DTS; @@ -370,18 +337,18 @@ namespace VEPROMS.CSLA.Library { if (_GID != tmp.GID) { - if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for old value + MyGroup?.RefreshGroupAssignments(); // Update List for old value _GID = tmp.GID; // Update the value } _MyGroup = null; // Reset list so that the next line gets a new list - if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for new value + MyGroup?.RefreshGroupAssignments(); // Update List for new value if (_FolderID != tmp.FolderID) { - if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for old value + MyFolder?.RefreshFolderAssignments(); // Update List for old value _FolderID = tmp.FolderID; // Update the value } _MyFolder = null; // Reset list so that the next line gets a new list - if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for new value + MyFolder?.RefreshFolderAssignments(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _DTS = tmp.DTS; @@ -391,8 +358,6 @@ namespace VEPROMS.CSLA.Library } public static AssignmentInfo Get(int aid) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Assignment"); try { AssignmentInfo tmp = GetCachedByPrimaryKey(aid); @@ -431,13 +396,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _AID; - public int AID - { get { return _AID; } } - public PKCriteria(int aid) - { - _AID = aid; - } + private readonly int _AID; + public int AID => _AID; + public PKCriteria(int aid) => _AID = aid; } private void ReadData(SafeDataReader dr) { @@ -499,7 +460,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - AssignmentInfoExtension _AssignmentInfoExtension = new AssignmentInfoExtension(); + readonly AssignmentInfoExtension _AssignmentInfoExtension = new AssignmentInfoExtension(); [Serializable()] partial class AssignmentInfoExtension : extensionBase { } [Serializable()] @@ -515,10 +476,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AssignmentInfo) + if (destType == typeof(string) && value is AssignmentInfo info) { // Return the ToString value - return ((AssignmentInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfoList.cs index 102d77e4..7dcd65e0 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AssignmentInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (AssignmentInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AssignmentInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AssignmentInfoList() { _CountFinalized++; } @@ -97,25 +90,6 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on AssignmentInfoList.Get", ex); } } - /// - /// Reset the list of all AssignmentInfo. - /// - public static void Reset() - { - _AssignmentInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static AssignmentInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on AssignmentInfoList.Get", ex); - // } - //} public static AssignmentInfoList GetByFolderID(int folderID) { try @@ -194,11 +168,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class FolderIDCriteria { - public FolderIDCriteria(int folderID) - { - _FolderID = folderID; - } - private int _FolderID; + public FolderIDCriteria(int folderID) => _FolderID = folderID; + private int _FolderID; public int FolderID { get { return _FolderID; } @@ -238,11 +209,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class GIDCriteria { - public GIDCriteria(int gid) - { - _GID = gid; - } - private int _GID; + public GIDCriteria(int gid) => _GID = gid; + private int _GID; public int GID { get { return _GID; } @@ -282,11 +250,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class RIDCriteria { - public RIDCriteria(int rid) - { - _RID = rid; - } - private int _RID; + public RIDCriteria(int rid) => _RID = rid; + private int _RID; public int RID { get { return _RID; } @@ -323,41 +288,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -379,7 +333,6 @@ namespace VEPROMS.CSLA.Library /// public partial class AssignmentInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private AssignmentInfo Item { get { return (AssignmentInfo)_Item; } } public AssignmentInfoListPropertyDescriptor(AssignmentInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -388,10 +341,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AssignmentInfoList) + if (destType == typeof(string) && value is AssignmentInfoList list) { // Return department and department role separated by comma. - return ((AssignmentInfoList)value).Items.Count.ToString() + " Assignments"; + return $"{list.Items.Count} Assignments"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Association.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Association.cs index c796a700..5b4671b9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Association.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Association.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshAssociations.Add(this); } - private void ClearRefreshList() - { - _RefreshAssociations = new List(); - } + private void ClearRefreshList() => _RefreshAssociations = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Association association) { @@ -67,7 +63,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(association)) _CacheList.Remove(association); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByVersionID_ROFstID = new Dictionary>(); private static void ConvertListToDictionary() { @@ -102,15 +100,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAssociationID = -1; - public static int NextAssociationID - { - get { return _nextAssociationID--; } - } + public static int NextAssociationID => _nextAssociationID--; private int _AssociationID; [System.ComponentModel.DataObjectField(true, true)] public int AssociationID @@ -254,37 +246,14 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyDocVersion == null ? false : _MyDocVersion.IsDirtyList(list)) || (_MyROFst == null ? false : _MyROFst.IsDirtyList(list)); + return base.IsDirty || (_MyDocVersion != null && _MyDocVersion.IsDirtyList(list)) || (_MyROFst != null && _MyROFst.IsDirtyList(list)); } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; - list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocVersion == null ? true : _MyDocVersion.IsValidList(list)) && (_MyROFst == null ? true : _MyROFst.IsValidList(list)); - } - // CSLATODO: Replace base Association.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Association - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Association.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Association - protected override object GetIdValue() - { - return MyAssociationUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyAssociationUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -314,8 +283,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -330,15 +299,10 @@ namespace VEPROMS.CSLA.Library ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); - //ValidationRules.AddDependantProperty("x", "y"); _AssociationExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - protected override void AddInstanceBusinessRules() - { - _AssociationExtension.AddInstanceValidationRules(ValidationRules); - // CSLATODO: Add other validation rules - } + protected override void AddInstanceBusinessRules() => _AssociationExtension.AddInstanceValidationRules(ValidationRules); private static bool MyDocVersionRequired(Association target, Csla.Validation.RuleArgs e) { if (target._VersionID == 0 && target._MyDocVersion == null) // Required field missing @@ -357,76 +321,14 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AssociationID, ""); - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(ROFstID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(VersionID, ""); - //AuthorizationRules.AllowWrite(ROFstID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - _AssociationExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _AssociationExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _AssociationUnique = 0; - protected static int AssociationUnique - { get { return ++_AssociationUnique; } } - private int _MyAssociationUnique = AssociationUnique; - public int MyAssociationUnique // Absolutely Unique ID - Editable - { get { return _MyAssociationUnique; } } + protected static int AssociationUnique => ++_AssociationUnique; + private readonly int _MyAssociationUnique = AssociationUnique; + // Absolutely Unique ID - Editable + public int MyAssociationUnique => _MyAssociationUnique; protected Association() {/* require use of factory methods */ AddToCache(this); @@ -435,15 +337,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Association() { _CountFinalized++; @@ -480,8 +378,6 @@ namespace VEPROMS.CSLA.Library } public static Association New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Association"); try { return DataPortal.Create(); @@ -519,7 +415,7 @@ namespace VEPROMS.CSLA.Library tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { - tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; + tmp._ErrorMessage += $"\r\n\tFailure: {br.RuleName}"; } } return tmp; @@ -550,8 +446,6 @@ namespace VEPROMS.CSLA.Library } public static Association Get(int associationID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Association"); try { Association tmp = GetCachedByPrimaryKey(associationID); @@ -574,8 +468,6 @@ namespace VEPROMS.CSLA.Library } public static Association GetByVersionID_ROFstID(int versionID, int rOFstID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Association"); try { Association tmp = GetCachedByVersionID_ROFstID(versionID, rOFstID); @@ -601,14 +493,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Association(dr); return null; } - internal Association(SafeDataReader dr) - { - ReadData(dr); - } + internal Association(SafeDataReader dr) => ReadData(dr); public static void Delete(int associationID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Association"); try { DataPortal.Delete(new PKCriteria(associationID)); @@ -620,12 +507,6 @@ namespace VEPROMS.CSLA.Library } public override Association Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Association"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Association"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Association"); try { BuildRefreshList(); @@ -645,23 +526,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _AssociationID; - public int AssociationID - { get { return _AssociationID; } } - public PKCriteria(int associationID) - { - _AssociationID = associationID; - } + private readonly int _AssociationID; + public int AssociationID => _AssociationID; + public PKCriteria(int associationID) => _AssociationID = associationID; } [Serializable()] private class VersionID_ROFstIDCriteria { - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } + private readonly int _VersionID; + public int VersionID => _VersionID; + private readonly int _ROFstID; + public int ROFstID => _ROFstID; public VersionID_ROFstIDCriteria(int versionID, int rOFstID) { _VersionID = versionID; @@ -773,7 +648,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Association.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -798,39 +673,47 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyDocVersion != null) _MyDocVersion.Update(); - if (_MyROFst != null) _MyROFst.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyDocVersion?.Update(); + _MyROFst?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addAssociation"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@VersionID", VersionID); - cm.Parameters.AddWithValue("@ROFstID", ROFstID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_AssociationID = new SqlParameter("@newAssociationID", SqlDbType.Int); - param_AssociationID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AssociationID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AssociationID = (int)cm.Parameters["@newAssociationID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addAssociation"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@VersionID", VersionID); + cm.Parameters.AddWithValue("@ROFstID", ROFstID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_AssociationID = new SqlParameter("@newAssociationID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AssociationID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AssociationID = (int)cm.Parameters["@newAssociationID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.SQLInsert", GetHashCode()); @@ -842,7 +725,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Association.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int associationID, DocVersion myDocVersion, ROFst myROFst, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Add", 0); @@ -860,11 +743,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_AssociationID = new SqlParameter("@newAssociationID", SqlDbType.Int); - param_AssociationID.Direction = ParameterDirection.Output; + SqlParameter param_AssociationID = new SqlParameter("@newAssociationID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AssociationID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -879,7 +766,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Association.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -902,41 +789,47 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.SQLUpdate", GetHashCode()); try { - if (_MyDocVersion != null) _MyDocVersion.Update(); - if (_MyROFst != null) _MyROFst.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyDocVersion?.Update(); + _MyROFst?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateAssociation"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AssociationID", _AssociationID); - cm.Parameters.AddWithValue("@VersionID", VersionID); - cm.Parameters.AddWithValue("@ROFstID", ROFstID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateAssociation"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AssociationID", _AssociationID); + cm.Parameters.AddWithValue("@VersionID", VersionID); + cm.Parameters.AddWithValue("@ROFstID", ROFstID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -949,18 +842,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Association.Add(cn, ref _AssociationID, _MyDocVersion, _MyROFst, _Config, _DTS, _UserID); - else - _LastChanged = Association.Update(cn, ref _AssociationID, _VersionID, _ROFstID, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Association.Add(cn, ref _AssociationID, _MyDocVersion, _MyROFst, _Config, _DTS, _UserID); + else + _LastChanged = Association.Update(cn, ref _AssociationID, _VersionID, _ROFstID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int associationID, int versionID, int rOFstID, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Update", 0); @@ -980,8 +877,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -995,12 +894,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Association.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_AssociationID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AssociationID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Delete", GetHashCode()); @@ -1025,7 +921,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Association.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int associationID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Remove", 0); @@ -1066,16 +962,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _AssociationID; + private readonly int _AssociationID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int associationID) - { - _AssociationID = associationID; - } + public bool Exists => _exists; + public ExistsCommand(int associationID) => _AssociationID = associationID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Execute", GetHashCode()); @@ -1083,7 +973,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1105,7 +995,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - AssociationExtension _AssociationExtension = new AssociationExtension(); + readonly AssociationExtension _AssociationExtension = new AssociationExtension(); [Serializable()] partial class AssociationExtension : extensionBase { @@ -1114,14 +1004,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1150,10 +1034,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Association) + if (destType == typeof(string) && value is Association assn) { // Return the ToString value - return ((Association)value).ToString(); + return assn.ToString(); } return base.ConvertTo(context, culture, value, destType); } @@ -1161,46 +1045,3 @@ namespace VEPROMS.CSLA.Library #endregion } // Namespace - -//// The following is a sample Extension File. You can use it to create AssociationExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Association -// { -// partial class AssociationExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfo.cs index 6715d67a..e86babac 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class AssociationInfo : ReadOnlyBase, IDisposable { public event AssociationInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(AssociationInfo associationInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(associationInfo)) _CacheList.Remove(associationInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Association _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _AssociationID; [System.ComponentModel.DataObjectField(true, true)] public int AssociationID @@ -167,32 +151,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base AssociationInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current AssociationInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check AssociationInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current AssociationInfo - protected override object GetIdValue() - { - return MyAssociationInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyAssociationInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _AssociationInfoUnique = 0; - private static int AssociationInfoUnique - { get { return ++_AssociationInfoUnique; } } - private int _MyAssociationInfoUnique = AssociationInfoUnique; - public int MyAssociationInfoUnique // Absolutely Unique ID - Info - { get { return _MyAssociationInfoUnique; } } + private static int AssociationInfoUnique => ++_AssociationInfoUnique; + private readonly int _MyAssociationInfoUnique = AssociationInfoUnique; + // Absolutely Unique ID - Info + public int MyAssociationInfoUnique => _MyAssociationInfoUnique; protected AssociationInfo() {/* require use of factory methods */ AddToCache(this); @@ -201,15 +172,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~AssociationInfo() { _CountFinalized++; @@ -226,10 +193,7 @@ namespace VEPROMS.CSLA.Library if (listAssociationInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AssociationID.ToString()); // remove the list } - public virtual Association Get() - { - return _Editable = Association.Get(_AssociationID); - } + public virtual Association Get() => _Editable = Association.Get(_AssociationID); public static void Refresh(Association tmp) { string key = tmp.AssociationID.ToString(); @@ -242,18 +206,18 @@ namespace VEPROMS.CSLA.Library { if (_VersionID != tmp.VersionID) { - if (MyDocVersion != null) MyDocVersion.RefreshDocVersionAssociations(); // Update List for old value + MyDocVersion?.RefreshDocVersionAssociations(); // Update List for old value _VersionID = tmp.VersionID; // Update the value } _MyDocVersion = null; // Reset list so that the next line gets a new list - if (MyDocVersion != null) MyDocVersion.RefreshDocVersionAssociations(); // Update List for new value + MyDocVersion?.RefreshDocVersionAssociations(); // Update List for new value if (_ROFstID != tmp.ROFstID) { - if (MyROFst != null) MyROFst.RefreshROFstAssociations(); // Update List for old value + MyROFst?.RefreshROFstAssociations(); // Update List for old value _ROFstID = tmp.ROFstID; // Update the value } _MyROFst = null; // Reset list so that the next line gets a new list - if (MyROFst != null) MyROFst.RefreshROFstAssociations(); // Update List for new value + MyROFst?.RefreshROFstAssociations(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -272,11 +236,11 @@ namespace VEPROMS.CSLA.Library { if (_ROFstID != tmp.ROFstID) { - if (MyROFst != null) MyROFst.RefreshROFstAssociations(); // Update List for old value + MyROFst?.RefreshROFstAssociations(); // Update List for old value _ROFstID = tmp.ROFstID; // Update the value } _MyROFst = null; // Reset list so that the next line gets a new list - if (MyROFst != null) MyROFst.RefreshROFstAssociations(); // Update List for new value + MyROFst?.RefreshROFstAssociations(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -295,11 +259,11 @@ namespace VEPROMS.CSLA.Library { if (_VersionID != tmp.VersionID) { - if (MyDocVersion != null) MyDocVersion.RefreshDocVersionAssociations(); // Update List for old value + MyDocVersion?.RefreshDocVersionAssociations(); // Update List for old value _VersionID = tmp.VersionID; // Update the value } _MyDocVersion = null; // Reset list so that the next line gets a new list - if (MyDocVersion != null) MyDocVersion.RefreshDocVersionAssociations(); // Update List for new value + MyDocVersion?.RefreshDocVersionAssociations(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -308,8 +272,6 @@ namespace VEPROMS.CSLA.Library } public static AssociationInfo Get(int associationID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Association"); try { AssociationInfo tmp = GetCachedByPrimaryKey(associationID); @@ -348,13 +310,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _AssociationID; - public int AssociationID - { get { return _AssociationID; } } - public PKCriteria(int associationID) - { - _AssociationID = associationID; - } + private readonly int _AssociationID; + public int AssociationID => _AssociationID; + public PKCriteria(int associationID) => _AssociationID = associationID; } private void ReadData(SafeDataReader dr) { @@ -414,7 +372,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - AssociationInfoExtension _AssociationInfoExtension = new AssociationInfoExtension(); + readonly AssociationInfoExtension _AssociationInfoExtension = new AssociationInfoExtension(); [Serializable()] partial class AssociationInfoExtension : extensionBase { } [Serializable()] @@ -430,10 +388,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AssociationInfo) + if (destType == typeof(string) && value is AssociationInfo info) { // Return the ToString value - return ((AssociationInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfoList.cs index dd110171..e5bf3a11 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/AssociationInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (AssociationInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~AssociationInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~AssociationInfoList() { _CountFinalized++; } @@ -104,18 +97,7 @@ namespace VEPROMS.CSLA.Library { _AssociationInfoList = null; } - // CSLATODO: Add alternative gets - - //public static AssociationInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on AssociationInfoList.Get", ex); - // } - //} + public static AssociationInfoList GetByVersionID(int versionID) { try @@ -180,11 +162,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class VersionIDCriteria { - public VersionIDCriteria(int versionID) - { - _VersionID = versionID; - } - private int _VersionID; + public VersionIDCriteria(int versionID) => _VersionID = versionID; + private int _VersionID; public int VersionID { get { return _VersionID; } @@ -224,11 +203,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ROFstIDCriteria { - public ROFstIDCriteria(int rOFstID) - { - _ROFstID = rOFstID; - } - private int _ROFstID; + public ROFstIDCriteria(int rOFstID) => _ROFstID = rOFstID; + private int _ROFstID; public int ROFstID { get { return _ROFstID; } @@ -265,41 +241,31 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -321,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class AssociationInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private AssociationInfo Item { get { return (AssociationInfo)_Item; } } public AssociationInfoListPropertyDescriptor(AssociationInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is AssociationInfoList) + if (destType == typeof(string) && value is AssociationInfoList list) { // Return department and department role separated by comma. - return ((AssociationInfoList)value).Items.Count.ToString() + " Associations"; + return $"{list.Items.Count} Associations"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Check.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Check.cs index 01d5a961..797a0d8b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Check.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Check.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshChecks.Add(this); } - private void ClearRefreshList() - { - _RefreshChecks = new List(); - } + private void ClearRefreshList() => _RefreshChecks = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Check check) { @@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(check)) _CacheList.Remove(check); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,15 +89,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextCheckID = -1; - public static int NextCheckID - { - get { return _nextCheckID--; } - } + public static int NextCheckID => _nextCheckID--; private int _CheckID; [System.ComponentModel.DataObjectField(true, true)] public int CheckID @@ -242,7 +233,7 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)) || (_MyStage == null ? false : _MyStage.IsDirtyList(list)); + return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list)) || (_MyStage != null && _MyStage.IsDirtyList(list)); } public override bool IsValid { @@ -251,20 +242,10 @@ namespace VEPROMS.CSLA.Library public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)) && (_MyStage == null ? true : _MyStage.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list)) && (_MyStage == null || _MyStage.IsValidList(list)); } - // CSLATODO: Replace base Check.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Check - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check Check.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// @@ -302,8 +283,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -318,14 +299,12 @@ namespace VEPROMS.CSLA.Library ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); - //ValidationRules.AddDependantProperty("x", "y"); _CheckExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _CheckExtension.AddInstanceValidationRules(ValidationRules); - // CSLATODO: Add other validation rules } private static bool MyRevisionRequired(Check target, Csla.Validation.RuleArgs e) { @@ -345,76 +324,14 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(CheckID, ""); - //AuthorizationRules.AllowRead(RevisionID, ""); - //AuthorizationRules.AllowRead(StageID, ""); - //AuthorizationRules.AllowRead(ConsistencyChecks, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(RevisionID, ""); - //AuthorizationRules.AllowWrite(StageID, ""); - //AuthorizationRules.AllowWrite(ConsistencyChecks, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - _CheckExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _CheckExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _CheckUnique = 0; - protected static int CheckUnique - { get { return ++_CheckUnique; } } - private int _MyCheckUnique = CheckUnique; - public int MyCheckUnique // Absolutely Unique ID - Editable - { get { return _MyCheckUnique; } } + protected static int CheckUnique => ++_CheckUnique; + private readonly int _MyCheckUnique = CheckUnique; + // Absolutely Unique ID - Editable + public int MyCheckUnique => _MyCheckUnique; protected Check() {/* require use of factory methods */ AddToCache(this); @@ -423,15 +340,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Check() { _CountFinalized++; @@ -456,8 +369,6 @@ namespace VEPROMS.CSLA.Library } public static Check New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Check"); try { return DataPortal.Create(); @@ -526,8 +437,6 @@ namespace VEPROMS.CSLA.Library } public static Check Get(int checkID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Check"); try { Check tmp = GetCachedByPrimaryKey(checkID); @@ -553,14 +462,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Check(dr); return null; } - internal Check(SafeDataReader dr) - { - ReadData(dr); - } + internal Check(SafeDataReader dr) => ReadData(dr); public static void Delete(int checkID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Check"); try { DataPortal.Delete(new PKCriteria(checkID)); @@ -572,12 +476,6 @@ namespace VEPROMS.CSLA.Library } public override Check Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Check"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Check"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Check"); try { BuildRefreshList(); @@ -597,13 +495,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _CheckID; - public int CheckID - { get { return _CheckID; } } - public PKCriteria(int checkID) - { - _CheckID = checkID; - } + private readonly int _CheckID; + public int CheckID => _CheckID; + public PKCriteria(int checkID) => _CheckID = checkID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -673,7 +567,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Check.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -698,39 +592,47 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyRevision != null) _MyRevision.Update(); - if (_MyStage != null) _MyStage.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyRevision?.Update(); + _MyStage?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addCheck"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@RevisionID", RevisionID); - cm.Parameters.AddWithValue("@StageID", StageID); - cm.Parameters.AddWithValue("@ConsistencyChecks", _ConsistencyChecks); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_CheckID = new SqlParameter("@newCheckID", SqlDbType.Int); - param_CheckID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_CheckID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _CheckID = (int)cm.Parameters["@newCheckID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addCheck"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@RevisionID", RevisionID); + cm.Parameters.AddWithValue("@StageID", StageID); + cm.Parameters.AddWithValue("@ConsistencyChecks", _ConsistencyChecks); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_CheckID = new SqlParameter("@newCheckID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_CheckID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _CheckID = (int)cm.Parameters["@newCheckID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.SQLInsert", GetHashCode()); @@ -742,7 +644,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Check.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int checkID, Revision myRevision, Stage myStage, string consistencyChecks, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Add", 0); @@ -760,11 +662,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_CheckID = new SqlParameter("@newCheckID", SqlDbType.Int); - param_CheckID.Direction = ParameterDirection.Output; + SqlParameter param_CheckID = new SqlParameter("@newCheckID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_CheckID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -779,7 +685,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Check.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -802,41 +708,47 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.SQLUpdate", GetHashCode()); try { - if (_MyRevision != null) _MyRevision.Update(); - if (_MyStage != null) _MyStage.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyRevision?.Update(); + _MyStage?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateCheck"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@CheckID", _CheckID); - cm.Parameters.AddWithValue("@RevisionID", RevisionID); - cm.Parameters.AddWithValue("@StageID", StageID); - cm.Parameters.AddWithValue("@ConsistencyChecks", _ConsistencyChecks); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateCheck"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@CheckID", _CheckID); + cm.Parameters.AddWithValue("@RevisionID", RevisionID); + cm.Parameters.AddWithValue("@StageID", StageID); + cm.Parameters.AddWithValue("@ConsistencyChecks", _ConsistencyChecks); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -849,18 +761,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, _MyStage, _ConsistencyChecks, _DTS, _UserID); - else - _LastChanged = Check.Update(cn, ref _CheckID, _RevisionID, _StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, _MyStage, _ConsistencyChecks, _DTS, _UserID); + else + _LastChanged = Check.Update(cn, ref _CheckID, _RevisionID, _StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int checkID, int revisionID, int stageID, string consistencyChecks, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Update", 0); @@ -880,8 +796,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -895,12 +813,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Check.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_CheckID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_CheckID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Delete", GetHashCode()); @@ -925,7 +840,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Check.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int checkID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Remove", 0); @@ -966,16 +881,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _CheckID; + private readonly int _CheckID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int checkID) - { - _CheckID = checkID; - } + public bool Exists => _exists; + public ExistsCommand(int checkID) => _CheckID = checkID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Execute", GetHashCode()); @@ -983,7 +892,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1005,7 +914,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - CheckExtension _CheckExtension = new CheckExtension(); + readonly CheckExtension _CheckExtension = new CheckExtension(); [Serializable()] partial class CheckExtension : extensionBase { @@ -1014,14 +923,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1050,10 +953,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Check) + if (destType == typeof(string) && value is Check check) { // Return the ToString value - return ((Check)value).ToString(); + return check.ToString(); } return base.ConvertTo(context, culture, value, destType); } @@ -1061,46 +964,3 @@ namespace VEPROMS.CSLA.Library #endregion } // Namespace - -//// The following is a sample Extension File. You can use it to create CheckExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Check -// { -// partial class CheckExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfo.cs index 41514fce..cb912731 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class CheckInfo : ReadOnlyBase, IDisposable { public event CheckInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(CheckInfo checkInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(checkInfo)) _CacheList.Remove(checkInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Check _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _CheckID; [System.ComponentModel.DataObjectField(true, true)] public int CheckID @@ -166,32 +150,18 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base CheckInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current CheckInfo - //public override string ToString() - //{ - // return base.ToString(); - //} - // CSLATODO: Check CheckInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current CheckInfo - protected override object GetIdValue() - { - return MyCheckInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyCheckInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _CheckInfoUnique = 0; - private static int CheckInfoUnique - { get { return ++_CheckInfoUnique; } } - private int _MyCheckInfoUnique = CheckInfoUnique; - public int MyCheckInfoUnique // Absolutely Unique ID - Info - { get { return _MyCheckInfoUnique; } } + private static int CheckInfoUnique => ++_CheckInfoUnique; + private readonly int _MyCheckInfoUnique = CheckInfoUnique; + // Absolutely Unique ID - Info + public int MyCheckInfoUnique => _MyCheckInfoUnique; protected CheckInfo() {/* require use of factory methods */ AddToCache(this); @@ -200,15 +170,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~CheckInfo() { _CountFinalized++; @@ -225,10 +191,7 @@ namespace VEPROMS.CSLA.Library if (listCheckInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(CheckID.ToString()); // remove the list } - public virtual Check Get() - { - return _Editable = Check.Get(_CheckID); - } + public virtual Check Get() => _Editable = Check.Get(_CheckID); public static void Refresh(Check tmp) { string key = tmp.CheckID.ToString(); @@ -241,18 +204,18 @@ namespace VEPROMS.CSLA.Library { if (_RevisionID != tmp.RevisionID) { - if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for old value + MyRevision?.RefreshRevisionChecks(); // Update List for old value _RevisionID = tmp.RevisionID; // Update the value } _MyRevision = null; // Reset list so that the next line gets a new list - if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for new value + MyRevision?.RefreshRevisionChecks(); // Update List for new value if (_StageID != tmp.StageID) { - if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for old value + MyStage?.RefreshStageChecks(); // Update List for old value _StageID = tmp.StageID; // Update the value } _MyStage = null; // Reset list so that the next line gets a new list - if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for new value + MyStage?.RefreshStageChecks(); // Update List for new value _ConsistencyChecks = tmp.ConsistencyChecks; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -271,11 +234,11 @@ namespace VEPROMS.CSLA.Library { if (_StageID != tmp.StageID) { - if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for old value + MyStage?.RefreshStageChecks(); // Update List for old value _StageID = tmp.StageID; // Update the value } _MyStage = null; // Reset list so that the next line gets a new list - if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for new value + MyStage?.RefreshStageChecks(); // Update List for new value _ConsistencyChecks = tmp.ConsistencyChecks; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -294,11 +257,11 @@ namespace VEPROMS.CSLA.Library { if (_RevisionID != tmp.RevisionID) { - if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for old value + MyRevision?.RefreshRevisionChecks(); // Update List for old value _RevisionID = tmp.RevisionID; // Update the value } _MyRevision = null; // Reset list so that the next line gets a new list - if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for new value + MyRevision?.RefreshRevisionChecks(); // Update List for new value _ConsistencyChecks = tmp.ConsistencyChecks; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -307,8 +270,6 @@ namespace VEPROMS.CSLA.Library } public static CheckInfo Get(int checkID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Check"); try { CheckInfo tmp = GetCachedByPrimaryKey(checkID); @@ -347,13 +308,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _CheckID; - public int CheckID - { get { return _CheckID; } } - public PKCriteria(int checkID) - { - _CheckID = checkID; - } + private readonly int _CheckID; + public int CheckID => _CheckID; + public PKCriteria(int checkID) => _CheckID = checkID; } private void ReadData(SafeDataReader dr) { @@ -413,7 +370,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - CheckInfoExtension _CheckInfoExtension = new CheckInfoExtension(); + readonly CheckInfoExtension _CheckInfoExtension = new CheckInfoExtension(); [Serializable()] partial class CheckInfoExtension : extensionBase { } [Serializable()] @@ -429,10 +386,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is CheckInfo) + if (destType == typeof(string) && value is CheckInfo info) { // Return the ToString value - return ((CheckInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfoList.cs index 3efcd815..ed90898a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/CheckInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (CheckInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~CheckInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~CheckInfoList() { _CountFinalized++; } @@ -180,11 +173,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class RevisionIDCriteria { - public RevisionIDCriteria(int revisionID) - { - _RevisionID = revisionID; - } - private int _RevisionID; + public RevisionIDCriteria(int revisionID) => _RevisionID = revisionID; + private int _RevisionID; public int RevisionID { get { return _RevisionID; } @@ -224,11 +214,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class StageIDCriteria { - public StageIDCriteria(int stageID) - { - _StageID = stageID; - } - private int _StageID; + public StageIDCriteria(int stageID) => _StageID = stageID; + private int _StageID; public int StageID { get { return _StageID; } @@ -265,41 +252,31 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -321,7 +298,6 @@ namespace VEPROMS.CSLA.Library /// public partial class CheckInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private CheckInfo Item { get { return (CheckInfo)_Item; } } public CheckInfoListPropertyDescriptor(CheckInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +306,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is CheckInfoList) + if (destType == typeof(string) && value is CheckInfoList list) { // Return department and department role separated by comma. - return ((CheckInfoList)value).Items.Count.ToString() + " Checks"; + return $"{list.Items.Count} Checks"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ChildFolders.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ChildFolders.cs index c7ed1e1a..86a5688b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ChildFolders.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ChildFolders.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public new Folder this[int folderID] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public new Folder this[int folderID] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public Folder GetItem(int folderID) + public new System.Collections.Generic.IList Items => base.Items; + public Folder GetItem(int folderID) { foreach (Folder folder in this) if (folder.FolderID == folderID) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(name)) { Folder folder = Folder.New(myParent, name, shortName); - this.Add(folder); + Add(folder); return folder; } else @@ -108,23 +100,19 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid - { - get { return IsValidList(new List()); } - } public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (Folder child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + { + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (Folder child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(string name) { foreach (Folder folder in this) @@ -156,20 +144,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return (hasBrokenRules?.BrokenRules); } } - #endregion - #region Factory Methods - internal static ChildFolders New() - { - return new ChildFolders(); - } - internal static ChildFolders Get(SafeDataReader dr, Folder parent) - { - return new ChildFolders(dr, parent); - } - public static ChildFolders GetByParentID(int parentID) + #endregion + #region Factory Methods + internal static ChildFolders New() => new ChildFolders(); + internal static ChildFolders Get(SafeDataReader dr, Folder parent) => new ChildFolders(dr, parent); + public static ChildFolders GetByParentID(int parentID) { try { @@ -180,11 +162,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ChildFolders.GetByParentID", ex); } } - private ChildFolders() - { - MarkAsChild(); - } - internal ChildFolders(SafeDataReader dr, Folder parent) + private ChildFolders() => MarkAsChild(); + internal ChildFolders(SafeDataReader dr, Folder parent) { MarkAsChild(); Fetch(dr, parent); @@ -193,16 +172,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ChildFolders() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ChildFolders() { _CountFinalized++; } @@ -217,19 +192,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr, Folder parent) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(Folder.Get(dr, parent)); - this.RaiseListChangedEvents = true; + Add(Folder.Get(dr, parent)); + RaiseListChangedEvents = true; } [Serializable()] private class ParentIDCriteria { - public ParentIDCriteria(int parentID) - { - _ParentID = parentID; - } - private int _ParentID; + public ParentIDCriteria(int parentID) => _ParentID = parentID; + private int _ParentID; public int ParentID { get { return _ParentID; } @@ -238,7 +210,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ParentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ChildFolders.DataPortal_FetchParentID", GetHashCode()); try { @@ -252,7 +224,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new Folder(dr, criteria.ParentID)); + while (dr.Read()) Add(new Folder(dr, criteria.ParentID)); } } } @@ -262,11 +234,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ChildFolders.DataPortal_FetchParentID", ex); throw new DbCslaException("ChildFolders.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Folder folder) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -285,49 +257,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ChildFoldersPropertyDescriptor pd = new ChildFoldersPropertyDescriptor(this, i); @@ -353,10 +314,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ChildFolders) + if (destType == typeof(string) && value is ChildFolders folders) { // Return department and department role separated by comma. - return ((ChildFolders)value).Items.Count.ToString() + " Folders"; + return $"{folders.Items.Count} Folders"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ChildFormats.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ChildFormats.cs index 932f9485..ab619955 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ChildFormats.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ChildFormats.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public new Format this[int formatID] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public new Format this[int formatID] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public Format GetItem(int formatID) + public new System.Collections.Generic.IList Items => base.Items; + public Format GetItem(int formatID) { foreach (Format format in this) if (format.FormatID == formatID) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(name)) { Format format = Format.New(myParent, name, data); - this.Add(format); + Add(format); return format; } else @@ -108,23 +100,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (Format child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (Format child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(string name) { foreach (Format format in this) @@ -156,20 +145,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return (hasBrokenRules?.BrokenRules); } } - #endregion - #region Factory Methods - internal static ChildFormats New() - { - return new ChildFormats(); - } - internal static ChildFormats Get(SafeDataReader dr, Format parent) - { - return new ChildFormats(dr, parent); - } - public static ChildFormats GetByParentID(int parentID) + #endregion + #region Factory Methods + internal static ChildFormats New() => new ChildFormats(); + internal static ChildFormats Get(SafeDataReader dr, Format parent) => new ChildFormats(dr, parent); + public static ChildFormats GetByParentID(int parentID) { try { @@ -180,11 +163,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ChildFormats.GetByParentID", ex); } } - private ChildFormats() - { - MarkAsChild(); - } - internal ChildFormats(SafeDataReader dr, Format parent) + private ChildFormats() => MarkAsChild(); + internal ChildFormats(SafeDataReader dr, Format parent) { MarkAsChild(); Fetch(dr, parent); @@ -193,16 +173,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ChildFormats() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ChildFormats() { _CountFinalized++; } @@ -217,19 +193,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr, Format parent) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(Format.Get(dr, parent)); - this.RaiseListChangedEvents = true; + Add(Format.Get(dr, parent)); + RaiseListChangedEvents = true; } [Serializable()] private class ParentIDCriteria { - public ParentIDCriteria(int parentID) - { - _ParentID = parentID; - } - private int _ParentID; + public ParentIDCriteria(int parentID) => _ParentID = parentID; + private int _ParentID; public int ParentID { get { return _ParentID; } @@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ParentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ChildFormats.DataPortal_FetchParentID", GetHashCode()); try { @@ -252,7 +225,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new Format(dr, criteria.ParentID)); + while (dr.Read()) Add(new Format(dr, criteria.ParentID)); } } } @@ -262,11 +235,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ChildFormats.DataPortal_FetchParentID", ex); throw new DbCslaException("ChildFormats.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Format format) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -285,49 +258,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ChildFormatsPropertyDescriptor pd = new ChildFormatsPropertyDescriptor(this, i); @@ -344,7 +306,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ChildFormatsPropertyDescriptor : vlnListPropertyDescriptor { - private Format Item { get { return (Format)_Item; } } public ChildFormatsPropertyDescriptor(ChildFormats collection, int index) : base(collection, index) { ;} } #endregion @@ -353,10 +314,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ChildFormats) + if (destType == typeof(string) && value is ChildFormats formats) { // Return department and department role separated by comma. - return ((ChildFormats)value).Items.Count.ToString() + " Formats"; + return $"{formats.Items.Count} Formats"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/CommonRules.cs b/PROMS/VEPROMS.CSLA.Library/Generated/CommonRules.cs index b59fd468..3a806d95 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/CommonRules.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/CommonRules.cs @@ -8,15 +8,6 @@ // $History: $ // ======================================================================== -using System; -using System.Data; -using System.Data.SqlClient; -using Csla; -using Csla.Data; -using System.Configuration; -using System.IO; -using System.ComponentModel; -using Csla.Validation; using System.Reflection; namespace VEPROMS.CSLA.Library { @@ -31,7 +22,7 @@ namespace VEPROMS.CSLA.Library if (propertyInfoObj == null) return true; if (propertyInfoObj.GetValue(target, null) == null) { - e.Description = e.PropertyName + " is a required field"; + e.Description = $"{e.PropertyName} is a required field"; return false; } return true; diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Connection.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Connection.cs index 784492cd..0c5bd7a8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Connection.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Connection.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -69,6 +67,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Connection connection) { @@ -78,7 +77,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(connection)) _CacheList.Remove(connection); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByName = new Dictionary>(); private static void ConvertListToDictionary() { @@ -113,15 +114,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextDBID = -1; - public static int NextDBID - { - get { return _nextDBID--; } - } + public static int NextDBID => _nextDBID--; private int _DBID; [System.ComponentModel.DataObjectField(true, true)] public int DBID @@ -298,10 +293,6 @@ namespace VEPROMS.CSLA.Library return _ConnectionFolders; } } - public void Reset_ConnectionFolders() - { - _ConnectionFolderCount = -1; - } public override bool IsDirty { get @@ -316,37 +307,21 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_ConnectionFolders == null ? false : _ConnectionFolders.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_ConnectionFolders != null && _ConnectionFolders.IsDirtyList(list)); } public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_ConnectionFolders == null ? true : _ConnectionFolders.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_ConnectionFolders == null || _ConnectionFolders.IsValidList(list)); } - // CSLATODO: Replace base Connection.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Connection - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Connection.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Connection - protected override object GetIdValue() - { - return MyConnectionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyConnectionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -375,8 +350,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -407,93 +382,14 @@ namespace VEPROMS.CSLA.Library _ConnectionExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DBID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowRead(ConnectionString, ""); - //AuthorizationRules.AllowRead(ServerType, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowWrite(ConnectionString, ""); - //AuthorizationRules.AllowWrite(ServerType, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - _ConnectionExtension.AddAuthorizationRules(AuthorizationRules); - } - protected override void AddInstanceAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - _ConnectionExtension.AddInstanceAuthorizationRules(AuthorizationRules); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _ConnectionFolderCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ConnectionUnique = 0; - protected static int ConnectionUnique - { get { return ++_ConnectionUnique; } } - private int _MyConnectionUnique = ConnectionUnique; - public int MyConnectionUnique // Absolutely Unique ID - Editable - { get { return _MyConnectionUnique; } } + protected static int ConnectionUnique => ++_ConnectionUnique; + private readonly int _MyConnectionUnique = ConnectionUnique; + // Absolutely Unique ID - Editable + public int MyConnectionUnique => _MyConnectionUnique; protected Connection() {/* require use of factory methods */ AddToCache(this); @@ -502,15 +398,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Connection() { _CountFinalized++; @@ -547,8 +439,6 @@ namespace VEPROMS.CSLA.Library } public static Connection New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Connection"); try { return DataPortal.Create(); @@ -613,8 +503,6 @@ namespace VEPROMS.CSLA.Library } public static Connection Get(int dbid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Connection"); try { Connection tmp = GetCachedByPrimaryKey(dbid); @@ -637,8 +525,6 @@ namespace VEPROMS.CSLA.Library } public static Connection GetByName(string name) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Connection"); try { Connection tmp = GetCachedByName(name); @@ -664,14 +550,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Connection(dr); return null; } - internal Connection(SafeDataReader dr) - { - ReadData(dr); - } + internal Connection(SafeDataReader dr) => ReadData(dr); public static void Delete(int dbid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Connection"); try { DataPortal.Delete(new PKCriteria(dbid)); @@ -683,12 +564,6 @@ namespace VEPROMS.CSLA.Library } public override Connection Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Connection"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Connection"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Connection"); try { BuildRefreshList(); @@ -708,24 +583,16 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DBID; - public int DBID - { get { return _DBID; } } - public PKCriteria(int dbid) - { - _DBID = dbid; - } + private readonly int _DBID; + public int DBID => _DBID; + public PKCriteria(int dbid) => _DBID = dbid; } [Serializable()] private class NameCriteria { - private string _Name; - public string Name - { get { return _Name; } } - public NameCriteria(string name) - { - _Name = name; - } + private readonly string _Name; + public string Name => _Name; + public NameCriteria(string name) => _Name = name; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -838,7 +705,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Connection.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -863,42 +730,50 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addConnection"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - cm.Parameters.AddWithValue("@ConnectionString", _ConnectionString); - cm.Parameters.AddWithValue("@ServerType", _ServerType); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_DBID = new SqlParameter("@newDBID", SqlDbType.Int); - param_DBID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_DBID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _DBID = (int)cm.Parameters["@newDBID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addConnection"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + cm.Parameters.AddWithValue("@ConnectionString", _ConnectionString); + cm.Parameters.AddWithValue("@ServerType", _ServerType); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_DBID = new SqlParameter("@newDBID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_DBID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _DBID = (int)cm.Parameters["@newDBID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_ConnectionFolders != null) _ConnectionFolders.Update(this); + _ConnectionFolders?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -908,7 +783,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Connection.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int dbid, string name, string title, string connectionString, int serverType, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Add", 0); @@ -928,11 +803,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_DBID = new SqlParameter("@newDBID", SqlDbType.Int); - param_DBID.Direction = ParameterDirection.Output; + SqlParameter param_DBID = new SqlParameter("@newDBID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_DBID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -947,7 +826,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Connection.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -970,44 +849,50 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateConnection"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@DBID", _DBID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - cm.Parameters.AddWithValue("@ConnectionString", _ConnectionString); - cm.Parameters.AddWithValue("@ServerType", _ServerType); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateConnection"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@DBID", _DBID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + cm.Parameters.AddWithValue("@ConnectionString", _ConnectionString); + cm.Parameters.AddWithValue("@ServerType", _ServerType); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_ConnectionFolders != null) _ConnectionFolders.Update(this); + _ConnectionFolders?.Update(this); } catch (Exception ex) { @@ -1018,19 +903,23 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Connection.Add(cn, ref _DBID, _Name, _Title, _ConnectionString, _ServerType, _Config, _DTS, _UsrID); - else - _LastChanged = Connection.Update(cn, ref _DBID, _Name, _Title, _ConnectionString, _ServerType, _Config, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Connection.Add(cn, ref _DBID, _Name, _Title, _ConnectionString, _ServerType, _Config, _DTS, _UsrID); + else + _LastChanged = Connection.Update(cn, ref _DBID, _Name, _Title, _ConnectionString, _ServerType, _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } - if (_ConnectionFolders != null) _ConnectionFolders.Update(this); + _ConnectionFolders?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int dbid, string name, string title, string connectionString, int serverType, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Update", 0); @@ -1052,8 +941,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1067,12 +958,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Connection.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_DBID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Delete", GetHashCode()); @@ -1097,7 +988,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Connection.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int dbid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Remove", 0); @@ -1138,16 +1029,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _DBID; + private readonly int _DBID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int dbid) - { - _DBID = dbid; - } + public bool Exists => _exists; + public ExistsCommand(int dbid) => _DBID = dbid; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Execute", GetHashCode()); @@ -1155,7 +1040,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1177,7 +1062,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ConnectionExtension _ConnectionExtension = new ConnectionExtension(); + readonly ConnectionExtension _ConnectionExtension = new ConnectionExtension(); [Serializable()] partial class ConnectionExtension : extensionBase { @@ -1186,18 +1071,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultServerType - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultServerType => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1226,10 +1102,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Connection) + if (destType == typeof(string) && value is Connection conn) { // Return the ToString value - return ((Connection)value).ToString(); + return conn.ToString(); } return base.ConvertTo(context, culture, value, destType); } @@ -1237,50 +1113,3 @@ namespace VEPROMS.CSLA.Library #endregion } // Namespace - -//// The following is a sample Extension File. You can use it to create ConnectionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Connection -// { -// partial class ConnectionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultServerType -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolder.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolder.cs index 09227cdd..02dc254b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolder.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolder.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _FolderID; [System.ComponentModel.DataObjectField(true, true)] public int FolderID @@ -255,19 +249,8 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ConnectionFolder - protected override object GetIdValue() - { - return MyConnectionFolderUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ConnectionFolder.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ConnectionFolder - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyConnectionFolderUnique; // Absolutely Unique ID + public override bool IsDirty { get @@ -282,18 +265,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyFolder != null && _MyFolder.IsDirtyList(list)); } + public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyFolder == null || _MyFolder.IsValidList(list)); } #endregion #region ValidationRules @@ -324,8 +304,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -363,86 +343,16 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} - #endregion - #region Authorization Rules - protected override void AddAuthorizationRules() - { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowRead(ParentID, ""); - //AuthorizationRules.AllowWrite(ParentID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowRead(ShortName, ""); - //AuthorizationRules.AllowWrite(ShortName, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowRead(ManualOrder, ""); - //AuthorizationRules.AllowWrite(ManualOrder, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ConnectionFolderUnique = 0; - private static int ConnectionFolderUnique - { get { return ++_ConnectionFolderUnique; } } - private int _MyConnectionFolderUnique = ConnectionFolderUnique; - public int MyConnectionFolderUnique // Absolutely Unique ID - Editable FK - { get { return _MyConnectionFolderUnique; } } - internal static ConnectionFolder New(Folder myParent, string name, string shortName) - { - return new ConnectionFolder(myParent, name, shortName); - } - internal static ConnectionFolder Get(SafeDataReader dr) - { - return new ConnectionFolder(dr); - } + private static int ConnectionFolderUnique => ++_ConnectionFolderUnique; + private readonly int _MyConnectionFolderUnique = ConnectionFolderUnique; + // Absolutely Unique ID - Editable FK + public int MyConnectionFolderUnique => _MyConnectionFolderUnique; + internal static ConnectionFolder New(Folder myParent, string name, string shortName) => new ConnectionFolder(myParent, name, shortName); + internal static ConnectionFolder Get(SafeDataReader dr) => new ConnectionFolder(dr); public ConnectionFolder() { MarkAsChild(); @@ -474,15 +384,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ConnectionFolder() { _CountFinalized++; @@ -522,33 +428,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Connection myConnection) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Folder.Add(cn, ref _FolderID, Folder.Get(_ParentID), myConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Folder.Add(cn, ref _FolderID, Folder.Get(_ParentID), myConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID); + } + MarkOld(); } internal void Update(Connection myConnection) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, myConnection.DBID, _Name, _Title, _ShortName, _FormatID, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, myConnection.DBID, _Name, _Title, _ShortName, _FormatID, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping myConnection for CSLA compliance")] internal void DeleteSelf(Connection myConnection) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Folder.Remove(cn, _FolderID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Folder.Remove(cn, _FolderID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ConnectionFolderExtension _ConnectionFolderExtension = new ConnectionFolderExtension(); + readonly ConnectionFolderExtension _ConnectionFolderExtension = new ConnectionFolderExtension(); [Serializable()] partial class ConnectionFolderExtension : extensionBase { @@ -557,22 +476,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultParentID - { - get { return 1; } - } - public virtual int DefaultDBID - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultParentID => 1; + public virtual int DefaultDBID => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -601,65 +508,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ConnectionFolder) + if (destType == typeof(string) && value is ConnectionFolder folder) { // Return the ToString value - return ((ConnectionFolder)value).ToString(); + return folder.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ConnectionFolderExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ConnectionFolder -// { -// partial class ConnectionFolderExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultParentID -// { -// get { return 1; } -// } -// public virtual int DefaultDBID -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolders.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolders.cs index 82458af8..149afade 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolders.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionFolders.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ConnectionFolder this[Folder myFolder] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ConnectionFolder this[Folder myFolder] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ConnectionFolder GetItem(Folder myFolder) + public new System.Collections.Generic.IList Items => base.Items; + public ConnectionFolder GetItem(Folder myFolder) { foreach (ConnectionFolder folder in this) if (folder.FolderID == myFolder.FolderID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ConnectionFolder Add(Folder myParent, string name, string shortName) // One to Many { ConnectionFolder folder = ConnectionFolder.New(myParent, name, shortName); - this.Add(folder); + Add(folder); return folder; } public void Remove(Folder myFolder) @@ -103,23 +95,19 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid - { - get { return IsValidList(new List()); } - } public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ConnectionFolder child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + { + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ConnectionFolder child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +125,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return (hasBrokenRules?.BrokenRules); } } - #endregion - #region Factory Methods - internal static ConnectionFolders New() - { - return new ConnectionFolders(); - } - internal static ConnectionFolders Get(SafeDataReader dr) - { - return new ConnectionFolders(dr); - } - public static ConnectionFolders GetByDBID(int dbid) + #endregion + #region Factory Methods + internal static ConnectionFolders New() => new ConnectionFolders(); + internal static ConnectionFolders Get(SafeDataReader dr) => new ConnectionFolders(dr); + public static ConnectionFolders GetByDBID(int dbid) { try { @@ -161,11 +143,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ConnectionFolders.GetByDBID", ex); } } - private ConnectionFolders() - { - MarkAsChild(); - } - internal ConnectionFolders(SafeDataReader dr) + private ConnectionFolders() => MarkAsChild(); + internal ConnectionFolders(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +153,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ConnectionFolders() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ConnectionFolders() { _CountFinalized++; } @@ -198,19 +173,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ConnectionFolder.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ConnectionFolder.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class DBIDCriteria { - public DBIDCriteria(int dbid) - { - _DBID = dbid; - } - private int _DBID; + public DBIDCriteria(int dbid) => _DBID = dbid; + private int _DBID; public int DBID { get { return _DBID; } @@ -219,7 +191,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(DBIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ConnectionFolders.DataPortal_FetchDBID", GetHashCode()); try { @@ -233,7 +205,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ConnectionFolder(dr)); + while (dr.Read()) Add(new ConnectionFolder(dr)); } } } @@ -243,11 +215,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ConnectionFolders.DataPortal_FetchDBID", ex); throw new DbCslaException("ConnectionFolders.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Connection connection) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +238,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ConnectionFoldersPropertyDescriptor pd = new ConnectionFoldersPropertyDescriptor(this, i); @@ -325,7 +286,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ConnectionFoldersPropertyDescriptor : vlnListPropertyDescriptor { - private ConnectionFolder Item { get { return (ConnectionFolder)_Item; } } public ConnectionFoldersPropertyDescriptor(ConnectionFolders collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +294,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ConnectionFolders) + if (destType == typeof(string) && value is ConnectionFolders folders) { // Return department and department role separated by comma. - return ((ConnectionFolders)value).Items.Count.ToString() + " Folders"; + return $"{folders.Items.Count} Folders"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfo.cs index 58f53517..0ad14d46 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ConnectionInfo : ReadOnlyBase, IDisposable { public event ConnectionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ConnectionInfo connectionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(connectionInfo)) _CacheList.Remove(connectionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Connection _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _DBID; [System.ComponentModel.DataObjectField(true, true)] public int DBID @@ -201,32 +185,19 @@ namespace VEPROMS.CSLA.Library foreach (ConnectionInfo tmp in _CacheByPrimaryKey[_DBID.ToString()]) tmp._ConnectionFolderCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base ConnectionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ConnectionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ConnectionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ConnectionInfo - protected override object GetIdValue() - { - return MyConnectionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyConnectionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ConnectionInfoUnique = 0; - private static int ConnectionInfoUnique - { get { return ++_ConnectionInfoUnique; } } - private int _MyConnectionInfoUnique = ConnectionInfoUnique; - public int MyConnectionInfoUnique // Absolutely Unique ID - Info - { get { return _MyConnectionInfoUnique; } } + private static int ConnectionInfoUnique => ++_ConnectionInfoUnique; + private readonly int _MyConnectionInfoUnique = ConnectionInfoUnique; + // Absolutely Unique ID - Info + public int MyConnectionInfoUnique => _MyConnectionInfoUnique; protected ConnectionInfo() {/* require use of factory methods */ AddToCache(this); @@ -235,15 +206,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ConnectionInfo() { _CountFinalized++; @@ -260,10 +227,7 @@ namespace VEPROMS.CSLA.Library if (listConnectionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(DBID.ToString()); // remove the list } - public virtual Connection Get() - { - return _Editable = Connection.Get(_DBID); - } + public virtual Connection Get() => _Editable = Connection.Get(_DBID); public static void Refresh(Connection tmp) { string key = tmp.DBID.ToString(); @@ -326,13 +290,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DBID; - public int DBID - { get { return _DBID; } } - public PKCriteria(int dbid) - { - _DBID = dbid; - } + private readonly int _DBID; + public int DBID => _DBID; + public PKCriteria(int dbid) => _DBID = dbid; } private void ReadData(SafeDataReader dr) { @@ -395,7 +355,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ConnectionInfoExtension _ConnectionInfoExtension = new ConnectionInfoExtension(); + readonly ConnectionInfoExtension _ConnectionInfoExtension = new ConnectionInfoExtension(); [Serializable()] partial class ConnectionInfoExtension : extensionBase { } [Serializable()] @@ -411,10 +371,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ConnectionInfo) + if (destType == typeof(string) && value is ConnectionInfo info) { // Return the ToString value - return ((ConnectionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfoList.cs index 4739144e..8f011843 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ConnectionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ConnectionInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ConnectionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ConnectionInfoList() { _CountFinalized++; } @@ -104,18 +97,6 @@ namespace VEPROMS.CSLA.Library { _ConnectionInfoList = null; } - // CSLATODO: Add alternative gets - - //public static ConnectionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ConnectionInfoList.Get", ex); - // } - //} private ConnectionInfoList() { /* require use of factory methods */ } #endregion @@ -149,41 +130,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +175,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ConnectionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ConnectionInfo Item { get { return (ConnectionInfo)_Item; } } public ConnectionInfoListPropertyDescriptor(ConnectionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +183,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ConnectionInfoList) + if (destType == typeof(string) && value is ConnectionInfoList list) { // Return department and department role separated by comma. - return ((ConnectionInfoList)value).Items.Count.ToString() + " Connections"; + return $"{list.Items.Count} Connections"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Content.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Content.cs index a2bc7db8..1b4c76fb 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Content.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Content.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -122,6 +120,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Content content) { @@ -131,6 +130,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(content)) _CacheList.Remove(content); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -159,15 +159,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextContentID = -1; - public static int NextContentID - { - get { return _nextContentID--; } - } + public static int NextContentID => _nextContentID--; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -369,10 +363,7 @@ namespace VEPROMS.CSLA.Library return _ContentDetails; } } - public void Reset_ContentDetails() - { - _ContentDetailCount = -1; - } + public void Reset_ContentDetails() => _ContentDetailCount = -1; private int _ContentEntryCount = 0; /// /// Count of ContentEntries for this Content @@ -564,10 +555,7 @@ namespace VEPROMS.CSLA.Library return _ContentRoUsages; } } - public void Reset_ContentRoUsages() - { - _ContentRoUsageCount = -1; - } + public void Reset_ContentRoUsages() => _ContentRoUsageCount = -1; private int _ContentTransitionCount = 0; /// /// Count of ContentTransitions for this Content @@ -601,10 +589,7 @@ namespace VEPROMS.CSLA.Library return _ContentTransitions; } } - public void Reset_ContentTransitions() - { - _ContentTransitionCount = -1; - } + public void Reset_ContentTransitions() => _ContentTransitionCount = -1; private int _ContentZContentCount = 0; /// /// Count of ContentZContents for this Content @@ -645,37 +630,21 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_ContentDetails == null ? false : _ContentDetails.IsDirtyList(list)) || (_MyEntry == null ? false : _MyEntry.IsDirtyList(list)) || (_MyGrid == null ? false : _MyGrid.IsDirtyList(list)) || (_MyImage == null ? false : _MyImage.IsDirtyList(list)) || (_ContentItems == null ? false : _ContentItems.IsDirtyList(list)) || (_ContentParts == null ? false : _ContentParts.IsDirtyList(list)) || (_ContentRoUsages == null ? false : _ContentRoUsages.IsDirtyList(list)) || (_ContentTransitions == null ? false : _ContentTransitions.IsDirtyList(list)) || (_MyZContent == null ? false : _MyZContent.IsDirtyList(list)) || (_MyFormat == null ? false : _MyFormat.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_ContentDetails != null && _ContentDetails.IsDirtyList(list)) || (_MyEntry != null && _MyEntry.IsDirtyList(list)) || (_MyGrid != null && _MyGrid.IsDirtyList(list)) || (_MyImage != null && _MyImage.IsDirtyList(list)) || (_ContentItems != null && _ContentItems.IsDirtyList(list)) || (_ContentParts != null && _ContentParts.IsDirtyList(list)) || (_ContentRoUsages != null && _ContentRoUsages.IsDirtyList(list)) || (_ContentTransitions != null && _ContentTransitions.IsDirtyList(list)) || (_MyZContent != null && _MyZContent.IsDirtyList(list)) || (_MyFormat != null && _MyFormat.IsDirtyList(list)); } public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_ContentDetails == null ? true : _ContentDetails.IsValidList(list)) && (_MyEntry == null ? true : _MyEntry.IsValidList(list)) && (_MyGrid == null ? true : _MyGrid.IsValidList(list)) && (_MyImage == null ? true : _MyImage.IsValidList(list)) && (_ContentItems == null ? true : _ContentItems.IsValidList(list)) && (_ContentParts == null ? true : _ContentParts.IsValidList(list)) && (_ContentRoUsages == null ? true : _ContentRoUsages.IsValidList(list)) && (_ContentTransitions == null ? true : _ContentTransitions.IsValidList(list)) && (_MyZContent == null ? true : _MyZContent.IsValidList(list)) && (_MyFormat == null ? true : _MyFormat.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_ContentDetails == null || _ContentDetails.IsValidList(list)) && (_MyEntry == null || _MyEntry.IsValidList(list)) && (_MyGrid == null || _MyGrid.IsValidList(list)) && (_MyImage == null || _MyImage.IsValidList(list)) && (_ContentItems == null || _ContentItems.IsValidList(list)) && (_ContentParts == null || _ContentParts.IsValidList(list)) && (_ContentRoUsages == null || _ContentRoUsages.IsValidList(list)) && (_ContentTransitions == null || _ContentTransitions.IsValidList(list)) && (_MyZContent == null || _MyZContent.IsValidList(list)) && (_MyFormat == null || _MyFormat.IsValidList(list)); } - // CSLATODO: Replace base Content.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Content - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Content.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Content - protected override object GetIdValue() - { - return MyContentUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyContentUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -713,8 +682,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -742,37 +711,11 @@ namespace VEPROMS.CSLA.Library _ContentExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(Number, ""); - //AuthorizationRules.AllowRead(Text, ""); - //AuthorizationRules.AllowRead(Type, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(Number, ""); - //AuthorizationRules.AllowWrite(Text, ""); - //AuthorizationRules.AllowWrite(Type, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _ContentExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -780,63 +723,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ContentExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _ContentDetailCount; - usedByCount += _ContentEntryCount; - usedByCount += _ContentGridCount; - usedByCount += _ContentImageCount; - usedByCount += _ContentItemCount; - usedByCount += _ContentPartCount; - usedByCount += _ContentRoUsageCount; - usedByCount += _ContentTransitionCount; - usedByCount += _ContentZContentCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ContentUnique = 0; - protected static int ContentUnique - { get { return ++_ContentUnique; } } - private int _MyContentUnique = ContentUnique; - public int MyContentUnique // Absolutely Unique ID - Editable - { get { return _MyContentUnique; } } + protected static int ContentUnique => ++_ContentUnique; + private readonly int _MyContentUnique = ContentUnique; + // Absolutely Unique ID - Editable + public int MyContentUnique => _MyContentUnique; protected Content() {/* require use of factory methods */ AddToCache(this); @@ -850,15 +744,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Content() { _CountFinalized++; @@ -891,26 +781,6 @@ namespace VEPROMS.CSLA.Library _MyGrid = null; } _Text = null; - //if (_ContentDetails != null) - // _ContentDetails = null; - //if (_ContentItems != null) - //{ - // _ContentItems = null; - // //foreach (ContentItem ci in _ContentItems) - // // ci.Dispose(); - //} - //if (_ContentRoUsages != null) - //{ - // //foreach (ContentRoUsage cr in _ContentRoUsages) - // // cr.Dispose(); - // _ContentRoUsages = null; - //} - //if (_ContentTransitions != null) - //{ - // foreach (ContentTransition ct in _ContentTransitions) - // ct.Dispose(); - // _ContentTransitions = null; - //} } private void RemoveFromDictionaries() { @@ -925,8 +795,6 @@ namespace VEPROMS.CSLA.Library } public static Content New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Content"); try { return DataPortal.Create(); @@ -992,8 +860,6 @@ namespace VEPROMS.CSLA.Library } public static Content Get(int contentID, bool forcerefresh = false) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Content"); try { //C2019-036 View Only mode work with Checked Out Procedures @@ -1028,14 +894,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Content(dr); return null; } - internal Content(SafeDataReader dr) - { - ReadData(dr); - } + internal Content(SafeDataReader dr) => ReadData(dr); public static void Delete(int contentID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Content"); try { DataPortal.Delete(new PKCriteria(contentID)); @@ -1047,12 +908,6 @@ namespace VEPROMS.CSLA.Library } public override Content Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Content"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Content"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Content"); try { BuildRefreshList(); @@ -1072,13 +927,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -1186,7 +1037,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Content.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -1211,51 +1062,59 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyFormat != null) _MyFormat.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyFormat?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addContent"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@Number", _Number); - cm.Parameters.AddWithValue("@Text", _Text); - cm.Parameters.AddWithValue("@Type", _Type); - cm.Parameters.AddWithValue("@FormatID", FormatID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_ContentID = new SqlParameter("@newContentID", SqlDbType.Int); - param_ContentID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ContentID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _ContentID = (int)cm.Parameters["@newContentID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addContent"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@Number", _Number); + cm.Parameters.AddWithValue("@Text", _Text); + cm.Parameters.AddWithValue("@Type", _Type); + cm.Parameters.AddWithValue("@FormatID", FormatID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_ContentID = new SqlParameter("@newContentID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ContentID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _ContentID = (int)cm.Parameters["@newContentID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_ContentItems != null) _ContentItems.Update(this); - if (_ContentDetails != null) _ContentDetails.Update(this); - if (_MyEntry != null) _MyEntry.Update(this); - if (_MyGrid != null) _MyGrid.Update(this); - if (_MyImage != null) _MyImage.Update(this); - if (_ContentParts != null) _ContentParts.Update(this); - if (_ContentRoUsages != null) _ContentRoUsages.Update(this); - if (_ContentTransitions != null) _ContentTransitions.Update(this); - if (_MyZContent != null) _MyZContent.Update(this); + _ContentItems?.Update(this); + _ContentDetails?.Update(this); + _MyEntry?.Update(this); + _MyGrid?.Update(this); + _MyImage?.Update(this); + _ContentParts?.Update(this); + _ContentRoUsages?.Update(this); + _ContentTransitions?.Update(this); + _MyZContent?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -1265,7 +1124,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Content.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int contentID, string number, string text, int? type, Format myFormat, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Add", 0); @@ -1285,11 +1144,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_ContentID = new SqlParameter("@newContentID", SqlDbType.Int); - param_ContentID.Direction = ParameterDirection.Output; + SqlParameter param_ContentID = new SqlParameter("@newContentID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_ContentID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1304,7 +1167,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Content.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1327,54 +1190,60 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.SQLUpdate", GetHashCode()); try { - if (_MyFormat != null) _MyFormat.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyFormat?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - //Volian.Base.Library.vlnStackTrace.ShowStackLocal("ContentID={0}", _ContentID.ToString()); - cm.CommandText = "updateContent"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@Number", _Number); - cm.Parameters.AddWithValue("@Text", _Text); - cm.Parameters.AddWithValue("@Type", _Type); - cm.Parameters.AddWithValue("@FormatID", FormatID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + //Volian.Base.Library.vlnStackTrace.ShowStackLocal("ContentID={0}", _ContentID.ToString()); + cm.CommandText = "updateContent"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@Number", _Number); + cm.Parameters.AddWithValue("@Text", _Text); + cm.Parameters.AddWithValue("@Type", _Type); + cm.Parameters.AddWithValue("@FormatID", FormatID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_ContentItems != null) _ContentItems.Update(this); - if (_ContentDetails != null) _ContentDetails.Update(this); - if (_MyEntry != null) _MyEntry.Update(this); - if (_MyGrid != null) _MyGrid.Update(this); - if (_MyImage != null) _MyImage.Update(this); - if (_ContentParts != null) _ContentParts.Update(this); - if (_ContentRoUsages != null) _ContentRoUsages.Update(this); - if (_ContentTransitions != null) _ContentTransitions.Update(this); - if (_MyZContent != null) _MyZContent.Update(this); + _ContentItems?.Update(this); + _ContentDetails?.Update(this); + _MyEntry?.Update(this); + _MyGrid?.Update(this); + _MyImage?.Update(this); + _ContentParts?.Update(this); + _ContentRoUsages?.Update(this); + _ContentTransitions?.Update(this); + _MyZContent?.Update(this); } catch (Exception ex) { @@ -1385,27 +1254,31 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Content.Add(cn, ref _ContentID, _Number, _Text, _Type, _MyFormat, _Config, _DTS, _UserID); - else - _LastChanged = Content.Update(cn, ref _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Content.Add(cn, ref _ContentID, _Number, _Text, _Type, _MyFormat, _Config, _DTS, _UserID); + else + _LastChanged = Content.Update(cn, ref _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_ContentItems != null) _ContentItems.Update(this); - if (_ContentDetails != null) _ContentDetails.Update(this); - if (_MyEntry != null) _MyEntry.Update(this); - if (_MyGrid != null) _MyGrid.Update(this); - if (_MyImage != null) _MyImage.Update(this); - if (_ContentParts != null) _ContentParts.Update(this); - if (_ContentRoUsages != null) _ContentRoUsages.Update(this); - if (_ContentTransitions != null) _ContentTransitions.Update(this); - if (_MyZContent != null) _MyZContent.Update(this); + _ContentItems?.Update(this); + _ContentDetails?.Update(this); + _MyEntry?.Update(this); + _MyGrid?.Update(this); + _MyImage?.Update(this); + _ContentParts?.Update(this); + _ContentRoUsages?.Update(this); + _ContentTransitions?.Update(this); + _MyZContent?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Update", 0); @@ -1427,8 +1300,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1442,12 +1317,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Content.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_ContentID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_ContentID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Delete", GetHashCode()); @@ -1472,7 +1344,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Content.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int contentID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Remove", 0); @@ -1513,16 +1385,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ContentID; + private readonly int _ContentID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int contentID) - { - _ContentID = contentID; - } + public bool Exists => _exists; + public ExistsCommand(int contentID) => _ContentID = contentID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Execute", GetHashCode()); @@ -1530,7 +1396,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1552,7 +1418,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ContentExtension _ContentExtension = new ContentExtension(); + readonly ContentExtension _ContentExtension = new ContentExtension(); [Serializable()] partial class ContentExtension : extensionBase { @@ -1561,14 +1427,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1597,10 +1457,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Content) + if (destType == typeof(string) && value is Content content) { // Return the ToString value - return ((Content)value).ToString(); + return content.ToString(); } return base.ConvertTo(context, culture, value, destType); } @@ -1608,46 +1468,3 @@ namespace VEPROMS.CSLA.Library #endregion } // Namespace - -//// The following is a sample Extension File. You can use it to create ContentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Content -// { -// partial class ContentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentAudit.cs index 183ae941..2baaaa7b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshContentAudits.Add(this); } - private void ClearRefreshList() - { - _RefreshContentAudits = new List(); - } + private void ClearRefreshList() => _RefreshContentAudits = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -55,7 +50,8 @@ namespace VEPROMS.CSLA.Library ClearRefreshList(); } #endregion - #region Collection + #region + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ContentAudit contentAudit) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(contentAudit)) _CacheList.Remove(contentAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -275,40 +266,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base ContentAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ContentAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check ContentAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentAudit - protected override object GetIdValue() - { - return MyContentAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyContentAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -336,8 +301,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -365,41 +330,11 @@ namespace VEPROMS.CSLA.Library _ContentAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(Number, ""); - //AuthorizationRules.AllowRead(Text, ""); - //AuthorizationRules.AllowRead(Type, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(Number, ""); - //AuthorizationRules.AllowWrite(Text, ""); - //AuthorizationRules.AllowWrite(Type, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); _ContentAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -407,42 +342,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ContentAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ContentAuditUnique = 0; - protected static int ContentAuditUnique - { get { return ++_ContentAuditUnique; } } - private int _MyContentAuditUnique = ContentAuditUnique; - public int MyContentAuditUnique // Absolutely Unique ID - Editable - { get { return _MyContentAuditUnique; } } + protected static int ContentAuditUnique => ++_ContentAuditUnique; + private readonly int _MyContentAuditUnique = ContentAuditUnique; + // Absolutely Unique ID - Editable + public int MyContentAuditUnique => _MyContentAuditUnique; protected ContentAudit() {/* require use of factory methods */ AddToCache(this); @@ -451,15 +358,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentAudit() { _CountFinalized++; @@ -484,8 +387,6 @@ namespace VEPROMS.CSLA.Library } public static ContentAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ContentAudit"); try { return DataPortal.Create(); @@ -536,8 +437,6 @@ namespace VEPROMS.CSLA.Library } public static ContentAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ContentAudit"); try { ContentAudit tmp = GetCachedByPrimaryKey(auditID); @@ -563,14 +462,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new ContentAudit(dr); return null; } - internal ContentAudit(SafeDataReader dr) - { - ReadData(dr); - } + internal ContentAudit(SafeDataReader dr) => ReadData(dr); public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ContentAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -582,12 +476,6 @@ namespace VEPROMS.CSLA.Library } public override ContentAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ContentAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ContentAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ContentAudit"); try { BuildRefreshList(); @@ -607,13 +495,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -685,7 +569,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -710,37 +594,43 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addContentAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@Number", _Number); - cm.Parameters.AddWithValue("@Text", _Text); - cm.Parameters.AddWithValue("@Type", _Type); - cm.Parameters.AddWithValue("@FormatID", _FormatID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addContentAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@Number", _Number); + cm.Parameters.AddWithValue("@Text", _Text); + cm.Parameters.AddWithValue("@Type", _Type); + cm.Parameters.AddWithValue("@FormatID", _FormatID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.SQLInsert", GetHashCode()); @@ -752,7 +642,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Add", 0); @@ -774,8 +664,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -790,7 +682,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -813,38 +705,42 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateContentAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@Number", _Number); - cm.Parameters.AddWithValue("@Text", _Text); - cm.Parameters.AddWithValue("@Type", _Type); - cm.Parameters.AddWithValue("@FormatID", _FormatID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateContentAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@Number", _Number); + cm.Parameters.AddWithValue("@Text", _Text); + cm.Parameters.AddWithValue("@Type", _Type); + cm.Parameters.AddWithValue("@FormatID", _FormatID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -857,18 +753,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - ContentAudit.Add(cn, ref _AuditID, _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, _DeleteStatus); - else - ContentAudit.Update(cn, ref _AuditID, _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, _DeleteStatus); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + ContentAudit.Add(cn, ref _AuditID, _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, _DeleteStatus); + else + ContentAudit.Update(cn, ref _AuditID, _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, _DeleteStatus); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Update", 0); @@ -903,12 +803,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.DataPortal_Delete", GetHashCode()); @@ -933,7 +833,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ContentAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Remove", 0); @@ -959,7 +859,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ContentAuditExtension _ContentAuditExtension = new ContentAuditExtension(); + readonly ContentAuditExtension _ContentAuditExtension = new ContentAuditExtension(); [Serializable()] partial class ContentAuditExtension : extensionBase { @@ -996,49 +896,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentAudit) + if (destType == typeof(string) && value is ContentAudit audit) { // Return the ToString value - return ((ContentAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ContentAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ContentAudit -// { -// partial class ContentAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfo.cs index 6d63a93e..6fb89c78 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ContentAuditInfo : ReadOnlyBase, IDisposable { public event ContentAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ContentAuditInfo contentAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(contentAuditInfo)) _CacheList.Remove(contentAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ContentAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -180,32 +164,19 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base ContentAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ContentAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ContentAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentAuditInfo - protected override object GetIdValue() - { - return MyContentAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyContentAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ContentAuditInfoUnique = 0; - private static int ContentAuditInfoUnique - { get { return ++_ContentAuditInfoUnique; } } - private int _MyContentAuditInfoUnique = ContentAuditInfoUnique; - public int MyContentAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyContentAuditInfoUnique; } } + private static int ContentAuditInfoUnique => ++_ContentAuditInfoUnique; + private readonly int _MyContentAuditInfoUnique = ContentAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyContentAuditInfoUnique => _MyContentAuditInfoUnique; protected ContentAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -214,15 +185,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentAuditInfo() { _CountFinalized++; @@ -239,10 +206,7 @@ namespace VEPROMS.CSLA.Library if (listContentAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual ContentAudit Get() - { - return _Editable = ContentAudit.Get(_AuditID); - } + public virtual ContentAudit Get() => _Editable = ContentAudit.Get(_AuditID); public static void Refresh(ContentAudit tmp) { string key = tmp.AuditID.ToString(); @@ -307,13 +271,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -377,7 +337,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ContentAuditInfoExtension _ContentAuditInfoExtension = new ContentAuditInfoExtension(); + readonly ContentAuditInfoExtension _ContentAuditInfoExtension = new ContentAuditInfoExtension(); [Serializable()] partial class ContentAuditInfoExtension : extensionBase { } [Serializable()] @@ -393,10 +353,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentAuditInfo) + if (destType == typeof(string) && value is ContentAuditInfo info) { // Return the ToString value - return ((ContentAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfoList.cs index b2287e3b..527b48a7 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ContentAuditInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ContentAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentAuditInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentAuditInfoList.Get", ex); } } - /// - /// Reset the list of all ContentAuditInfo. - /// - public static void Reset() - { - _ContentAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ContentAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ContentAuditInfoList.Get", ex); - // } - //} - private ContentAuditInfoList() + /// + /// Reset the list of all ContentAuditInfo. + /// + public static void Reset() => _ContentAuditInfoList = null; + private ContentAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ContentAuditInfo Item { get { return (ContentAuditInfo)_Item; } } public ContentAuditInfoListPropertyDescriptor(ContentAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentAuditInfoList) + if (destType == typeof(string) && value is ContentAuditInfoList list) { // Return department and department role separated by comma. - return ((ContentAuditInfoList)value).Items.Count.ToString() + " ContentAudits"; + return $"{list.Items.Count} ContentAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetail.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetail.cs index 87b465ec..e6b14362 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetail.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetail.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _DetailID; [System.ComponentModel.DataObjectField(true, true)] public int DetailID @@ -174,17 +168,19 @@ namespace VEPROMS.CSLA.Library { get { return base.IsDirty; } } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping with CSLA")] public bool IsDirtyList(List list) { return base.IsDirty; } public override bool IsValid { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } + get { return (IsNew && !IsDirty) || base.IsValid; } } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping with CSLA")] public bool IsValidList(List list) { - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; } #endregion #region ValidationRules @@ -213,8 +209,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -295,7 +291,7 @@ namespace VEPROMS.CSLA.Library private static int _ContentDetailUnique = 0; private static int ContentDetailUnique { get { return ++_ContentDetailUnique; } } - private int _MyContentDetailUnique = ContentDetailUnique; + private readonly int _MyContentDetailUnique = ContentDetailUnique; public int MyContentDetailUnique // Absolutely Unique ID - Editable FK { get { return _MyContentDetailUnique; } } internal static ContentDetail New(int itemType, string text) @@ -336,7 +332,7 @@ namespace VEPROMS.CSLA.Library private static int _CountFinalized = 0; private static int IncrementCountCreated { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; public static int CountCreated { get { return _CountCreated; } } public static int CountNotDisposed @@ -378,33 +374,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Detail.Add(cn, ref _DetailID, myContent, _ItemType, _Text, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Detail.Add(cn, ref _DetailID, myContent, _ItemType, _Text, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Detail.Update(cn, ref _DetailID, myContent.ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Detail.Update(cn, ref _DetailID, myContent.ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping with CSLA")] internal void DeleteSelf(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Detail.Remove(cn, _DetailID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Detail.Remove(cn, _DetailID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ContentDetailExtension _ContentDetailExtension = new ContentDetailExtension(); + readonly ContentDetailExtension _ContentDetailExtension = new ContentDetailExtension(); [Serializable()] partial class ContentDetailExtension : extensionBase { @@ -449,10 +458,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentDetail) + if (destType == typeof(string) && value is ContentDetail detail) { // Return the ToString value - return ((ContentDetail)value).ToString(); + return detail.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetails.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetails.cs index fc42bd09..7a8ba337 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetails.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentDetails.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ContentDetail this[Detail myDetail] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ContentDetail this[Detail myDetail] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ContentDetail GetItem(Detail myDetail) + public new System.Collections.Generic.IList Items => base.Items; + public ContentDetail GetItem(Detail myDetail) { foreach (ContentDetail detail in this) if (detail.DetailID == myDetail.DetailID) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ContentDetail child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ContentDetail child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return (hasBrokenRules?.BrokenRules); } } - #endregion - #region Factory Methods - internal static ContentDetails New() - { - return new ContentDetails(); - } - internal static ContentDetails Get(SafeDataReader dr) - { - return new ContentDetails(dr); - } - public static ContentDetails GetByContentID(int contentID) + #endregion + #region Factory Methods + internal static ContentDetails New() => new ContentDetails(); + internal static ContentDetails Get(SafeDataReader dr) => new ContentDetails(dr); + public static ContentDetails GetByContentID(int contentID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentDetails.GetByContentID", ex); } } - private ContentDetails() - { - MarkAsChild(); - } - internal ContentDetails(SafeDataReader dr) + private ContentDetails() => MarkAsChild(); + internal ContentDetails(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ContentDetails() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentDetails() { _CountFinalized++; } @@ -206,11 +182,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -269,41 +242,30 @@ namespace VEPROMS.CSLA.Library this.RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentDetailsPropertyDescriptor : vlnListPropertyDescriptor { - private ContentDetail Item { get { return (ContentDetail)_Item; } } public ContentDetailsPropertyDescriptor(ContentDetails collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentDetails) + if (destType == typeof(string) && value is ContentDetails details) { // Return department and department role separated by comma. - return ((ContentDetails)value).Items.Count.ToString() + " Details"; + return $"{details.Items.Count} Details"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfo.cs index 58d49b91..346df3c0 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,16 +26,13 @@ namespace VEPROMS.CSLA.Library public partial class ContentInfo : ReadOnlyBase, IDisposable { public static event ContentInfoEvent InfoChanged; - private void OnInfoChanged(ContentInfo contentInfo) - { - if (InfoChanged != null) - InfoChanged(this); - } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + private void OnInfoChanged(ContentInfo contentInfo) => InfoChanged?.Invoke(this); public event ContentInfoEvent Changed; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] private void OnChange(ContentInfo contentInfo) { - if (Changed != null) - Changed(this); + Changed?.Invoke(this); OnInfoChanged(this); } private void OnChange() @@ -53,6 +48,7 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ContentInfo contentInfo) { @@ -62,6 +58,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(contentInfo)) _CacheList.Remove(contentInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -104,21 +101,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Content _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -518,24 +502,12 @@ namespace VEPROMS.CSLA.Library return _MyZContent; } } - // CSLATODO: Replace base ContentInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ContentInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ContentInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentInfo - protected override object GetIdValue() - { - return MyContentInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyContentInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ContentInfoUnique = 0; @@ -549,9 +521,9 @@ namespace VEPROMS.CSLA.Library return ui; } } - private int _MyContentInfoUnique = ContentInfoUnique; - public int MyContentInfoUnique // Absolutely Unique ID - Info - { get { return _MyContentInfoUnique; } } + private readonly int _MyContentInfoUnique = ContentInfoUnique; + // Absolutely Unique ID - Info + public int MyContentInfoUnique => _MyContentInfoUnique; protected ContentInfo() {/* require use of factory methods */ AddToCache(this); @@ -560,15 +532,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentInfo() { _CountFinalized++; @@ -606,25 +574,8 @@ namespace VEPROMS.CSLA.Library if (_ContentItems != null) _ContentItems = null; _Text = null; - //if (_ContentParts != null) - // _ContentParts = null; - //if (_ContentRoUsages != null) - // _ContentRoUsages = null; - //if (_ContentTransitions != null) - // _ContentTransitions = null; - //if (_MyEntry != null) - // _MyEntry = null; - //if (_MyGrid != null) - // _MyGrid = null; - //if (_MyImage != null) - // _MyImage = null; - //if (_MyZContent != null) - // _MyZContent = null; - } - public virtual Content Get() - { - return _Editable = Content.Get(_ContentID); } + public virtual Content Get() => _Editable = Content.Get(_ContentID); public static void Refresh(Content tmp) { string key = tmp.ContentID.ToString(); @@ -675,11 +626,11 @@ namespace VEPROMS.CSLA.Library _Type = tmp.Type; if (_FormatID != tmp.FormatID) { - if (MyFormat != null) MyFormat.RefreshFormatContents(); // Update List for old value + MyFormat?.RefreshFormatContents(); // Update List for old value _FormatID = tmp.FormatID; // Update the value } _MyFormat = null; // Reset list so that the next line gets a new list - if (MyFormat != null) MyFormat.RefreshFormatContents(); // Update List for new value + MyFormat?.RefreshFormatContents(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -716,8 +667,6 @@ namespace VEPROMS.CSLA.Library } public static ContentInfo Get(int contentID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Content"); try { ContentInfo tmp = GetCachedByPrimaryKey(contentID); @@ -756,13 +705,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } private void ReadData(SafeDataReader dr) { @@ -834,7 +779,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ContentInfoExtension _ContentInfoExtension = new ContentInfoExtension(); + readonly ContentInfoExtension _ContentInfoExtension = new ContentInfoExtension(); [Serializable()] partial class ContentInfoExtension : extensionBase { } [Serializable()] @@ -850,10 +795,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentInfo) + if (destType == typeof(string) && value is ContentInfo info) { // Return the ToString value - return ((ContentInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfoList.cs index cb156688..9a53a9be 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ContentInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~ContentInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentInfoList.Get", ex); } } - /// - /// Reset the list of all ContentInfo. - /// - public static void Reset() - { - _ContentInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ContentInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ContentInfoList.Get", ex); - // } - //} - public static ContentInfoList GetByFormatID(int? formatID) + /// + /// Reset the list of all ContentInfo. + /// + public static void Reset() => _ContentInfoList = null; + public static ContentInfoList GetByFormatID(int? formatID) { try { @@ -166,11 +144,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class FormatIDCriteria { - public FormatIDCriteria(int? formatID) - { - _FormatID = formatID; - } - private int? _FormatID; + public FormatIDCriteria(int? formatID) => _FormatID = formatID; + private int? _FormatID; public int? FormatID { get { return _FormatID; } @@ -207,41 +182,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -263,7 +227,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ContentInfo Item { get { return (ContentInfo)_Item; } } public ContentInfoListPropertyDescriptor(ContentInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -272,10 +235,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentInfoList) + if (destType == typeof(string) && value is ContentInfoList list) { // Return department and department role separated by comma. - return ((ContentInfoList)value).Items.Count.ToString() + " Contents"; + return $"{list.Items.Count} Contents"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentItem.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentItem.cs index 815a68f7..c8a38497 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentItem.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentItem.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ItemID; [System.ComponentModel.DataObjectField(true, true)] public int ItemID @@ -131,10 +125,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentItem - protected override object GetIdValue() - { - return MyContentItemUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyContentItemUnique; // Absolutely Unique ID // CSLATODO: Replace base ContentItem.ToString function as necessary /// /// Overrides Base ToString @@ -144,22 +135,12 @@ namespace VEPROMS.CSLA.Library //{ // return base.ToString(); //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -188,8 +169,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -201,74 +182,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(PreviousID, ""); - //AuthorizationRules.AllowWrite(PreviousID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ContentItemUnique = 0; - private static int ContentItemUnique - { get { return ++_ContentItemUnique; } } - private int _MyContentItemUnique = ContentItemUnique; - public int MyContentItemUnique // Absolutely Unique ID - Editable FK - { get { return _MyContentItemUnique; } } - internal static ContentItem New() - { - return new ContentItem(); - } - internal static ContentItem Get(SafeDataReader dr) - { - return new ContentItem(dr); - } + private static int ContentItemUnique => ++_ContentItemUnique; + private readonly int _MyContentItemUnique = ContentItemUnique; + // Absolutely Unique ID - Editable FK + public int MyContentItemUnique => _MyContentItemUnique; + internal static ContentItem New() => new ContentItem(); + internal static ContentItem Get(SafeDataReader dr) => new ContentItem(dr); public ContentItem() { MarkAsChild(); @@ -286,15 +215,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentItem() { _CountFinalized++; @@ -328,33 +253,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Item.Add(cn, ref _ItemID, Item.Get((int)_PreviousID), myContent, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Item.Add(cn, ref _ItemID, Item.Get((int)_PreviousID), myContent, _DTS, _UserID); + } + MarkOld(); } internal void Update(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, myContent.ContentID, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, myContent.ContentID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Item.Remove(cn, _ItemID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Item.Remove(cn, _ItemID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ContentItemExtension _ContentItemExtension = new ContentItemExtension(); + readonly ContentItemExtension _ContentItemExtension = new ContentItemExtension(); [Serializable()] partial class ContentItemExtension : extensionBase { @@ -363,14 +301,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -399,57 +331,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentItem) + if (destType == typeof(string) && value is ContentItem item) { // Return the ToString value - return ((ContentItem)value).ToString(); + return item.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ContentItemExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ContentItem -// { -// partial class ContentItemExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentItems.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentItems.cs index 0d55b0e1..94d6a3e5 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentItems.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentItems.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ContentItem this[Item myItem] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ContentItem this[Item myItem] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ContentItem GetItem(Item myItem) + public new System.Collections.Generic.IList Items => base.Items; + public ContentItem GetItem(Item myItem) { foreach (ContentItem item in this) if (item.ItemID == myItem.ItemID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ContentItem Add() // One to Many { ContentItem item = ContentItem.New(); - this.Add(item); + Add(item); return item; } public void Remove(Item myItem) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ContentItem child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ContentItem child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ContentItems New() - { - return new ContentItems(); - } - internal static ContentItems Get(SafeDataReader dr) - { - return new ContentItems(dr); - } - public static ContentItems GetByContentID(int contentID) + #endregion + #region Factory Methods + internal static ContentItems New() => new ContentItems(); + internal static ContentItems Get(SafeDataReader dr) => new ContentItems(dr); + public static ContentItems GetByContentID(int contentID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentItems.GetByContentID", ex); } } - private ContentItems() - { - MarkAsChild(); - } - internal ContentItems(SafeDataReader dr) + private ContentItems() => MarkAsChild(); + internal ContentItems(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ContentItems() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentItems() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ContentItem.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ContentItem.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentItems.DataPortal_FetchContentID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ContentItem(dr)); + while (dr.Read()) Add(new ContentItem(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentItems.DataPortal_FetchContentID", ex); throw new DbCslaException("ContentItems.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Content content) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ContentItemsPropertyDescriptor pd = new ContentItemsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentItemsPropertyDescriptor : vlnListPropertyDescriptor { - private ContentItem Item { get { return (ContentItem)_Item; } } public ContentItemsPropertyDescriptor(ContentItems collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentItems) + if (destType == typeof(string) && value is ContentItems items) { // Return department and department role separated by comma. - return ((ContentItems)value).Items.Count.ToString() + " Items"; + return $"{items.Items.Count} Items"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentPart.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentPart.cs index 7a139983..147f7bb6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentPart.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentPart.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _FromType; [System.ComponentModel.DataObjectField(true, true)] public int FromType @@ -155,10 +149,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentPart - protected override object GetIdValue() - { - return MyContentPartUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyContentPartUnique; // Absolutely Unique ID // CSLATODO: Replace base ContentPart.ToString function as necessary /// /// Overrides Base ToString @@ -182,18 +173,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyItem == null ? false : _MyItem.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyItem != null && _MyItem.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyItem == null ? true : _MyItem.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyItem == null || _MyItem.IsValidList(list)); } #endregion #region ValidationRules @@ -223,8 +211,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -246,74 +234,21 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FromType, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ContentPartUnique = 0; - private static int ContentPartUnique - { get { return ++_ContentPartUnique; } } - private int _MyContentPartUnique = ContentPartUnique; - public int MyContentPartUnique // Absolutely Unique ID - Editable FK - { get { return _MyContentPartUnique; } } - internal static ContentPart New(int fromType, Item myItem) - { - return new ContentPart(fromType, myItem); - } - internal static ContentPart Get(SafeDataReader dr) - { - return new ContentPart(dr); - } + private static int ContentPartUnique => ++_ContentPartUnique; + private readonly int _MyContentPartUnique = ContentPartUnique; + // Absolutely Unique ID - Editable FK + public int MyContentPartUnique => _MyContentPartUnique; + internal static ContentPart New(int fromType, Item myItem) => new ContentPart(fromType, myItem); + internal static ContentPart Get(SafeDataReader dr) => new ContentPart(dr); public ContentPart() { MarkAsChild(); @@ -341,15 +276,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentPart() { _CountFinalized++; @@ -392,33 +323,45 @@ namespace VEPROMS.CSLA.Library internal void Insert(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Part.Add(cn, myContent, _FromType, _MyItem, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Part.Add(cn, myContent, _FromType, _MyItem, _DTS, _UserID); + } + MarkOld(); } internal void Update(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Part.Update(cn, myContent.ContentID, _FromType, _ItemID, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Part.Update(cn, myContent.ContentID, _FromType, _ItemID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } internal void DeleteSelf(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Part.Remove(cn, myContent.ContentID, _FromType); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Part.Remove(cn, myContent.ContentID, _FromType); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ContentPartExtension _ContentPartExtension = new ContentPartExtension(); + readonly ContentPartExtension _ContentPartExtension = new ContentPartExtension(); [Serializable()] partial class ContentPartExtension : extensionBase { @@ -427,14 +370,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -463,57 +400,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentPart) + if (destType == typeof(string) && value is ContentPart part) { // Return the ToString value - return ((ContentPart)value).ToString(); + return part.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ContentPartExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ContentPart -// { -// partial class ContentPartExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentParts.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentParts.cs index 08abc267..06af1884 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentParts.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentParts.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public new ContentPart this[int fromType] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public new ContentPart this[int fromType] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ContentPart GetItem(int fromType) + public new System.Collections.Generic.IList Items => base.Items; + public ContentPart GetItem(int fromType) { foreach (ContentPart part in this) if (part.FromType == fromType) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(fromType)) { ContentPart part = ContentPart.New(fromType, myItem); - this.Add(part); + Add(part); return part; } else @@ -108,11 +100,8 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { // run through all the child objects // and if any are invalid then the @@ -142,20 +131,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ContentParts New() - { - return new ContentParts(); - } - internal static ContentParts Get(SafeDataReader dr) - { - return new ContentParts(dr); - } - public static ContentParts GetByContentID(int contentID) + #endregion + #region Factory Methods + internal static ContentParts New() => new ContentParts(); + internal static ContentParts Get(SafeDataReader dr) => new ContentParts(dr); + public static ContentParts GetByContentID(int contentID) { try { @@ -166,11 +149,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentParts.GetByContentID", ex); } } - private ContentParts() - { - MarkAsChild(); - } - internal ContentParts(SafeDataReader dr) + private ContentParts() => MarkAsChild(); + internal ContentParts(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -179,16 +159,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ContentParts() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentParts() { _CountFinalized++; } @@ -203,19 +179,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ContentPart.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ContentPart.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -224,7 +197,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentParts.DataPortal_FetchContentID", GetHashCode()); try { @@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ContentPart(dr)); + while (dr.Read()) Add(new ContentPart(dr)); } } } @@ -248,11 +221,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentParts.DataPortal_FetchContentID", ex); throw new DbCslaException("ContentParts.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Content content) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -271,49 +244,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ContentPartsPropertyDescriptor pd = new ContentPartsPropertyDescriptor(this, i); @@ -330,7 +292,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentPartsPropertyDescriptor : vlnListPropertyDescriptor { - private ContentPart Item { get { return (ContentPart)_Item; } } public ContentPartsPropertyDescriptor(ContentParts collection, int index) : base(collection, index) { ;} } #endregion @@ -339,10 +300,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentParts) + if (destType == typeof(string) && value is ContentParts parts) { // Return department and department role separated by comma. - return ((ContentParts)value).Items.Count.ToString() + " Parts"; + return $"{parts.Items.Count} Parts"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsage.cs index 4451517d..f951e9bf 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsage.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int ROUsageID @@ -232,19 +226,8 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentRoUsage - protected override object GetIdValue() - { - return MyContentRoUsageUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ContentRoUsage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ContentRoUsage - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyContentRoUsageUnique; // Absolutely Unique ID + public override bool IsDirty { get @@ -259,18 +242,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRODb != null && _MyRODb.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRODb == null || _MyRODb.IsValidList(list)); } #endregion #region ValidationRules @@ -300,8 +280,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -331,78 +311,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ROUsageID, ""); - //AuthorizationRules.AllowRead(ROID, ""); - //AuthorizationRules.AllowWrite(ROID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowWrite(RODbID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ContentRoUsageUnique = 0; - private static int ContentRoUsageUnique - { get { return ++_ContentRoUsageUnique; } } - private int _MyContentRoUsageUnique = ContentRoUsageUnique; - public int MyContentRoUsageUnique // Absolutely Unique ID - Editable FK - { get { return _MyContentRoUsageUnique; } } - internal static ContentRoUsage New(string roid, RODb myRODb) - { - return new ContentRoUsage(roid, myRODb); - } - internal static ContentRoUsage Get(SafeDataReader dr) - { - return new ContentRoUsage(dr); - } + private static int ContentRoUsageUnique => ++_ContentRoUsageUnique; + private readonly int _MyContentRoUsageUnique = ContentRoUsageUnique; + // Absolutely Unique ID - Editable FK + public int MyContentRoUsageUnique => _MyContentRoUsageUnique; + internal static ContentRoUsage New(string roid, RODb myRODb) => new ContentRoUsage(roid, myRODb); + internal static ContentRoUsage Get(SafeDataReader dr) => new ContentRoUsage(dr); public ContentRoUsage() { MarkAsChild(); @@ -431,15 +355,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentRoUsage() { _CountFinalized++; @@ -481,33 +401,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = RoUsage.Add(cn, ref _ROUsageID, myContent, _ROID, _Config, _DTS, _UserID, _MyRODb); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = RoUsage.Add(cn, ref _ROUsageID, myContent, _ROID, _Config, _DTS, _UserID, _MyRODb); + } + MarkOld(); } internal void Update(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = RoUsage.Update(cn, ref _ROUsageID, myContent.ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = RoUsage.Update(cn, ref _ROUsageID, myContent.ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - RoUsage.Remove(cn, _ROUsageID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + RoUsage.Remove(cn, _ROUsageID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ContentRoUsageExtension _ContentRoUsageExtension = new ContentRoUsageExtension(); + readonly ContentRoUsageExtension _ContentRoUsageExtension = new ContentRoUsageExtension(); [Serializable()] partial class ContentRoUsageExtension : extensionBase { @@ -516,18 +449,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultContentID - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultContentID => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -556,61 +480,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentRoUsage) + if (destType == typeof(string) && value is ContentRoUsage usage) { // Return the ToString value - return ((ContentRoUsage)value).ToString(); + return usage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ContentRoUsageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ContentRoUsage -// { -// partial class ContentRoUsageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultContentID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsages.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsages.cs index 68ed89ba..39839c01 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsages.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentRoUsages.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ContentRoUsage this[RoUsage myRoUsage] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ContentRoUsage this[RoUsage myRoUsage] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ContentRoUsage GetItem(RoUsage myRoUsage) + public new System.Collections.Generic.IList Items => base.Items; + public ContentRoUsage GetItem(RoUsage myRoUsage) { foreach (ContentRoUsage roUsage in this) if (roUsage.ROUsageID == myRoUsage.ROUsageID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ContentRoUsage Add(string roid, RODb myRODb) // One to Many { ContentRoUsage roUsage = ContentRoUsage.New(roid, myRODb); - this.Add(roUsage); + Add(roUsage); return roUsage; } public void Remove(RoUsage myRoUsage) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ContentRoUsage child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ContentRoUsage child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ContentRoUsages New() - { - return new ContentRoUsages(); - } - internal static ContentRoUsages Get(SafeDataReader dr) - { - return new ContentRoUsages(dr); - } - public static ContentRoUsages GetByContentID(int contentID) + #endregion + #region Factory Methods + internal static ContentRoUsages New() => new ContentRoUsages(); + internal static ContentRoUsages Get(SafeDataReader dr) => new ContentRoUsages(dr); + public static ContentRoUsages GetByContentID(int contentID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentRoUsages.GetByContentID", ex); } } - private ContentRoUsages() - { - MarkAsChild(); - } - internal ContentRoUsages(SafeDataReader dr) + private ContentRoUsages() => MarkAsChild(); + internal ContentRoUsages(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ContentRoUsages() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentRoUsages() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ContentRoUsage.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ContentRoUsage.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentRoUsages.DataPortal_FetchContentID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ContentRoUsage(dr)); + while (dr.Read()) Add(new ContentRoUsage(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentRoUsages.DataPortal_FetchContentID", ex); throw new DbCslaException("ContentRoUsages.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Content content) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ContentRoUsagesPropertyDescriptor pd = new ContentRoUsagesPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentRoUsagesPropertyDescriptor : vlnListPropertyDescriptor { - private ContentRoUsage Item { get { return (ContentRoUsage)_Item; } } public ContentRoUsagesPropertyDescriptor(ContentRoUsages collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentRoUsages) + if (destType == typeof(string) && value is ContentRoUsages usages) { // Return department and department role separated by comma. - return ((ContentRoUsages)value).Items.Count.ToString() + " RoUsages"; + return $"{usages.Items.Count} RoUsages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransition.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransition.cs index a730f992..2487c0c8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransition.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransition.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -32,11 +29,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -295,19 +289,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ContentTransition - protected override object GetIdValue() - { - return MyContentTransitionUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ContentTransition.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ContentTransition - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyContentTransitionUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -322,18 +304,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyItemToID == null ? false : _MyItemToID.IsDirtyList(list)) || (_MyItemRangeID == null ? false : _MyItemRangeID.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyItemToID != null && _MyItemToID.IsDirtyList(list)) || (_MyItemRangeID != null && _MyItemRangeID.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyItemToID == null ? true : _MyItemToID.IsValidList(list)) && (_MyItemRangeID == null ? true : _MyItemRangeID.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyItemToID == null || _MyItemToID.IsValidList(list)) && (_MyItemRangeID == null || _MyItemRangeID.IsValidList(list)); } #endregion #region ValidationRules @@ -364,8 +343,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -400,82 +379,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(TransitionID, ""); - //AuthorizationRules.AllowRead(ToID, ""); - //AuthorizationRules.AllowWrite(ToID, ""); - //AuthorizationRules.AllowRead(RangeID, ""); - //AuthorizationRules.AllowWrite(RangeID, ""); - //AuthorizationRules.AllowRead(IsRange, ""); - //AuthorizationRules.AllowWrite(IsRange, ""); - //AuthorizationRules.AllowRead(TranType, ""); - //AuthorizationRules.AllowWrite(TranType, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ContentTransitionUnique = 0; - private static int ContentTransitionUnique - { get { return ++_ContentTransitionUnique; } } - private int _MyContentTransitionUnique = ContentTransitionUnique; - public int MyContentTransitionUnique // Absolutely Unique ID - Editable FK - { get { return _MyContentTransitionUnique; } } - internal static ContentTransition New(Item myItemToID, Item myItemRangeID) - { - return new ContentTransition(myItemToID, myItemRangeID); - } - internal static ContentTransition Get(SafeDataReader dr) - { - return new ContentTransition(dr); - } + private static int ContentTransitionUnique => ++_ContentTransitionUnique; + private readonly int _MyContentTransitionUnique = ContentTransitionUnique; + // Absolutely Unique ID - Editable FK + public int MyContentTransitionUnique => _MyContentTransitionUnique; + internal static ContentTransition New(Item myItemToID, Item myItemRangeID) => new ContentTransition(myItemToID, myItemRangeID); + internal static ContentTransition Get(SafeDataReader dr) => new ContentTransition(dr); public ContentTransition() { MarkAsChild(); @@ -508,15 +427,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ContentTransition() { _CountFinalized++; @@ -562,39 +477,52 @@ namespace VEPROMS.CSLA.Library internal void Insert(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - string pattern = string.Format(@"( [0-9]*){{1,2}}\[END>", _TransitionID); - Match m = Regex.Match(myContent.Text, pattern); - if (m.Groups.Count > 1 && m.Groups[1].Value.ToUpper().Contains("(PAGE ~)")) // B2020-089, check for upper case Page ~ in case step was upper cased - _Config = ""; - else - _Config = string.Empty; - _LastChanged = Transition.Add(cn, ref _TransitionID, myContent, _MyItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + string pattern = string.Format(@"( [0-9]*){{1,2}}\[END>", _TransitionID); + Match m = Regex.Match(myContent.Text, pattern); + if (m.Groups.Count > 1 && m.Groups[1].Value.ToUpper().Contains("(PAGE ~)")) // B2020-089, check for upper case Page ~ in case step was upper cased + _Config = ""; + else + _Config = string.Empty; + _LastChanged = Transition.Add(cn, ref _TransitionID, myContent, _MyItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Transition.Update(cn, ref _TransitionID, myContent.ContentID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Transition.Update(cn, ref _TransitionID, myContent.ContentID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Content myContent) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Transition.Remove(cn, _TransitionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Transition.Remove(cn, _TransitionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ContentTransitionExtension _ContentTransitionExtension = new ContentTransitionExtension(); + readonly ContentTransitionExtension _ContentTransitionExtension = new ContentTransitionExtension(); [Serializable()] partial class ContentTransitionExtension : extensionBase { @@ -603,22 +531,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultIsRange - { - get { return 0; } - } - public virtual int DefaultTranType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultIsRange => 0; + public virtual int DefaultTranType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -647,65 +563,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentTransition) + if (destType == typeof(string) && value is ContentTransition transition) { // Return the ToString value - return ((ContentTransition)value).ToString(); + return transition.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ContentTransitionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ContentTransition -// { -// partial class ContentTransitionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultIsRange -// { -// get { return 0; } -// } -// public virtual int DefaultTranType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransitions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransitions.cs index c763c610..05bdbf8f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransitions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ContentTransitions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ContentTransition this[Transition myTransition] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ContentTransition this[Transition myTransition] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ContentTransition GetItem(Transition myTransition) + public new System.Collections.Generic.IList Items => base.Items; + public ContentTransition GetItem(Transition myTransition) { foreach (ContentTransition transition in this) if (transition.TransitionID == myTransition.TransitionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ContentTransition Add(Item myItemToID, Item myItemRangeID) // One to Many { ContentTransition transition = ContentTransition.New(myItemToID, myItemRangeID); - this.Add(transition); + Add(transition); return transition; } public void Remove(Transition myTransition) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ContentTransition child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ContentTransition child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ContentTransitions New() - { - return new ContentTransitions(); - } - internal static ContentTransitions Get(SafeDataReader dr) - { - return new ContentTransitions(dr); - } - public static ContentTransitions GetByFromID(int fromID) + #endregion + #region Factory Methods + internal static ContentTransitions New() => new ContentTransitions(); + internal static ContentTransitions Get(SafeDataReader dr) => new ContentTransitions(dr); + public static ContentTransitions GetByFromID(int fromID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ContentTransitions.GetByFromID", ex); } } - private ContentTransitions() - { - MarkAsChild(); - } - internal ContentTransitions(SafeDataReader dr) + private ContentTransitions() => MarkAsChild(); + internal ContentTransitions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ContentTransitions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ContentTransitions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ContentTransition.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ContentTransition.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class FromIDCriteria { - public FromIDCriteria(int fromID) - { - _FromID = fromID; - } - private int _FromID; + public FromIDCriteria(int fromID) => _FromID = fromID; + private int _FromID; public int FromID { get { return _FromID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FromIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentTransitions.DataPortal_FetchFromID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ContentTransition(dr)); + while (dr.Read()) Add(new ContentTransition(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentTransitions.DataPortal_FetchFromID", ex); throw new DbCslaException("ContentTransitions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Content content) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ContentTransitionsPropertyDescriptor pd = new ContentTransitionsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ContentTransitionsPropertyDescriptor : vlnListPropertyDescriptor { - private ContentTransition Item { get { return (ContentTransition)_Item; } } public ContentTransitionsPropertyDescriptor(ContentTransitions collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ContentTransitions) + if (destType == typeof(string) && value is ContentTransitions transitions) { // Return department and department role separated by comma. - return ((ContentTransitions)value).Items.Count.ToString() + " Transitions"; + return $"{transitions.Items.Count} Transitions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DROUsage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DROUsage.cs index 37121afd..24c5cfa6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DROUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DROUsage.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -58,6 +56,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DROUsage dROUsage) { @@ -67,6 +66,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(dROUsage)) _CacheList.Remove(dROUsage); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,15 +92,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextDROUsageID = -1; - public static int NextDROUsageID - { - get { return _nextDROUsageID--; } - } + public static int NextDROUsageID => _nextDROUsageID--; private int _DROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int DROUsageID @@ -261,7 +255,7 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)) || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); + return base.IsDirty || (_MyDocument != null && _MyDocument.IsDirtyList(list)) || (_MyRODb != null && _MyRODb.IsDirtyList(list)); } public override bool IsValid { @@ -270,28 +264,16 @@ namespace VEPROMS.CSLA.Library public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocument == null || _MyDocument.IsValidList(list)) && (_MyRODb == null || _MyRODb.IsValidList(list)); } - // CSLATODO: Replace base DROUsage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DROUsage - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DROUsage.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DROUsage - protected override object GetIdValue() - { - return MyDROUsageUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDROUsageUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -321,8 +303,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -369,35 +351,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DROUsageID, ""); - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowRead(ROID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowWrite(DocID, ""); - //AuthorizationRules.AllowWrite(ROID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(RODbID, ""); _DROUsageExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -405,42 +363,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _DROUsageExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DROUsageUnique = 0; - protected static int DROUsageUnique - { get { return ++_DROUsageUnique; } } - private int _MyDROUsageUnique = DROUsageUnique; - public int MyDROUsageUnique // Absolutely Unique ID - Editable - { get { return _MyDROUsageUnique; } } + protected static int DROUsageUnique => ++_DROUsageUnique; + private readonly int _MyDROUsageUnique = DROUsageUnique; + // Absolutely Unique ID - Editable + public int MyDROUsageUnique => _MyDROUsageUnique; protected DROUsage() {/* require use of factory methods */ AddToCache(this); @@ -449,15 +379,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DROUsage() { _CountFinalized++; @@ -482,8 +408,6 @@ namespace VEPROMS.CSLA.Library } public static DROUsage New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a DROUsage"); try { return DataPortal.Create(); @@ -554,8 +478,6 @@ namespace VEPROMS.CSLA.Library } public static DROUsage Get(int dROUsageID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a DROUsage"); try { DROUsage tmp = GetCachedByPrimaryKey(dROUsageID); @@ -581,14 +503,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new DROUsage(dr); return null; } - internal DROUsage(SafeDataReader dr) - { - ReadData(dr); - } + internal DROUsage(SafeDataReader dr) => ReadData(dr); public static void Delete(int dROUsageID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a DROUsage"); try { DataPortal.Delete(new PKCriteria(dROUsageID)); @@ -600,12 +517,6 @@ namespace VEPROMS.CSLA.Library } public override DROUsage Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a DROUsage"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a DROUsage"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a DROUsage"); try { BuildRefreshList(); @@ -625,13 +536,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DROUsageID; - public int DROUsageID - { get { return _DROUsageID; } } - public PKCriteria(int dROUsageID) - { - _DROUsageID = dROUsageID; - } + private readonly int _DROUsageID; + public int DROUsageID => _DROUsageID; + public PKCriteria(int dROUsageID) => _DROUsageID = dROUsageID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -703,7 +610,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DROUsage.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -728,40 +635,48 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyDocument != null) _MyDocument.Update(); - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyDocument?.Update(); + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addDROUsage"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@DocID", DocID); - cm.Parameters.AddWithValue("@ROID", _ROID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@RODbID", RODbID); - // Output Calculated Columns - SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int); - param_DROUsageID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_DROUsageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _DROUsageID = (int)cm.Parameters["@newDROUsageID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addDROUsage"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@DocID", DocID); + cm.Parameters.AddWithValue("@ROID", _ROID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@RODbID", RODbID); + // Output Calculated Columns + SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_DROUsageID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _DROUsageID = (int)cm.Parameters["@newDROUsageID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.SQLInsert", GetHashCode()); @@ -773,7 +688,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DROUsage.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int dROUsageID, Document myDocument, string roid, string config, DateTime dts, string userID, RODb myRODb) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Add", 0); @@ -792,11 +707,15 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID); // Output Calculated Columns - SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int); - param_DROUsageID.Direction = ParameterDirection.Output; + SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_DROUsageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -811,7 +730,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DROUsage.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -834,42 +753,48 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.SQLUpdate", GetHashCode()); try { - if (_MyDocument != null) _MyDocument.Update(); - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyDocument?.Update(); + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateDROUsage"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@DROUsageID", _DROUsageID); - cm.Parameters.AddWithValue("@DocID", DocID); - cm.Parameters.AddWithValue("@ROID", _ROID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - cm.Parameters.AddWithValue("@RODbID", RODbID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateDROUsage"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@DROUsageID", _DROUsageID); + cm.Parameters.AddWithValue("@DocID", DocID); + cm.Parameters.AddWithValue("@ROID", _ROID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + cm.Parameters.AddWithValue("@RODbID", RODbID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -882,18 +807,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = DROUsage.Add(cn, ref _DROUsageID, _MyDocument, _ROID, _Config, _DTS, _UserID, _MyRODb); - else - _LastChanged = DROUsage.Update(cn, ref _DROUsageID, _DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = DROUsage.Add(cn, ref _DROUsageID, _MyDocument, _ROID, _Config, _DTS, _UserID, _MyRODb); + else + _LastChanged = DROUsage.Update(cn, ref _DROUsageID, _DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int dROUsageID, int docID, string roid, string config, DateTime dts, string userID, ref byte[] lastChanged, int rODbID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Update", 0); @@ -914,8 +843,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@RODbID", rODbID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -929,12 +860,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DROUsage.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_DROUsageID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_DROUsageID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Delete", GetHashCode()); @@ -959,7 +887,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DROUsage.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int dROUsageID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Remove", 0); @@ -1000,16 +928,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _DROUsageID; + private readonly int _DROUsageID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int dROUsageID) - { - _DROUsageID = dROUsageID; - } + public bool Exists => _exists; + public ExistsCommand(int dROUsageID) => _DROUsageID = dROUsageID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Execute", GetHashCode()); @@ -1017,7 +939,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1039,7 +961,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - DROUsageExtension _DROUsageExtension = new DROUsageExtension(); + readonly DROUsageExtension _DROUsageExtension = new DROUsageExtension(); [Serializable()] partial class DROUsageExtension : extensionBase { @@ -1048,18 +970,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultDocID - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultDocID => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1088,61 +1001,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DROUsage) + if (destType == typeof(string) && value is DROUsage usage) { // Return the ToString value - return ((DROUsage)value).ToString(); + return usage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DROUsageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DROUsage -// { -// partial class DROUsageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultDocID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfo.cs index db731e11..e352cf6e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class DROUsageInfo : ReadOnlyBase, IDisposable { public event DROUsageInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DROUsageInfo dROUsageInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(dROUsageInfo)) _CacheList.Remove(dROUsageInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected DROUsage _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _DROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int DROUsageID @@ -175,32 +159,19 @@ namespace VEPROMS.CSLA.Library return _MyRODb; } } - // CSLATODO: Replace base DROUsageInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DROUsageInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DROUsageInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DROUsageInfo - protected override object GetIdValue() - { - return MyDROUsageInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDROUsageInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _DROUsageInfoUnique = 0; - private static int DROUsageInfoUnique - { get { return ++_DROUsageInfoUnique; } } - private int _MyDROUsageInfoUnique = DROUsageInfoUnique; - public int MyDROUsageInfoUnique // Absolutely Unique ID - Info - { get { return _MyDROUsageInfoUnique; } } + private static int DROUsageInfoUnique => ++_DROUsageInfoUnique; + private readonly int _MyDROUsageInfoUnique = DROUsageInfoUnique; + // Absolutely Unique ID - Info + public int MyDROUsageInfoUnique => _MyDROUsageInfoUnique; protected DROUsageInfo() {/* require use of factory methods */ AddToCache(this); @@ -209,15 +180,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DROUsageInfo() { _CountFinalized++; @@ -234,10 +201,7 @@ namespace VEPROMS.CSLA.Library if (listDROUsageInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(DROUsageID.ToString()); // remove the list } - public virtual DROUsage Get() - { - return _Editable = DROUsage.Get(_DROUsageID); - } + public virtual DROUsage Get() => _Editable = DROUsage.Get(_DROUsageID); public static void Refresh(DROUsage tmp) { string key = tmp.DROUsageID.ToString(); @@ -250,22 +214,22 @@ namespace VEPROMS.CSLA.Library { if (_DocID != tmp.DocID) { - if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for old value + MyDocument?.RefreshDocumentDROUsages(); // Update List for old value _DocID = tmp.DocID; // Update the value } _MyDocument = null; // Reset list so that the next line gets a new list - if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for new value + MyDocument?.RefreshDocumentDROUsages(); // Update List for new value _ROID = tmp.ROID; _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; if (_RODbID != tmp.RODbID) { - if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for old value + MyRODb?.RefreshRODbDROUsages(); // Update List for old value _RODbID = tmp.RODbID; // Update the value } _MyRODb = null; // Reset list so that the next line gets a new list - if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for new value + MyRODb?.RefreshRODbDROUsages(); // Update List for new value _DROUsageInfoExtension.Refresh(this); OnChange();// raise an event } @@ -285,11 +249,11 @@ namespace VEPROMS.CSLA.Library _UserID = tmp.UserID; if (_RODbID != tmp.RODbID) { - if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for old value + MyRODb?.RefreshRODbDROUsages(); // Update List for old value _RODbID = tmp.RODbID; // Update the value } _MyRODb = null; // Reset list so that the next line gets a new list - if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for new value + MyRODb?.RefreshRODbDROUsages(); // Update List for new value _DROUsageInfoExtension.Refresh(this); OnChange();// raise an event } @@ -305,11 +269,11 @@ namespace VEPROMS.CSLA.Library { if (_DocID != tmp.DocID) { - if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for old value + MyDocument?.RefreshDocumentDROUsages(); // Update List for old value _DocID = tmp.DocID; // Update the value } _MyDocument = null; // Reset list so that the next line gets a new list - if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for new value + MyDocument?.RefreshDocumentDROUsages(); // Update List for new value _ROID = tmp.ROID; _Config = tmp.Config; _DTS = tmp.DTS; @@ -319,8 +283,6 @@ namespace VEPROMS.CSLA.Library } public static DROUsageInfo Get(int dROUsageID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a DROUsage"); try { DROUsageInfo tmp = GetCachedByPrimaryKey(dROUsageID); @@ -359,13 +321,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DROUsageID; - public int DROUsageID - { get { return _DROUsageID; } } - public PKCriteria(int dROUsageID) - { - _DROUsageID = dROUsageID; - } + private readonly int _DROUsageID; + public int DROUsageID => _DROUsageID; + public PKCriteria(int dROUsageID) => _DROUsageID = dROUsageID; } private void ReadData(SafeDataReader dr) { @@ -426,7 +384,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - DROUsageInfoExtension _DROUsageInfoExtension = new DROUsageInfoExtension(); + readonly DROUsageInfoExtension _DROUsageInfoExtension = new DROUsageInfoExtension(); [Serializable()] partial class DROUsageInfoExtension : extensionBase { } [Serializable()] @@ -442,10 +400,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DROUsageInfo) + if (destType == typeof(string) && value is DROUsageInfo info) { // Return the ToString value - return ((DROUsageInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfoList.cs index 9b844706..8ba44d7b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DROUsageInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (DROUsageInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~DROUsageInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DROUsageInfoList() { _CountFinalized++; } @@ -97,26 +90,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DROUsageInfoList.Get", ex); } } - /// - /// Reset the list of all DROUsageInfo. - /// - public static void Reset() - { - _DROUsageInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static DROUsageInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on DROUsageInfoList.Get", ex); - // } - //} - public static DROUsageInfoList GetByDocID(int docID) + /// + /// Reset the list of all DROUsageInfo. + /// + public static void Reset() => _DROUsageInfoList = null; + + public static DROUsageInfoList GetByDocID(int docID) { try { @@ -150,7 +129,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -164,7 +143,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DROUsageInfo(dr)); + while (dr.Read()) Add(new DROUsageInfo(dr)); IsReadOnly = true; } } @@ -175,16 +154,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class DocIDCriteria { - public DocIDCriteria(int docID) - { - _DocID = docID; - } - private int _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + private int _DocID; public int DocID { get { return _DocID; } @@ -193,7 +169,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(DocIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_FetchDocID", GetHashCode()); try { @@ -208,7 +184,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DROUsageInfo(dr)); + while (dr.Read()) Add(new DROUsageInfo(dr)); IsReadOnly = true; } } @@ -219,16 +195,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_FetchDocID", ex); throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -237,7 +210,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_FetchRODbID", GetHashCode()); try { @@ -252,7 +225,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DROUsageInfo(dr)); + while (dr.Read()) Add(new DROUsageInfo(dr)); IsReadOnly = true; } } @@ -263,48 +236,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_FetchRODbID", ex); throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DROUsageInfoListPropertyDescriptor pd = new DROUsageInfoListPropertyDescriptor(this, i); @@ -321,7 +283,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DROUsageInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private DROUsageInfo Item { get { return (DROUsageInfo)_Item; } } public DROUsageInfoListPropertyDescriptor(DROUsageInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +291,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DROUsageInfoList) + if (destType == typeof(string) && value is DROUsageInfoList list) { // Return department and department role separated by comma. - return ((DROUsageInfoList)value).Items.Count.ToString() + " DROUsages"; + return $"{list.Items.Count} DROUsages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Database.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Database.cs index 7cc80a48..2903211b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Database.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Database.cs @@ -15,7 +15,6 @@ using Csla; using Csla.Data; using System.Configuration; using System.IO; -using System.ComponentModel; using System.Diagnostics; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -35,79 +34,76 @@ namespace VEPROMS.CSLA.Library private static string _DBServer = null; private static DateTime _RevDate=DateTime.MinValue; -public static DateTime RevDate -{ - get { return Database._RevDate; } - set { Database._RevDate = value; } -} + public static DateTime RevDate + { + get { return _RevDate; } + set { _RevDate = value; } + } private static string _RevDescription= "Unknown"; -public static string RevDescription -{ - get { return Database._RevDescription; } - set { Database._RevDescription = value; } -} -public static string DBServer -{ - get - { - if (_DBServer == null) + public static string RevDescription { - string cnstr = null; - try + get { return _RevDescription; } + set { _RevDescription = value; } + } + public static string DBServer + { + get { - using (SqlConnection cn = Database.VEPROMS_SqlConnection) + if (_DBServer == null) { - cnstr = cn.ConnectionString; + string cnstr = null; try { - using (SqlCommand cmd = new SqlCommand("vesp_GetSQLCodeRevision", cn)) + using (SqlConnection cn = VEPROMS_SqlConnection) { - cmd.CommandType = CommandType.StoredProcedure; - cmd.CommandTimeout = 0; - SqlDataReader dr = cmd.ExecuteReader(); - while (dr.Read()) + cnstr = cn.ConnectionString; + try { - _RevDate = dr.GetDateTime(0); - _RevDescription = dr.GetString(1); + using (SqlCommand cmd = new SqlCommand("vesp_GetSQLCodeRevision", cn)) + { + cmd.CommandType = CommandType.StoredProcedure; + cmd.CommandTimeout = 0; + SqlDataReader dr = cmd.ExecuteReader(); + while (dr.Read()) + { + _RevDate = dr.GetDateTime(0); + _RevDescription = dr.GetString(1); + } + } } + catch (Exception) + { + _RevDate = DateTime.MinValue; + _RevDescription = "Unknown"; + } + string server = ""; + string db = ""; + Match m = Regex.Match(cnstr, "Data Source=([^;]+)(;[^;]+)*;*Initial Catalog=([^;]+)(;[^;]+)*"); + if (m.Success && m.Groups.Count > 4) + { + server = m.Groups[1].Value; + db = m.Groups[3].Value; + } + _DBServer = string.Format("{0} - {1} [SQL:{2:yyMM.ddHH}]", server, db, RevDate); } } - catch (Exception ex) + catch (Exception) { - _RevDate = DateTime.MinValue; - _RevDescription = "Unknown"; + _DBServer = cnstr; } - string server = ""; - string db = ""; - Match m = Regex.Match(cnstr, "Data Source=([^;]+)(;[^;]+)*;*Initial Catalog=([^;]+)(;[^;]+)*"); - if (m.Success && m.Groups.Count > 4) - { - server = m.Groups[1].Value; - db = m.Groups[3].Value; - } - _DBServer = string.Format("{0} - {1} [SQL:{2:yyMM.ddHH}]", server, db, RevDate); } - } - catch (Exception) - { - _DBServer = cnstr; + return _DBServer; } } - return _DBServer; - } -} private static int _DefaultTimeout = 600; // 600 seconds, i.e. 10 minutes public static int DefaultTimeout { get { return _DefaultTimeout; } set { _DefaultTimeout = value; } } - public static int SQLTimeout - { - get { return _DefaultTimeout/20; } - } - public static void LogException(string s, Exception ex) + public static int SQLTimeout => _DefaultTimeout / 20; + public static void LogException(string s, Exception ex) { int i = 0; Console.WriteLine("Error - {0}", s); @@ -122,7 +118,7 @@ public static string DBServer get { return _LoggingInfo; } set { _LoggingInfo = value; } } - static System.Diagnostics.Process _CurrentProcess = System.Diagnostics.Process.GetCurrentProcess(); + static readonly System.Diagnostics.Process _CurrentProcess = Process.GetCurrentProcess(); public static void LogInfo(string s, int hashCode) { if (_LoggingInfo) @@ -136,8 +132,8 @@ public static string DBServer private static string _ConnectionName = "VEPROMS"; public static string ConnectionName { - get { return Database._ConnectionName; } - set { Database._ConnectionName = value; _VEPROMS_Connection = null; /* Reset Connection */ } + get { return _ConnectionName; } + set { _ConnectionName = value; _VEPROMS_Connection = null; /* Reset Connection */ } } private static bool _TrackDBUsage = false; public static bool TrackDBUsage @@ -145,7 +141,8 @@ public static string DBServer get { return _TrackDBUsage; } set { _TrackDBUsage = value; } } - private static Dictionary _Methods = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary _Methods = new Dictionary(); public static void ShowDBTracking(string fileName) { DebugDBTrack.Open(VlnSettings.TemporaryFolder + "\\" + fileName); @@ -159,12 +156,7 @@ public static string DBServer { if (TrackDBUsage) { - string str = Volian.Base.Library.vlnStackTrace.CalledFromCSLA; - //if (str.Contains("ItemAndChildren")) - //{ - // ShowDictionary(Methods); - // Methods = new Dictionary(); - //} + string str = vlnStackTrace.CalledFromCSLA; if (!_Methods.ContainsKey(str)) _Methods.Add(str, 1); else @@ -177,7 +169,7 @@ public static string DBServer DateTime.Today.ToLongDateString(); // If DBConnection.XML exists, use the connection string from DBConnection.XML string cnOverride = System.Windows.Forms.Application.StartupPath + @"\DBConnection.XML"; - if (System.IO.File.Exists(cnOverride)) + if (File.Exists(cnOverride)) { System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.Load(cnOverride); @@ -209,12 +201,8 @@ public static string DBServer } } // Otherwise get the value from the ConfigurationManager - ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[ConnectionName]; - if (cs == null) - { - throw new ApplicationException("Database.cs Could not find connection " + ConnectionName); - } - string constr = FixServer(cs.ConnectionString); + ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[ConnectionName] ?? throw new ApplicationException("Database.cs Could not find connection " + ConnectionName); + string constr = FixServer(cs.ConnectionString); if (constr.Contains("{MENU}")) { constr = ChooseDatabase(constr); @@ -240,10 +228,10 @@ public static string DBServer } private static string FixServer(string connectionString) { - string serverName = Volian.Base.Library.VlnSettings.GetServer(); + string serverName = VlnSettings.GetServer(); if (serverName != null && serverName != "") { - System.Text.RegularExpressions.Match mServer = System.Text.RegularExpressions.Regex.Match(connectionString, ".*Data Source=([^;]*).*"); + System.Text.RegularExpressions.Match mServer = Regex.Match(connectionString, ".*Data Source=([^;]*).*"); if (mServer.Success) { connectionString = connectionString.Substring(0, mServer.Groups[1].Index) + serverName + connectionString.Substring(mServer.Groups[1].Index + mServer.Groups[1].Length); @@ -254,24 +242,22 @@ public static string DBServer private static string _SelectedDatabase; public static string SelectedDatabase { - get { return Database._SelectedDatabase; } - set { Database._SelectedDatabase = value; } + get { return _SelectedDatabase; } + set { _SelectedDatabase = value; } } public static string ActiveDatabase { get { - string activeDatabase = SelectedDatabase; - if(activeDatabase == null) - activeDatabase = Regex.Replace(VEPROMS_Connection, "^.*Initial Catalog=([^;]*);.*$", "$1", RegexOptions.IgnoreCase); - return activeDatabase; + string activeDatabase = SelectedDatabase ?? Regex.Replace(VEPROMS_Connection, "^.*Initial Catalog=([^;]*);.*$", "$1", RegexOptions.IgnoreCase); + return activeDatabase; } } private static string _LastDatabase="NoDefault"; public static string LastDatabase { - get { return Database._LastDatabase; } - set { Database._LastDatabase = value; } + get { return _LastDatabase; } + set { _LastDatabase = value; } } private static string ChooseDatabase(string constr) { @@ -300,95 +286,98 @@ public static string DBServer return constr.Replace("{MENU}", _SelectedDatabase); } private static System.Windows.Forms.ContextMenuStrip BuildDatabaseMenu(string constr) - { - string tmp = constr.Replace("{MENU}", "master"); - SqlConnection cn = new SqlConnection(tmp); - cn.Open(); - // SqlDataAdapter da = new SqlDataAdapter("select name from sysdatabases where name like 'VEP%' order by name", cn); - //SqlDataAdapter da = new SqlDataAdapter("select name, case when object_id('[' + name + ']..Items') is null then 'Not PROMS' when object_id('[' + name + ']..Revisions') is not null then 'Approval' when object_id('[' + name + ']..ContentAudits') is not null then 'Change Manager' else 'Original' end functionality from sysdatabases where name not in ('master','model','msdb','tempdb') order by name", cn); - SqlDataAdapter da = new SqlDataAdapter("select name, 'Approval' functionality from sysdatabases where name not in ('master','model','msdb','tempdb') order by name", cn); - da.SelectCommand.CommandTimeout = 300; // 300 sec timeout - DataSet ds = new DataSet(); - try - { - da.Fill(ds); - } - catch (Exception ex) - { - System.Windows.Forms.MessageBox.Show(ex.GetType().Name, ex.Message); - throw(new Exception("Cannot Load Data List",ex)); - } - cn.Close(); - System.Windows.Forms.ContextMenuStrip cms = new System.Windows.Forms.ContextMenuStrip(); - cms.Items.Add("Choose Database"); - System.Windows.Forms.ToolStripMenuItem tsmi = cms.Items[0] as System.Windows.Forms.ToolStripMenuItem; - tsmi.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaption);// System.Drawing.Color.Pink; - tsmi.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaptionText); - tsmi.Font = new System.Drawing.Font(tsmi.Font, System.Drawing.FontStyle.Bold); - foreach (DataRow dr in ds.Tables[0].Rows) - { - if (dr["functionality"].ToString() == "Approval" && !dr["name"].ToString().EndsWith("_RO")) // don't display sql ro databases in list - cms.Items.Add(dr["name"].ToString(), null, new EventHandler(Database_Click)); - } - return cms; - } + { + string tmp = constr.Replace("{MENU}", "master"); + using (SqlConnection cn = new SqlConnection(tmp)) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlDataAdapter da = new SqlDataAdapter("select name, 'Approval' functionality from sysdatabases where name not in ('master','model','msdb','tempdb') order by name", cn)) + { + da.SelectCommand.CommandTimeout = 300; // 300 sec timeout + DataSet ds = new DataSet(); + try + { + da.Fill(ds); + } + catch (Exception ex) + { + System.Windows.Forms.MessageBox.Show(ex.GetType().Name, ex.Message); + throw (new Exception("Cannot Load Data List", ex)); + } + cn.Close(); + System.Windows.Forms.ContextMenuStrip cms = new System.Windows.Forms.ContextMenuStrip(); + cms.Items.Add("Choose Database"); + System.Windows.Forms.ToolStripMenuItem tsmi = cms.Items[0] as System.Windows.Forms.ToolStripMenuItem; + tsmi.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaption);// System.Drawing.Color.Pink; + tsmi.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaptionText); + tsmi.Font = new System.Drawing.Font(tsmi.Font, System.Drawing.FontStyle.Bold); + foreach (DataRow dr in ds.Tables[0].Rows) + { + if (dr["functionality"].ToString() == "Approval" && !dr["name"].ToString().EndsWith("_RO")) // don't display sql ro databases in list + cms.Items.Add(dr["name"].ToString(), null, new EventHandler(Database_Click)); + } + return cms; + } + } + } - static void Database_Click(object sender, EventArgs e) + static void Database_Click(object sender, EventArgs e) { - System.Windows.Forms.ToolStripMenuItem tsmi = sender as System.Windows.Forms.ToolStripMenuItem; - if (tsmi != null) - { - _SelectedDatabase = tsmi.Text; - } - } + if (sender is System.Windows.Forms.ToolStripMenuItem tsmi) + { + _SelectedDatabase = tsmi.Text; + } + } public static SqlConnection VEPROMS_SqlConnection { get - { - string strConn = VEPROMS_Connection; // If failure - Fail (Don't try to catch) - // Attempt to make a connection + { + string strConn = VEPROMS_Connection; // If failure - Fail (Don't try to catch) + // Attempt to make a connection + + //note - cannot use using here as it will close the connection and it needs to return it as open SqlConnection cn = new SqlConnection(strConn); - try - { - cn.Open(); - return cn; - } - catch (SqlException exsql) - { - const string strAttachError = "An attempt to attach an auto-named database for file "; - if (exsql.Message.StartsWith(strAttachError)) - {// Check to see if the file is missing - string sFile = exsql.Message.Substring(strAttachError.Length); - sFile = sFile.Substring(0, sFile.IndexOf(" failed")); - // "An attempt to attach an auto-named database for file failed" - if (strConn.ToLower().IndexOf("user instance=true") < 0) - { - throw new ApplicationException("Connection String missing attribute: User Instance=True"); - } - if (System.IO.File.Exists(sFile)) - { - throw new ApplicationException("Database file " + sFile + " Cannot be opened\r\n", exsql); - } - else - { - throw new FileNotFoundException("Database file " + sFile + " Not Found", exsql); - } - } - else - { - //Open a MesageBox so the user is given some feedback that the connection has failed. - ReportInnermostException(exsql,strConn); - throw new ApplicationException("Failure on Connect", exsql); - } - } - catch (Exception ex)// Throw Application Exception on Failure - { - if (_MyLog.IsErrorEnabled) _MyLog.Error("Connection Error", ex); - throw new ApplicationException("Failure on Connect", ex); - } - } - } + try + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + return cn; + } + catch (SqlException exsql) + { + const string strAttachError = "An attempt to attach an auto-named database for file "; + if (exsql.Message.StartsWith(strAttachError)) + {// Check to see if the file is missing + string sFile = exsql.Message.Substring(strAttachError.Length); + sFile = sFile.Substring(0, sFile.IndexOf(" failed")); + // "An attempt to attach an auto-named database for file failed" + if (strConn.ToLower().IndexOf("user instance=true") < 0) + { + throw new ApplicationException("Connection String missing attribute: User Instance=True"); + } + if (File.Exists(sFile)) + { + throw new ApplicationException("Database file " + sFile + " Cannot be opened\r\n", exsql); + } + else + { + throw new FileNotFoundException("Database file " + sFile + " Not Found", exsql); + } + } + else + { + //Open a MesageBox so the user is given some feedback that the connection has failed. + ReportInnermostException(exsql, strConn); + throw new ApplicationException("Failure on Connect", exsql); + } + } + catch (Exception ex)// Throw Application Exception on Failure + { + if (_MyLog.IsErrorEnabled) _MyLog.Error("Connection Error", ex); + throw new ApplicationException("Failure on Connect", ex); + } + } + } /// /// Open a MessageBox with the exception type, the connection string and the exception message /// @@ -400,15 +389,13 @@ public static string DBServer while (ex.InnerException != null) ex = ex.InnerException; System.Windows.Forms.MessageBox.Show(string.Format("{0}\r\n\r\nConnection String ={1}", ex.Message,conn) - ,"PROMS - " + ex.GetType().FullName, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); - System.Diagnostics.Process.GetCurrentProcess().Kill(); + , $"PROMS - {ex.GetType().FullName}", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); + Process.GetCurrentProcess().Kill(); } public static void PurgeData() { try { - //SqlConnection cn = VEPROMS_SqlConnection; - //SqlCommand cmd = new SqlCommand("purgedata", cn); using (SqlConnection cn = VEPROMS_SqlConnection) { using (SqlCommand cmd = new SqlCommand("purgedata", cn)) @@ -458,8 +445,6 @@ public static string DBServer { try { - //SqlConnection cn = VEPROMS_SqlConnection; - //SqlCommand cmd = new SqlCommand("purgedata", cn); using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cmd = new SqlCommand("purgedata", cn)) @@ -483,11 +468,8 @@ public static string DBServer { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private ProposedTransition _ProposedTransition; + public string ErrorMessage => _ErrorMessage; + private ProposedTransition _ProposedTransition; public ProposedTransition ProposedTransition { get { return _ProposedTransition; } @@ -508,10 +490,12 @@ public static string DBServer #region Factory Methods public static ProposedTransition Execute(int fromID, int toID) { - CanTransitionBeCreatedCommand cmd = new CanTransitionBeCreatedCommand(); - cmd.FromID = fromID; - cmd.ToID = toID; - cmd = DataPortal.Execute(cmd); + CanTransitionBeCreatedCommand cmd = new CanTransitionBeCreatedCommand + { + FromID = fromID, + ToID = toID + }; + cmd = DataPortal.Execute(cmd); return cmd.ProposedTransition; } private CanTransitionBeCreatedCommand() @@ -536,8 +520,6 @@ public static string DBServer { try { - //SqlConnection cn = VEPROMS_SqlConnection; - //SqlCommand cmd = new SqlCommand("purgedata", cn); using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cmd = new SqlCommand("vesp_CanTransitionBeCreated", cn)) @@ -571,16 +553,10 @@ public static string DBServer { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - private List _InvalidTransitions; - public List InvalidTransitions - { - get { return _InvalidTransitions; } - } - private int _ItemID; + public string ErrorMessage => _ErrorMessage; + private List _InvalidTransitions; + public List InvalidTransitions => _InvalidTransitions; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -595,10 +571,12 @@ public static string DBServer #region Factory Methods public static List Execute(int itemID, string newAppl) { - WillTransitionsBeValidCommand cmd = new WillTransitionsBeValidCommand(); - cmd.ItemID = itemID; - cmd.NewAppl = newAppl; - cmd = DataPortal.Execute(cmd); + WillTransitionsBeValidCommand cmd = new WillTransitionsBeValidCommand + { + ItemID = itemID, + NewAppl = newAppl + }; + cmd = DataPortal.Execute(cmd); return cmd.InvalidTransitions; } private WillTransitionsBeValidCommand() @@ -626,8 +604,6 @@ public static string DBServer { try { - //SqlConnection cn = VEPROMS_SqlConnection; - //SqlCommand cmd = new SqlCommand("purgedata", cn); using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cmd = new SqlCommand("vesp_WillTransitionsBeValid", cn)) diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Detail.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Detail.cs index dd3bd91b..de14f08f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Detail.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Detail.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshDetails.Add(this); } - private void ClearRefreshList() - { - _RefreshDetails = new List(); - } + private void ClearRefreshList() => _RefreshDetails = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -57,6 +52,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Detail detail) { @@ -66,6 +62,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(detail)) _CacheList.Remove(detail); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -91,15 +88,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextDetailID = -1; - public static int NextDetailID - { - get { return _nextDetailID--; } - } + public static int NextDetailID => _nextDetailID--; private int _DetailID; [System.ComponentModel.DataObjectField(true, true)] public int DetailID @@ -248,37 +239,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)); } - // CSLATODO: Replace base Detail.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Detail - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Detail.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Detail - protected override object GetIdValue() - { - return MyDetailUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDetailUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -307,8 +283,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -345,35 +321,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DetailID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(ItemType, ""); - //AuthorizationRules.AllowRead(Text, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(ItemType, ""); - //AuthorizationRules.AllowWrite(Text, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _DetailExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -381,42 +333,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _DetailExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DetailUnique = 0; - protected static int DetailUnique - { get { return ++_DetailUnique; } } - private int _MyDetailUnique = DetailUnique; - public int MyDetailUnique // Absolutely Unique ID - Editable - { get { return _MyDetailUnique; } } + protected static int DetailUnique => ++_DetailUnique; + private readonly int _MyDetailUnique = DetailUnique; + // Absolutely Unique ID - Editable + public int MyDetailUnique => _MyDetailUnique; protected Detail() {/* require use of factory methods */ AddToCache(this); @@ -425,15 +349,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Detail() { _CountFinalized++; @@ -458,8 +378,6 @@ namespace VEPROMS.CSLA.Library } public static Detail New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Detail"); try { return DataPortal.Create(); @@ -531,8 +449,6 @@ namespace VEPROMS.CSLA.Library } public static Detail Get(int detailID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Detail"); try { Detail tmp = GetCachedByPrimaryKey(detailID); @@ -558,14 +474,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Detail(dr); return null; } - internal Detail(SafeDataReader dr) - { - ReadData(dr); - } + internal Detail(SafeDataReader dr) => ReadData(dr); public static void Delete(int detailID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Detail"); try { DataPortal.Delete(new PKCriteria(detailID)); @@ -577,12 +488,6 @@ namespace VEPROMS.CSLA.Library } public override Detail Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Detail"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Detail"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Detail"); try { BuildRefreshList(); @@ -602,13 +507,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DetailID; - public int DetailID - { get { return _DetailID; } } - public PKCriteria(int detailID) - { - _DetailID = detailID; - } + private readonly int _DetailID; + public int DetailID => _DetailID; + public PKCriteria(int detailID) => _DetailID = detailID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -679,7 +580,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Detail.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -704,39 +605,47 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyContent != null) _MyContent.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyContent?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addDetail"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@ItemType", _ItemType); - cm.Parameters.AddWithValue("@Text", _Text); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int); - param_DetailID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_DetailID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _DetailID = (int)cm.Parameters["@newDetailID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addDetail"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@ItemType", _ItemType); + cm.Parameters.AddWithValue("@Text", _Text); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_DetailID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _DetailID = (int)cm.Parameters["@newDetailID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.SQLInsert", GetHashCode()); @@ -748,7 +657,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Detail.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int detailID, Content myContent, int itemType, string text, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Add", 0); @@ -767,11 +676,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int); - param_DetailID.Direction = ParameterDirection.Output; + SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_DetailID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -786,7 +699,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Detail.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -809,41 +722,47 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.SQLUpdate", GetHashCode()); try { - if (_MyContent != null) _MyContent.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyContent?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateDetail"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@DetailID", _DetailID); - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@ItemType", _ItemType); - cm.Parameters.AddWithValue("@Text", _Text); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateDetail"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@DetailID", _DetailID); + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@ItemType", _ItemType); + cm.Parameters.AddWithValue("@Text", _Text); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -856,18 +775,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Detail.Add(cn, ref _DetailID, _MyContent, _ItemType, _Text, _Config, _DTS, _UserID); - else - _LastChanged = Detail.Update(cn, ref _DetailID, _ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Detail.Add(cn, ref _DetailID, _MyContent, _ItemType, _Text, _Config, _DTS, _UserID); + else + _LastChanged = Detail.Update(cn, ref _DetailID, _ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int detailID, int contentID, int itemType, string text, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Update", 0); @@ -888,8 +811,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -903,12 +828,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Detail.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_DetailID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Delete", GetHashCode()); @@ -933,7 +858,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Detail.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int detailID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Remove", 0); @@ -974,16 +899,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _DetailID; + private readonly int _DetailID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int detailID) - { - _DetailID = detailID; - } + public bool Exists => _exists; + public ExistsCommand(int detailID) => _DetailID = detailID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Execute", GetHashCode()); @@ -991,7 +910,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1013,7 +932,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - DetailExtension _DetailExtension = new DetailExtension(); + readonly DetailExtension _DetailExtension = new DetailExtension(); [Serializable()] partial class DetailExtension : extensionBase { @@ -1022,14 +941,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1058,57 +971,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Detail) + if (destType == typeof(string) && value is Detail detail) { // Return the ToString value - return ((Detail)value).ToString(); + return detail.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DetailExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Detail -// { -// partial class DetailExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfo.cs index a66ab7aa..cd1762d3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class DetailInfo : ReadOnlyBase, IDisposable { public event DetailInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DetailInfo detailInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(detailInfo)) _CacheList.Remove(detailInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Detail _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _DetailID; [System.ComponentModel.DataObjectField(true, true)] public int DetailID @@ -164,32 +148,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base DetailInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DetailInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DetailInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DetailInfo - protected override object GetIdValue() - { - return MyDetailInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDetailInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _DetailInfoUnique = 0; - private static int DetailInfoUnique - { get { return ++_DetailInfoUnique; } } - private int _MyDetailInfoUnique = DetailInfoUnique; - public int MyDetailInfoUnique // Absolutely Unique ID - Info - { get { return _MyDetailInfoUnique; } } + private static int DetailInfoUnique => ++_DetailInfoUnique; + private readonly int _MyDetailInfoUnique = DetailInfoUnique; + // Absolutely Unique ID - Info + public int MyDetailInfoUnique => _MyDetailInfoUnique; protected DetailInfo() {/* require use of factory methods */ AddToCache(this); @@ -198,15 +169,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DetailInfo() { _CountFinalized++; @@ -223,10 +190,7 @@ namespace VEPROMS.CSLA.Library if (listDetailInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(DetailID.ToString()); // remove the list } - public virtual Detail Get() - { - return _Editable = Detail.Get(_DetailID); - } + public virtual Detail Get() => _Editable = Detail.Get(_DetailID); public static void Refresh(Detail tmp) { string key = tmp.DetailID.ToString(); @@ -239,11 +203,11 @@ namespace VEPROMS.CSLA.Library { if (_ContentID != tmp.ContentID) { - if (MyContent != null) MyContent.RefreshContentDetails(); // Update List for old value + MyContent?.RefreshContentDetails(); // Update List for old value _ContentID = tmp.ContentID; // Update the value } _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentDetails(); // Update List for new value + MyContent?.RefreshContentDetails(); // Update List for new value _ItemType = tmp.ItemType; _Text = tmp.Text; _Config = tmp.Config; @@ -272,8 +236,6 @@ namespace VEPROMS.CSLA.Library } public static DetailInfo Get(int detailID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Detail"); try { DetailInfo tmp = GetCachedByPrimaryKey(detailID); @@ -312,13 +274,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DetailID; - public int DetailID - { get { return _DetailID; } } - public PKCriteria(int detailID) - { - _DetailID = detailID; - } + private readonly int _DetailID; + public int DetailID => _DetailID; + public PKCriteria(int detailID) => _DetailID = detailID; } private void ReadData(SafeDataReader dr) { @@ -379,7 +337,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - DetailInfoExtension _DetailInfoExtension = new DetailInfoExtension(); + readonly DetailInfoExtension _DetailInfoExtension = new DetailInfoExtension(); [Serializable()] partial class DetailInfoExtension : extensionBase { } [Serializable()] @@ -395,10 +353,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DetailInfo) + if (destType == typeof(string) && value is DetailInfo info) { // Return the ToString value - return ((DetailInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfoList.cs index c979f723..88ae567a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DetailInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (DetailInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~DetailInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DetailInfoList() { _CountFinalized++; } @@ -97,26 +90,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DetailInfoList.Get", ex); } } - /// - /// Reset the list of all DetailInfo. - /// - public static void Reset() - { - _DetailInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static DetailInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on DetailInfoList.Get", ex); - // } - //} - public static DetailInfoList GetByContentID(int contentID) + /// + /// Reset the list of all DetailInfo. + /// + public static void Reset() => _DetailInfoList = null; + + public static DetailInfoList GetByContentID(int contentID) { try { @@ -166,11 +145,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -207,41 +183,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -263,7 +228,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DetailInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private DetailInfo Item { get { return (DetailInfo)_Item; } } public DetailInfoListPropertyDescriptor(DetailInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -272,10 +236,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DetailInfoList) + if (destType == typeof(string) && value is DetailInfoList list) { // Return department and department role separated by comma. - return ((DetailInfoList)value).Items.Count.ToString() + " Details"; + return $"{list.Items.Count} Details"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersion.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersion.cs index 0b18bb3d..04130c74 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersion.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersion.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -72,6 +70,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DocVersion docVersion) { @@ -81,6 +80,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(docVersion)) _CacheList.Remove(docVersion); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -106,15 +106,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextVersionID = -1; - public static int NextVersionID - { - get { return _nextVersionID--; } - } + public static int NextVersionID => _nextVersionID--; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -362,10 +356,7 @@ namespace VEPROMS.CSLA.Library return _DocVersionAssociations; } } - public void Reset_DocVersionAssociations() - { - _DocVersionAssociationCount = -1; - } + public void Reset_DocVersionAssociations() => _DocVersionAssociationCount = -1; public override bool IsDirty { get @@ -380,37 +371,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_DocVersionAssociations == null ? false : _DocVersionAssociations.IsDirtyList(list)) || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)) || (_MyFormat == null ? false : _MyFormat.IsDirtyList(list)) || (_MyItem == null ? false : _MyItem.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_DocVersionAssociations != null && _DocVersionAssociations.IsDirtyList(list)) || (_MyFolder != null && _MyFolder.IsDirtyList(list)) || (_MyFormat != null && _MyFormat.IsDirtyList(list)) || (_MyItem != null && _MyItem.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_DocVersionAssociations == null ? true : _DocVersionAssociations.IsValidList(list)) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)) && (_MyFormat == null ? true : _MyFormat.IsValidList(list)) && (_MyItem == null ? true : _MyItem.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_DocVersionAssociations == null || _DocVersionAssociations.IsValidList(list)) && (_MyFolder == null || _MyFolder.IsValidList(list)) && (_MyFormat == null || _MyFormat.IsValidList(list)) && (_MyItem == null || _MyItem.IsValidList(list)); } - // CSLATODO: Replace base DocVersion.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocVersion - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DocVersion.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocVersion - protected override object GetIdValue() - { - return MyDocVersionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocVersionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -442,8 +418,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -483,41 +459,10 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowRead(VersionType, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(FolderID, ""); - //AuthorizationRules.AllowWrite(VersionType, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _DocVersionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -525,55 +470,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _DocVersionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _DocVersionAssociationCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocVersionUnique = 0; - protected static int DocVersionUnique - { get { return ++_DocVersionUnique; } } - private int _MyDocVersionUnique = DocVersionUnique; - public int MyDocVersionUnique // Absolutely Unique ID - Editable - { get { return _MyDocVersionUnique; } } + protected static int DocVersionUnique => ++_DocVersionUnique; + private readonly int _MyDocVersionUnique = DocVersionUnique; + // Absolutely Unique ID - Editable + public int MyDocVersionUnique => _MyDocVersionUnique; protected DocVersion() {/* require use of factory methods */ AddToCache(this); @@ -582,15 +486,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocVersion() { _CountFinalized++; @@ -615,8 +515,6 @@ namespace VEPROMS.CSLA.Library } public static DocVersion New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a DocVersion"); try { return DataPortal.Create(); @@ -692,8 +590,6 @@ namespace VEPROMS.CSLA.Library } public static DocVersion Get(int versionID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a DocVersion"); try { DocVersion tmp = GetCachedByPrimaryKey(versionID); @@ -725,8 +621,6 @@ namespace VEPROMS.CSLA.Library } public static void Delete(int versionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a DocVersion"); try { DataPortal.Delete(new PKCriteria(versionID)); @@ -738,12 +632,6 @@ namespace VEPROMS.CSLA.Library } public override DocVersion Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a DocVersion"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a DocVersion"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a DocVersion"); try { BuildRefreshList(); @@ -763,13 +651,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - public PKCriteria(int versionID) - { - _VersionID = versionID; - } + private readonly int _VersionID; + public int VersionID => _VersionID; + public PKCriteria(int versionID) => _VersionID = versionID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -848,7 +732,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocVersion.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -873,47 +757,55 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyFolder != null) _MyFolder.Update(); - if (_MyFormat != null) _MyFormat.Update(); - if (_MyItem != null) _MyItem.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyFolder?.Update(); + _MyFormat?.Update(); + _MyItem?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addDocVersion"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@FolderID", FolderID); - cm.Parameters.AddWithValue("@VersionType", _VersionType); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - cm.Parameters.AddWithValue("@ItemID", ItemID); - cm.Parameters.AddWithValue("@FormatID", FormatID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); - param_VersionID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_VersionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _VersionID = (int)cm.Parameters["@newVersionID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addDocVersion"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@FolderID", FolderID); + cm.Parameters.AddWithValue("@VersionType", _VersionType); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + cm.Parameters.AddWithValue("@ItemID", ItemID); + cm.Parameters.AddWithValue("@FormatID", FormatID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_VersionID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _VersionID = (int)cm.Parameters["@newVersionID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_DocVersionAssociations != null) _DocVersionAssociations.Update(this); + _DocVersionAssociations?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -923,7 +815,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocVersion.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int versionID, Folder myFolder, int versionType, string name, string title, Item myItem, Format myFormat, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Add", 0); @@ -945,11 +837,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); - param_VersionID.Direction = ParameterDirection.Output; + SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_VersionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -964,7 +860,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocVersion.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -987,49 +883,55 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.SQLUpdate", GetHashCode()); try { - if (_MyFolder != null) _MyFolder.Update(); - if (_MyFormat != null) _MyFormat.Update(); - if (_MyItem != null) _MyItem.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyFolder?.Update(); + _MyFormat?.Update(); + _MyItem?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateDocVersion"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@VersionID", _VersionID); - cm.Parameters.AddWithValue("@FolderID", FolderID); - cm.Parameters.AddWithValue("@VersionType", _VersionType); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - cm.Parameters.AddWithValue("@ItemID", ItemID); - cm.Parameters.AddWithValue("@FormatID", FormatID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateDocVersion"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@VersionID", _VersionID); + cm.Parameters.AddWithValue("@FolderID", FolderID); + cm.Parameters.AddWithValue("@VersionType", _VersionType); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + cm.Parameters.AddWithValue("@ItemID", ItemID); + cm.Parameters.AddWithValue("@FormatID", FormatID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_DocVersionAssociations != null) _DocVersionAssociations.Update(this); + _DocVersionAssociations?.Update(this); } catch (Exception ex) { @@ -1040,19 +942,23 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, _MyItem, _MyFormat, _Config, _DTS, _UserID); - else - _LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, _ItemID, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, _MyItem, _MyFormat, _Config, _DTS, _UserID); + else + _LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, _ItemID, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_DocVersionAssociations != null) _DocVersionAssociations.Update(this); + _DocVersionAssociations?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int versionID, int folderID, int versionType, string name, string title, int? itemID, int? formatID, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Update", 0); @@ -1076,8 +982,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1091,12 +999,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocVersion.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_VersionID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Delete", GetHashCode()); @@ -1121,7 +1029,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocVersion.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int versionID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Remove", 0); @@ -1162,16 +1070,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _VersionID; + private readonly int _VersionID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int versionID) - { - _VersionID = versionID; - } + public bool Exists => _exists; + public ExistsCommand(int versionID) => _VersionID = versionID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Execute", GetHashCode()); @@ -1179,7 +1081,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1201,7 +1103,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - DocVersionExtension _DocVersionExtension = new DocVersionExtension(); + readonly DocVersionExtension _DocVersionExtension = new DocVersionExtension(); [Serializable()] partial class DocVersionExtension : extensionBase { @@ -1210,18 +1112,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultVersionType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultVersionType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1250,61 +1143,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocVersion) + if (destType == typeof(string) && value is DocVersion version) { // Return the ToString value - return ((DocVersion)value).ToString(); + return version.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocVersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DocVersion -// { -// partial class DocVersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultVersionType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs index 2baf6ba5..30ee7d23 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociation.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _AssociationID; [System.ComponentModel.DataObjectField(true, true)] public int AssociationID @@ -145,15 +139,6 @@ namespace VEPROMS.CSLA.Library } } private byte[] _LastChanged = new byte[8];//timestamp - private int _ROFst_RODbID; - public int ROFst_RODbID - { - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] - get - { - return _ROFst_RODbID; - } - } private byte[] _ROFst_ROLookup; public byte[] ROFst_ROLookup { @@ -163,7 +148,7 @@ namespace VEPROMS.CSLA.Library return _ROFst_ROLookup; } } - private string _ROFst_Config = string.Empty; + private readonly string _ROFst_Config = string.Empty; public string ROFst_Config { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] @@ -172,7 +157,7 @@ namespace VEPROMS.CSLA.Library return _ROFst_Config; } } - private DateTime _ROFst_DTS = new DateTime(); + private readonly DateTime _ROFst_DTS = new DateTime(); public DateTime ROFst_DTS { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] @@ -181,7 +166,7 @@ namespace VEPROMS.CSLA.Library return _ROFst_DTS; } } - private string _ROFst_UserID = string.Empty; + private readonly string _ROFst_UserID = string.Empty; public string ROFst_UserID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] @@ -195,10 +180,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocVersionAssociation - protected override object GetIdValue() - { - return MyDocVersionAssociationUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocVersionAssociationUnique; // Absolutely Unique ID // CSLATODO: Replace base DocVersionAssociation.ToString function as necessary /// /// Overrides Base ToString @@ -222,18 +204,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyROFst == null ? false : _MyROFst.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyROFst != null && _MyROFst.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyROFst == null ? true : _MyROFst.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyROFst == null || _MyROFst.IsValidList(list)); } #endregion #region ValidationRules @@ -264,7 +243,7 @@ namespace VEPROMS.CSLA.Library { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -289,76 +268,21 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AssociationID, ""); - //AuthorizationRules.AllowRead(ROFstID, ""); - //AuthorizationRules.AllowWrite(ROFstID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocVersionAssociationUnique = 0; - private static int DocVersionAssociationUnique - { get { return ++_DocVersionAssociationUnique; } } - private int _MyDocVersionAssociationUnique = DocVersionAssociationUnique; - public int MyDocVersionAssociationUnique // Absolutely Unique ID - Editable FK - { get { return _MyDocVersionAssociationUnique; } } - internal static DocVersionAssociation New(ROFst myROFst) - { - return new DocVersionAssociation(myROFst); - } - internal static DocVersionAssociation Get(SafeDataReader dr) - { - return new DocVersionAssociation(dr); - } + private static int DocVersionAssociationUnique => ++_DocVersionAssociationUnique; + private readonly int _MyDocVersionAssociationUnique = DocVersionAssociationUnique; + // Absolutely Unique ID - Editable FK + public int MyDocVersionAssociationUnique => _MyDocVersionAssociationUnique; + internal static DocVersionAssociation New(ROFst myROFst) => new DocVersionAssociation(myROFst); + internal static DocVersionAssociation Get(SafeDataReader dr) => new DocVersionAssociation(dr); public DocVersionAssociation() { MarkAsChild(); @@ -386,15 +310,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocVersionAssociation() { _CountFinalized++; @@ -420,12 +340,7 @@ namespace VEPROMS.CSLA.Library dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); // B2023-020: setting RO Database on new working draft crashes. Query 'getAssociationsByVersionID' had been modified // for memory improvements to not return the ROFst values, so don't Get the values. Comment out for now. - //_ROFst_RODbID = dr.GetInt32("ROFst_RODbID"); - //_ROFst_ROLookup = (byte[])dr.GetValue("ROFst_ROLookup"); _ROFst_ROLookup = null; // B2022-026 RO Memory reduction - use ROlookup of null to know if we loaded the RO.FST file - //_ROFst_Config = dr.GetString("ROFst_Config"); - //_ROFst_DTS = dr.GetDateTime("ROFst_DTS"); - //_ROFst_UserID = dr.GetString("ROFst_UserID"); } catch (Exception ex) // FKItem Fetch { @@ -438,32 +353,45 @@ namespace VEPROMS.CSLA.Library { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Association.Add(cn, ref _AssociationID, myDocVersion, _MyROFst, _Config, _DTS, _UserID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Association.Add(cn, ref _AssociationID, myDocVersion, _MyROFst, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(DocVersion myDocVersion) { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Association.Update(cn, ref _AssociationID, myDocVersion.VersionID, _ROFstID, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Association.Update(cn, ref _AssociationID, myDocVersion.VersionID, _ROFstID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(DocVersion myDocVersion) { // if we're not dirty then don't update the database if (!this.IsDirty) return; // if we're new then don't update the database if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Association.Remove(cn, _AssociationID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Association.Remove(cn, _AssociationID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - DocVersionAssociationExtension _DocVersionAssociationExtension = new DocVersionAssociationExtension(); + readonly DocVersionAssociationExtension _DocVersionAssociationExtension = new DocVersionAssociationExtension(); [Serializable()] partial class DocVersionAssociationExtension : extensionBase { @@ -472,14 +400,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -508,57 +430,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocVersionAssociation) + if (destType == typeof(string) && value is DocVersionAssociation association) { // Return the ToString value - return ((DocVersionAssociation)value).ToString(); + return association.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocVersionAssociationExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DocVersionAssociation -// { -// partial class DocVersionAssociationExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociations.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociations.cs index ff91336b..6685bed9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociations.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionAssociations.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public DocVersionAssociation this[Association myAssociation] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public DocVersionAssociation this[Association myAssociation] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public DocVersionAssociation GetItem(Association myAssociation) + public new System.Collections.Generic.IList Items => base.Items; + public DocVersionAssociation GetItem(Association myAssociation) { foreach (DocVersionAssociation association in this) if (association.AssociationID == myAssociation.AssociationID) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(myROFst)) { DocVersionAssociation association = DocVersionAssociation.New(myROFst); - this.Add(association); + Add(association); return association; } else @@ -113,18 +105,18 @@ namespace VEPROMS.CSLA.Library get { return IsValidList(new List()); } } public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (DocVersionAssociation child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + { + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (DocVersionAssociation child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(ROFst myROFst) { foreach (DocVersionAssociation association in this) @@ -156,20 +148,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static DocVersionAssociations New() - { - return new DocVersionAssociations(); - } - internal static DocVersionAssociations Get(SafeDataReader dr) - { - return new DocVersionAssociations(dr); - } - public static DocVersionAssociations GetByVersionID(int versionID) + #endregion + #region Factory Methods + internal static DocVersionAssociations New() => new DocVersionAssociations(); + internal static DocVersionAssociations Get(SafeDataReader dr) => new DocVersionAssociations(dr); + public static DocVersionAssociations GetByVersionID(int versionID) { try { @@ -180,11 +166,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DocVersionAssociations.GetByVersionID", ex); } } - private DocVersionAssociations() - { - MarkAsChild(); - } - internal DocVersionAssociations(SafeDataReader dr) + private DocVersionAssociations() => MarkAsChild(); + internal DocVersionAssociations(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -193,16 +176,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~DocVersionAssociations() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocVersionAssociations() { _CountFinalized++; } @@ -217,19 +196,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(DocVersionAssociation.Get(dr)); - this.RaiseListChangedEvents = true; + Add(DocVersionAssociation.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class VersionIDCriteria { - public VersionIDCriteria(int versionID) - { - _VersionID = versionID; - } - private int _VersionID; + public VersionIDCriteria(int versionID) => _VersionID = versionID; + private int _VersionID; public int VersionID { get { return _VersionID; } @@ -238,7 +214,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(VersionIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionAssociations.DataPortal_FetchVersionID", GetHashCode()); try { @@ -252,7 +228,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new DocVersionAssociation(dr)); + while (dr.Read()) Add(new DocVersionAssociation(dr)); } } } @@ -262,11 +238,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionAssociations.DataPortal_FetchVersionID", ex); throw new DbCslaException("DocVersionAssociations.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(DocVersion docVersion) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -285,49 +261,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DocVersionAssociationsPropertyDescriptor pd = new DocVersionAssociationsPropertyDescriptor(this, i); @@ -344,7 +309,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocVersionAssociationsPropertyDescriptor : vlnListPropertyDescriptor { - private DocVersionAssociation Item { get { return (DocVersionAssociation)_Item; } } public DocVersionAssociationsPropertyDescriptor(DocVersionAssociations collection, int index) : base(collection, index) { ;} } #endregion @@ -353,10 +317,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocVersionAssociations) + if (destType == typeof(string) && value is DocVersionAssociations associations) { // Return department and department role separated by comma. - return ((DocVersionAssociations)value).Items.Count.ToString() + " Associations"; + return $"{associations.Items.Count} Associations"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfo.cs index aa0bb85b..9ef46ea0 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class DocVersionInfo : ReadOnlyBase, IDisposable { public event DocVersionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DocVersionInfo docVersionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(docVersionInfo)) _CacheList.Remove(docVersionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected DocVersion _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -252,32 +236,19 @@ namespace VEPROMS.CSLA.Library foreach (DocVersionInfo tmp in _CacheByPrimaryKey[_VersionID.ToString()]) tmp._DocVersionAssociationCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base DocVersionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocVersionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DocVersionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocVersionInfo - protected override object GetIdValue() - { - return MyDocVersionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocVersionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _DocVersionInfoUnique = 0; - private static int DocVersionInfoUnique - { get { return ++_DocVersionInfoUnique; } } - private int _MyDocVersionInfoUnique = DocVersionInfoUnique; - public int MyDocVersionInfoUnique // Absolutely Unique ID - Info - { get { return _MyDocVersionInfoUnique; } } + private static int DocVersionInfoUnique => ++_DocVersionInfoUnique; + private readonly int _MyDocVersionInfoUnique = DocVersionInfoUnique; + // Absolutely Unique ID - Info + public int MyDocVersionInfoUnique => _MyDocVersionInfoUnique; protected DocVersionInfo() {/* require use of factory methods */ AddToCache(this); @@ -286,15 +257,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocVersionInfo() { _CountFinalized++; @@ -311,10 +278,7 @@ namespace VEPROMS.CSLA.Library if (listDocVersionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(VersionID.ToString()); // remove the list } - public virtual DocVersion Get() - { - return _Editable = DocVersion.Get(_VersionID); - } + public virtual DocVersion Get() => _Editable = DocVersion.Get(_VersionID); public static void Refresh(DocVersion tmp) { string key = tmp.VersionID.ToString(); @@ -327,28 +291,28 @@ namespace VEPROMS.CSLA.Library { if (_FolderID != tmp.FolderID) { - if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for old value + MyFolder?.RefreshFolderDocVersions(); // Update List for old value _FolderID = tmp.FolderID; // Update the value } _MyFolder = null; // Reset list so that the next line gets a new list - if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for new value + MyFolder?.RefreshFolderDocVersions(); // Update List for new value _VersionType = tmp.VersionType; _Name = tmp.Name; _Title = tmp.Title; if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for old value + MyItem?.RefreshItemDocVersions(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for new value + MyItem?.RefreshItemDocVersions(); // Update List for new value if (_FormatID != tmp.FormatID) { - if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for old value + MyFormat?.RefreshFormatDocVersions(); // Update List for old value _FormatID = tmp.FormatID; // Update the value } _MyFormat = null; // Reset list so that the next line gets a new list - if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for new value + MyFormat?.RefreshFormatDocVersions(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -370,18 +334,18 @@ namespace VEPROMS.CSLA.Library _Title = tmp.Title; if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for old value + MyItem?.RefreshItemDocVersions(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for new value + MyItem?.RefreshItemDocVersions(); // Update List for new value if (_FormatID != tmp.FormatID) { - if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for old value + MyFormat?.RefreshFormatDocVersions(); // Update List for old value _FormatID = tmp.FormatID; // Update the value } _MyFormat = null; // Reset list so that the next line gets a new list - if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for new value + MyFormat?.RefreshFormatDocVersions(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -400,21 +364,21 @@ namespace VEPROMS.CSLA.Library { if (_FolderID != tmp.FolderID) { - if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for old value + MyFolder?.RefreshFolderDocVersions(); // Update List for old value _FolderID = tmp.FolderID; // Update the value } _MyFolder = null; // Reset list so that the next line gets a new list - if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for new value + MyFolder?.RefreshFolderDocVersions(); // Update List for new value _VersionType = tmp.VersionType; _Name = tmp.Name; _Title = tmp.Title; if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for old value + MyItem?.RefreshItemDocVersions(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for new value + MyItem?.RefreshItemDocVersions(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -433,21 +397,21 @@ namespace VEPROMS.CSLA.Library { if (_FolderID != tmp.FolderID) { - if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for old value + MyFolder?.RefreshFolderDocVersions(); // Update List for old value _FolderID = tmp.FolderID; // Update the value } _MyFolder = null; // Reset list so that the next line gets a new list - if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for new value + MyFolder?.RefreshFolderDocVersions(); // Update List for new value _VersionType = tmp.VersionType; _Name = tmp.Name; _Title = tmp.Title; if (_FormatID != tmp.FormatID) { - if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for old value + MyFormat?.RefreshFormatDocVersions(); // Update List for old value _FormatID = tmp.FormatID; // Update the value } _MyFormat = null; // Reset list so that the next line gets a new list - if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for new value + MyFormat?.RefreshFormatDocVersions(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -456,8 +420,6 @@ namespace VEPROMS.CSLA.Library } public static DocVersionInfo Get(int versionID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a DocVersion"); try { DocVersionInfo tmp = GetCachedByPrimaryKey(versionID); @@ -496,13 +458,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - public PKCriteria(int versionID) - { - _VersionID = versionID; - } + private readonly int _VersionID; + public int VersionID => _VersionID; + public PKCriteria(int versionID) => _VersionID = versionID; } private void ReadData(SafeDataReader dr) { @@ -567,7 +525,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - DocVersionInfoExtension _DocVersionInfoExtension = new DocVersionInfoExtension(); + readonly DocVersionInfoExtension _DocVersionInfoExtension = new DocVersionInfoExtension(); [Serializable()] partial class DocVersionInfoExtension : extensionBase { } [Serializable()] @@ -583,10 +541,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocVersionInfo) + if (destType == typeof(string) && value is DocVersionInfo info) { // Return the ToString value - return ((DocVersionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfoList.cs index 18ebcfbd..0563edb3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocVersionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (DocVersionInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~DocVersionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocVersionInfoList() { _CountFinalized++; } @@ -104,18 +97,7 @@ namespace VEPROMS.CSLA.Library { _DocVersionInfoList = null; } - // CSLATODO: Add alternative gets - - //public static DocVersionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on DocVersionInfoList.Get", ex); - // } - //} + public static DocVersionInfoList GetByFolderID(int folderID) { try @@ -164,7 +146,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -178,7 +160,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DocVersionInfo(dr)); + while (dr.Read()) Add(new DocVersionInfo(dr)); IsReadOnly = true; } } @@ -189,16 +171,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class FolderIDCriteria { - public FolderIDCriteria(int folderID) - { - _FolderID = folderID; - } - private int _FolderID; + public FolderIDCriteria(int folderID) => _FolderID = folderID; + private int _FolderID; public int FolderID { get { return _FolderID; } @@ -207,7 +186,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FolderIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchFolderID", GetHashCode()); try { @@ -222,7 +201,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DocVersionInfo(dr)); + while (dr.Read()) Add(new DocVersionInfo(dr)); IsReadOnly = true; } } @@ -233,16 +212,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchFolderID", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class FormatIDCriteria { - public FormatIDCriteria(int? formatID) - { - _FormatID = formatID; - } - private int? _FormatID; + public FormatIDCriteria(int? formatID) => _FormatID = formatID; + private int? _FormatID; public int? FormatID { get { return _FormatID; } @@ -251,7 +227,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FormatIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchFormatID", GetHashCode()); try { @@ -266,7 +242,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DocVersionInfo(dr)); + while (dr.Read()) Add(new DocVersionInfo(dr)); IsReadOnly = true; } } @@ -277,16 +253,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchFormatID", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int? itemID) - { - _ItemID = itemID; - } - private int? _ItemID; + public ItemIDCriteria(int? itemID) => _ItemID = itemID; + private int? _ItemID; public int? ItemID { get { return _ItemID; } @@ -295,7 +268,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchItemID", GetHashCode()); try { @@ -310,7 +283,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DocVersionInfo(dr)); + while (dr.Read()) Add(new DocVersionInfo(dr)); IsReadOnly = true; } } @@ -321,48 +294,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchItemID", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DocVersionInfoListPropertyDescriptor pd = new DocVersionInfoListPropertyDescriptor(this, i); @@ -379,7 +341,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocVersionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private DocVersionInfo Item { get { return (DocVersionInfo)_Item; } } public DocVersionInfoListPropertyDescriptor(DocVersionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -388,10 +349,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocVersionInfoList) + if (destType == typeof(string) && value is DocVersionInfoList list) { // Return department and department role separated by comma. - return ((DocVersionInfoList)value).Items.Count.ToString() + " DocVersions"; + return $"{list.Items.Count} DocVersions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Document.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Document.cs index 6ca09e38..d8e429b9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Document.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Document.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -95,6 +93,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Document document) { @@ -104,6 +103,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(document)) _CacheList.Remove(document); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -129,15 +129,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextDocID = -1; - public static int NextDocID - { - get { return _nextDocID--; } - } + public static int NextDocID => _nextDocID--; private int _DocID; [System.ComponentModel.DataObjectField(true, true)] public int DocID @@ -354,10 +348,7 @@ namespace VEPROMS.CSLA.Library return _DocumentEntries; } } - public void Reset_DocumentEntries() - { - _DocumentEntryCount = -1; - } + public void Reset_DocumentEntries() => _DocumentEntryCount = -1; private int _DocumentPdfCount = 0; /// /// Count of DocumentPdfs for this Document @@ -389,10 +380,7 @@ namespace VEPROMS.CSLA.Library return _DocumentPdfs; } } - public void Reset_DocumentPdfs() - { - _DocumentPdfCount = -1; - } + public void Reset_DocumentPdfs() => _DocumentPdfCount = -1; public override bool IsDirty { get @@ -407,37 +395,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_DocumentDROUsages == null ? false : _DocumentDROUsages.IsDirtyList(list)) || (_DocumentEntries == null ? false : _DocumentEntries.IsDirtyList(list)) || (_DocumentPdfs == null ? false : _DocumentPdfs.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_DocumentDROUsages != null && _DocumentDROUsages.IsDirtyList(list)) || (_DocumentEntries != null && _DocumentEntries.IsDirtyList(list)) || (_DocumentPdfs != null && _DocumentPdfs.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_DocumentDROUsages == null ? true : _DocumentDROUsages.IsValidList(list)) && (_DocumentEntries == null ? true : _DocumentEntries.IsValidList(list)) && (_DocumentPdfs == null ? true : _DocumentPdfs.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_DocumentDROUsages == null || _DocumentDROUsages.IsValidList(list)) && (_DocumentEntries == null || _DocumentEntries.IsValidList(list)) && (_DocumentPdfs == null || _DocumentPdfs.IsValidList(list)); } - // CSLATODO: Replace base Document.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Document - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Document.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Document - protected override object GetIdValue() - { - return MyDocumentUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocumentUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -468,8 +441,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -502,37 +475,11 @@ namespace VEPROMS.CSLA.Library _DocumentExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowRead(LibTitle, ""); - //AuthorizationRules.AllowRead(DocContent, ""); - //AuthorizationRules.AllowRead(DocAscii, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(FileExtension, ""); - //AuthorizationRules.AllowWrite(LibTitle, ""); - //AuthorizationRules.AllowWrite(DocContent, ""); - //AuthorizationRules.AllowWrite(DocAscii, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(FileExtension, ""); _DocumentExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -540,57 +487,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _DocumentExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _DocumentDROUsageCount; - usedByCount += _DocumentEntryCount; - usedByCount += _DocumentPdfCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocumentUnique = 0; - protected static int DocumentUnique - { get { return ++_DocumentUnique; } } - private int _MyDocumentUnique = DocumentUnique; - public int MyDocumentUnique // Absolutely Unique ID - Editable - { get { return _MyDocumentUnique; } } + protected static int DocumentUnique => ++_DocumentUnique; + private readonly int _MyDocumentUnique = DocumentUnique; + // Absolutely Unique ID - Editable + public int MyDocumentUnique => _MyDocumentUnique; protected Document() {/* require use of factory methods */ AddToCache(this); @@ -599,15 +503,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Document() { _CountFinalized++; @@ -632,8 +532,6 @@ namespace VEPROMS.CSLA.Library } public static Document New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Document"); try { return DataPortal.Create(); @@ -699,8 +597,6 @@ namespace VEPROMS.CSLA.Library } public static Document Get(int docID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Document"); try { Document tmp = GetCachedByPrimaryKey(docID); @@ -726,14 +622,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Document(dr); return null; } - internal Document(SafeDataReader dr) - { - ReadData(dr); - } + internal Document(SafeDataReader dr) => ReadData(dr); public static void Delete(int docID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Document"); try { DataPortal.Delete(new PKCriteria(docID)); @@ -745,12 +636,6 @@ namespace VEPROMS.CSLA.Library } public override Document Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Document"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Document"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Document"); try { BuildRefreshList(); @@ -770,13 +655,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - public PKCriteria(int docID) - { - _DocID = docID; - } + private readonly int _DocID; + public int DocID => _DocID; + public PKCriteria(int docID) => _DocID = docID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -861,7 +742,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Document.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -886,44 +767,52 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addDocument"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@LibTitle", _LibTitle); - cm.Parameters.AddWithValue("@DocContent", _DocContent); - cm.Parameters.AddWithValue("@DocAscii", _DocAscii); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@FileExtension", _FileExtension); - // Output Calculated Columns - SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int); - param_DocID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_DocID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _DocID = (int)cm.Parameters["@newDocID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addDocument"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@LibTitle", _LibTitle); + cm.Parameters.AddWithValue("@DocContent", _DocContent); + cm.Parameters.AddWithValue("@DocAscii", _DocAscii); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@FileExtension", _FileExtension); + // Output Calculated Columns + SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_DocID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _DocID = (int)cm.Parameters["@newDocID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_DocumentEntries != null) _DocumentEntries.Update(this); - if (_DocumentDROUsages != null) _DocumentDROUsages.Update(this); - if (_DocumentPdfs != null) _DocumentPdfs.Update(this); + _DocumentEntries?.Update(this); + _DocumentDROUsages?.Update(this); + _DocumentPdfs?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -933,7 +822,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Document.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Add", 0); @@ -953,11 +842,15 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@FileExtension", fileExtension); // Output Calculated Columns - SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int); - param_DocID.Direction = ParameterDirection.Output; + SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_DocID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -972,7 +865,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Document.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -995,46 +888,52 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateDocument"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@DocID", _DocID); - cm.Parameters.AddWithValue("@LibTitle", _LibTitle); - cm.Parameters.AddWithValue("@DocContent", _DocContent); - cm.Parameters.AddWithValue("@DocAscii", _DocAscii); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - cm.Parameters.AddWithValue("@FileExtension", _FileExtension); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateDocument"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@DocID", _DocID); + cm.Parameters.AddWithValue("@LibTitle", _LibTitle); + cm.Parameters.AddWithValue("@DocContent", _DocContent); + cm.Parameters.AddWithValue("@DocAscii", _DocAscii); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + cm.Parameters.AddWithValue("@FileExtension", _FileExtension); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_DocumentEntries != null) _DocumentEntries.Update(this); - if (_DocumentDROUsages != null) _DocumentDROUsages.Update(this); - if (_DocumentPdfs != null) _DocumentPdfs.Update(this); + _DocumentEntries?.Update(this); + _DocumentDROUsages?.Update(this); + _DocumentPdfs?.Update(this); } catch (Exception ex) { @@ -1045,21 +944,25 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Document.Add(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension); - else - _LastChanged = Document.Update(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, ref _LastChanged, _FileExtension); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Document.Add(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension); + else + _LastChanged = Document.Update(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, ref _LastChanged, _FileExtension); + } + MarkOld(); } - if (_DocumentEntries != null) _DocumentEntries.Update(this); - if (_DocumentDROUsages != null) _DocumentDROUsages.Update(this); - if (_DocumentPdfs != null) _DocumentPdfs.Update(this); + _DocumentEntries?.Update(this); + _DocumentDROUsages?.Update(this); + _DocumentPdfs?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, ref byte[] lastChanged, string fileExtension) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Update", 0); @@ -1081,8 +984,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@FileExtension", fileExtension); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1096,12 +1001,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Document.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_DocID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_DocID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Delete", GetHashCode()); @@ -1126,7 +1028,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Document.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int docID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Remove", 0); @@ -1167,16 +1069,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _DocID; + private readonly int _DocID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int docID) - { - _DocID = docID; - } + public bool Exists => _exists; + public ExistsCommand(int docID) => _DocID = docID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Execute", GetHashCode()); @@ -1184,7 +1080,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1206,7 +1102,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - DocumentExtension _DocumentExtension = new DocumentExtension(); + readonly DocumentExtension _DocumentExtension = new DocumentExtension(); [Serializable()] partial class DocumentExtension : extensionBase { @@ -1215,18 +1111,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } - public virtual string DefaultFileExtension - { - get { return ".Doc"; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; + public virtual string DefaultFileExtension => ".Doc"; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1255,61 +1142,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Document) + if (destType == typeof(string) && value is Document doc) { // Return the ToString value - return ((Document)value).ToString(); + return doc.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocumentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Document -// { -// partial class DocumentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public virtual string DefaultFileExtension -// { -// get { return ".Doc"; } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAudit.cs index 7f1fdaf5..068f18c5 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshDocumentAudits.Add(this); } - private void ClearRefreshList() - { - _RefreshDocumentAudits = new List(); - } + private void ClearRefreshList() => _RefreshDocumentAudits = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DocumentAudit documentAudit) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(documentAudit)) _CacheList.Remove(documentAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -294,40 +285,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base DocumentAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocumentAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check DocumentAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocumentAudit - protected override object GetIdValue() - { - return MyDocumentAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocumentAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -355,8 +320,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -389,43 +354,11 @@ namespace VEPROMS.CSLA.Library _DocumentAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowRead(LibTitle, ""); - //AuthorizationRules.AllowRead(DocContent, ""); - //AuthorizationRules.AllowRead(DocAscii, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(FileExtension, ""); - //AuthorizationRules.AllowRead(DocPdf, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(DocID, ""); - //AuthorizationRules.AllowWrite(LibTitle, ""); - //AuthorizationRules.AllowWrite(DocContent, ""); - //AuthorizationRules.AllowWrite(DocAscii, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(FileExtension, ""); - //AuthorizationRules.AllowWrite(DocPdf, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); _DocumentAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -433,42 +366,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _DocumentAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocumentAuditUnique = 0; - protected static int DocumentAuditUnique - { get { return ++_DocumentAuditUnique; } } - private int _MyDocumentAuditUnique = DocumentAuditUnique; - public int MyDocumentAuditUnique // Absolutely Unique ID - Editable - { get { return _MyDocumentAuditUnique; } } + protected static int DocumentAuditUnique => ++_DocumentAuditUnique; + private readonly int _MyDocumentAuditUnique = DocumentAuditUnique; + // Absolutely Unique ID - Editable + public int MyDocumentAuditUnique => _MyDocumentAuditUnique; protected DocumentAudit() {/* require use of factory methods */ AddToCache(this); @@ -477,15 +382,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocumentAudit() { _CountFinalized++; @@ -510,8 +411,6 @@ namespace VEPROMS.CSLA.Library } public static DocumentAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a DocumentAudit"); try { return DataPortal.Create(); @@ -564,8 +463,6 @@ namespace VEPROMS.CSLA.Library } public static DocumentAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a DocumentAudit"); try { DocumentAudit tmp = GetCachedByPrimaryKey(auditID); @@ -591,14 +488,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new DocumentAudit(dr); return null; } - internal DocumentAudit(SafeDataReader dr) - { - ReadData(dr); - } + internal DocumentAudit(SafeDataReader dr) => ReadData(dr); public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a DocumentAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -610,12 +502,6 @@ namespace VEPROMS.CSLA.Library } public override DocumentAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a DocumentAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a DocumentAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a DocumentAudit"); try { BuildRefreshList(); @@ -635,13 +521,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -714,7 +596,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocumentAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -739,38 +621,44 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addDocumentAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@DocID", _DocID); - cm.Parameters.AddWithValue("@LibTitle", _LibTitle); - cm.Parameters.AddWithValue("@DocContent", _DocContent); - cm.Parameters.AddWithValue("@DocAscii", _DocAscii); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@FileExtension", _FileExtension); - cm.Parameters.AddWithValue("@DocPdf", _DocPdf); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addDocumentAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@DocID", _DocID); + cm.Parameters.AddWithValue("@LibTitle", _LibTitle); + cm.Parameters.AddWithValue("@DocContent", _DocContent); + cm.Parameters.AddWithValue("@DocAscii", _DocAscii); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@FileExtension", _FileExtension); + cm.Parameters.AddWithValue("@DocPdf", _DocPdf); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.SQLInsert", GetHashCode()); @@ -782,7 +670,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocumentAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension, byte[] docPdf, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Add", 0); @@ -805,8 +693,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@DocPdf", docPdf); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -821,7 +711,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocumentAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -844,39 +734,43 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateDocumentAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@DocID", _DocID); - cm.Parameters.AddWithValue("@LibTitle", _LibTitle); - cm.Parameters.AddWithValue("@DocContent", _DocContent); - cm.Parameters.AddWithValue("@DocAscii", _DocAscii); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@FileExtension", _FileExtension); - cm.Parameters.AddWithValue("@DocPdf", _DocPdf); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateDocumentAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@DocID", _DocID); + cm.Parameters.AddWithValue("@LibTitle", _LibTitle); + cm.Parameters.AddWithValue("@DocContent", _DocContent); + cm.Parameters.AddWithValue("@DocAscii", _DocAscii); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@FileExtension", _FileExtension); + cm.Parameters.AddWithValue("@DocPdf", _DocPdf); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -889,18 +783,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - DocumentAudit.Add(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus); - else - DocumentAudit.Update(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + DocumentAudit.Add(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus); + else + DocumentAudit.Update(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension, byte[] docPdf, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Update", 0); @@ -936,12 +834,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocumentAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_AuditID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AuditID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.DataPortal_Delete", GetHashCode()); @@ -966,7 +861,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("DocumentAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Remove", 0); @@ -992,7 +887,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - DocumentAuditExtension _DocumentAuditExtension = new DocumentAuditExtension(); + readonly DocumentAuditExtension _DocumentAuditExtension = new DocumentAuditExtension(); [Serializable()] partial class DocumentAuditExtension : extensionBase { @@ -1029,49 +924,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentAudit) + if (destType == typeof(string) && value is DocumentAudit audit) { // Return the ToString value - return ((DocumentAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocumentAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DocumentAudit -// { -// partial class DocumentAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfo.cs index a288f552..1ed1867a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class DocumentAuditInfo : ReadOnlyBase, IDisposable { public event DocumentAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DocumentAuditInfo documentAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(documentAuditInfo)) _CacheList.Remove(documentAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected DocumentAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -180,32 +164,19 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base DocumentAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocumentAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DocumentAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocumentAuditInfo - protected override object GetIdValue() - { - return MyDocumentAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocumentAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _DocumentAuditInfoUnique = 0; - private static int DocumentAuditInfoUnique - { get { return ++_DocumentAuditInfoUnique; } } - private int _MyDocumentAuditInfoUnique = DocumentAuditInfoUnique; - public int MyDocumentAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyDocumentAuditInfoUnique; } } + private static int DocumentAuditInfoUnique => ++_DocumentAuditInfoUnique; + private readonly int _MyDocumentAuditInfoUnique = DocumentAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyDocumentAuditInfoUnique => _MyDocumentAuditInfoUnique; protected DocumentAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -214,15 +185,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocumentAuditInfo() { _CountFinalized++; @@ -239,10 +206,7 @@ namespace VEPROMS.CSLA.Library if (listDocumentAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual DocumentAudit Get() - { - return _Editable = DocumentAudit.Get(_AuditID); - } + public virtual DocumentAudit Get() => _Editable = DocumentAudit.Get(_AuditID); public static void Refresh(DocumentAudit tmp) { string key = tmp.AuditID.ToString(); @@ -267,8 +231,6 @@ namespace VEPROMS.CSLA.Library } public static DocumentAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a DocumentAudit"); try { DocumentAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -307,13 +269,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -377,7 +335,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - DocumentAuditInfoExtension _DocumentAuditInfoExtension = new DocumentAuditInfoExtension(); + readonly DocumentAuditInfoExtension _DocumentAuditInfoExtension = new DocumentAuditInfoExtension(); [Serializable()] partial class DocumentAuditInfoExtension : extensionBase { } [Serializable()] @@ -393,10 +351,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentAuditInfo) + if (destType == typeof(string) && value is DocumentAuditInfo info) { // Return the ToString value - return ((DocumentAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfoList.cs index f5375756..ae249d1c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (DocumentAuditInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~DocumentAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocumentAuditInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DocumentAuditInfoList.Get", ex); } } - /// - /// Reset the list of all DocumentAuditInfo. - /// - public static void Reset() - { - _DocumentAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static DocumentAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on DocumentAuditInfoList.Get", ex); - // } - //} - private DocumentAuditInfoList() + /// + /// Reset the list of all DocumentAuditInfo. + /// + public static void Reset() => _DocumentAuditInfoList = null; + private DocumentAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocumentAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private DocumentAuditInfo Item { get { return (DocumentAuditInfo)_Item; } } public DocumentAuditInfoListPropertyDescriptor(DocumentAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentAuditInfoList) + if (destType == typeof(string) && value is DocumentAuditInfoList list) { // Return department and department role separated by comma. - return ((DocumentAuditInfoList)value).Items.Count.ToString() + " DocumentAudits"; + return $"{list.Items.Count} DocumentAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsage.cs index b3c396de..1467fd2d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsage.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _DROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int DROUsageID @@ -232,10 +226,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocumentDROUsage - protected override object GetIdValue() - { - return MyDocumentDROUsageUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocumentDROUsageUnique; // Absolutely Unique ID // CSLATODO: Replace base DocumentDROUsage.ToString function as necessary /// /// Overrides Base ToString @@ -259,18 +250,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRODb != null && _MyRODb.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRODb == null || _MyRODb.IsValidList(list)); } #endregion #region ValidationRules @@ -300,8 +288,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -331,78 +319,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DROUsageID, ""); - //AuthorizationRules.AllowRead(ROID, ""); - //AuthorizationRules.AllowWrite(ROID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowWrite(RODbID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocumentDROUsageUnique = 0; - private static int DocumentDROUsageUnique - { get { return ++_DocumentDROUsageUnique; } } - private int _MyDocumentDROUsageUnique = DocumentDROUsageUnique; - public int MyDocumentDROUsageUnique // Absolutely Unique ID - Editable FK - { get { return _MyDocumentDROUsageUnique; } } - internal static DocumentDROUsage New(string roid, RODb myRODb) - { - return new DocumentDROUsage(roid, myRODb); - } - internal static DocumentDROUsage Get(SafeDataReader dr) - { - return new DocumentDROUsage(dr); - } + private static int DocumentDROUsageUnique => ++_DocumentDROUsageUnique; + private readonly int _MyDocumentDROUsageUnique = DocumentDROUsageUnique; + // Absolutely Unique ID - Editable FK + public int MyDocumentDROUsageUnique => _MyDocumentDROUsageUnique; + internal static DocumentDROUsage New(string roid, RODb myRODb) => new DocumentDROUsage(roid, myRODb); + internal static DocumentDROUsage Get(SafeDataReader dr) => new DocumentDROUsage(dr); public DocumentDROUsage() { MarkAsChild(); @@ -431,15 +363,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocumentDROUsage() { _CountFinalized++; @@ -481,33 +409,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DROUsage.Add(cn, ref _DROUsageID, myDocument, _ROID, _Config, _DTS, _UserID, _MyRODb); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DROUsage.Add(cn, ref _DROUsageID, myDocument, _ROID, _Config, _DTS, _UserID, _MyRODb); + } + MarkOld(); } internal void Update(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DROUsage.Update(cn, ref _DROUsageID, myDocument.DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DROUsage.Update(cn, ref _DROUsageID, myDocument.DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - DROUsage.Remove(cn, _DROUsageID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + DROUsage.Remove(cn, _DROUsageID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - DocumentDROUsageExtension _DocumentDROUsageExtension = new DocumentDROUsageExtension(); + readonly DocumentDROUsageExtension _DocumentDROUsageExtension = new DocumentDROUsageExtension(); [Serializable()] partial class DocumentDROUsageExtension : extensionBase { @@ -516,18 +457,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultDocID - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultDocID => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -556,61 +488,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentDROUsage) + if (destType == typeof(string) && value is DocumentDROUsage usage) { // Return the ToString value - return ((DocumentDROUsage)value).ToString(); + return usage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocumentDROUsageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DocumentDROUsage -// { -// partial class DocumentDROUsageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultDocID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsages.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsages.cs index 6e620f8b..940eac31 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsages.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentDROUsages.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public DocumentDROUsage this[DROUsage myDROUsage] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public DocumentDROUsage this[DROUsage myDROUsage] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public DocumentDROUsage GetItem(DROUsage myDROUsage) + public new System.Collections.Generic.IList Items => base.Items; + public DocumentDROUsage GetItem(DROUsage myDROUsage) { foreach (DocumentDROUsage dROUsage in this) if (dROUsage.DROUsageID == myDROUsage.DROUsageID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public DocumentDROUsage Add(string roid, RODb myRODb) // One to Many { DocumentDROUsage dROUsage = DocumentDROUsage.New(roid, myRODb); - this.Add(dROUsage); + Add(dROUsage); return dROUsage; } public void Remove(DROUsage myDROUsage) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (DocumentDROUsage child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (DocumentDROUsage child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static DocumentDROUsages New() - { - return new DocumentDROUsages(); - } - internal static DocumentDROUsages Get(SafeDataReader dr) - { - return new DocumentDROUsages(dr); - } - public static DocumentDROUsages GetByDocID(int docID) + #endregion + #region Factory Methods + internal static DocumentDROUsages New() => new DocumentDROUsages(); + internal static DocumentDROUsages Get(SafeDataReader dr) => new DocumentDROUsages(dr); + public static DocumentDROUsages GetByDocID(int docID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DocumentDROUsages.GetByDocID", ex); } } - private DocumentDROUsages() - { - MarkAsChild(); - } - internal DocumentDROUsages(SafeDataReader dr) + private DocumentDROUsages() => MarkAsChild(); + internal DocumentDROUsages(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~DocumentDROUsages() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocumentDROUsages() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(DocumentDROUsage.Get(dr)); - this.RaiseListChangedEvents = true; + Add(DocumentDROUsage.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class DocIDCriteria { - public DocIDCriteria(int docID) - { - _DocID = docID; - } - private int _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + private int _DocID; public int DocID { get { return _DocID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(DocIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentDROUsages.DataPortal_FetchDocID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new DocumentDROUsage(dr)); + while (dr.Read()) Add(new DocumentDROUsage(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentDROUsages.DataPortal_FetchDocID", ex); throw new DbCslaException("DocumentDROUsages.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Document document) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DocumentDROUsagesPropertyDescriptor pd = new DocumentDROUsagesPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocumentDROUsagesPropertyDescriptor : vlnListPropertyDescriptor { - private DocumentDROUsage Item { get { return (DocumentDROUsage)_Item; } } public DocumentDROUsagesPropertyDescriptor(DocumentDROUsages collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentDROUsages) + if (destType == typeof(string) && value is DocumentDROUsages usages) { // Return department and department role separated by comma. - return ((DocumentDROUsages)value).Items.Count.ToString() + " DROUsages"; + return $"{usages.Items.Count} DROUsages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntries.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntries.cs index 882b3ac9..b1e429a6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntries.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntries.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public DocumentEntry this[Entry myEntry] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public DocumentEntry this[Entry myEntry] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public DocumentEntry GetItem(Entry myEntry) + public new System.Collections.Generic.IList Items => base.Items; + public DocumentEntry GetItem(Entry myEntry) { foreach (DocumentEntry entry in this) if (entry.ContentID == myEntry.ContentID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public DocumentEntry Add(Entry myEntry) // One to Many { DocumentEntry entry = DocumentEntry.New(myEntry); - this.Add(entry); + Add(entry); return entry; } public void Remove(Entry myEntry) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (DocumentEntry child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (DocumentEntry child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static DocumentEntries New() - { - return new DocumentEntries(); - } - internal static DocumentEntries Get(SafeDataReader dr) - { - return new DocumentEntries(dr); - } - public static DocumentEntries GetByDocID(int docID) + #endregion + #region Factory Methods + internal static DocumentEntries New() => new DocumentEntries(); + internal static DocumentEntries Get(SafeDataReader dr) => new DocumentEntries(dr); + public static DocumentEntries GetByDocID(int docID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DocumentEntries.GetByDocID", ex); } } - private DocumentEntries() - { - MarkAsChild(); - } - internal DocumentEntries(SafeDataReader dr) + private DocumentEntries() => MarkAsChild(); + internal DocumentEntries(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~DocumentEntries() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocumentEntries() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(DocumentEntry.Get(dr)); - this.RaiseListChangedEvents = true; + Add(DocumentEntry.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class DocIDCriteria { - public DocIDCriteria(int docID) - { - _DocID = docID; - } - private int _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + private int _DocID; public int DocID { get { return _DocID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(DocIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentEntries.DataPortal_FetchDocID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new DocumentEntry(dr)); + while (dr.Read()) Add(new DocumentEntry(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentEntries.DataPortal_FetchDocID", ex); throw new DbCslaException("DocumentEntries.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Document document) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DocumentEntriesPropertyDescriptor pd = new DocumentEntriesPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocumentEntriesPropertyDescriptor : vlnListPropertyDescriptor { - private DocumentEntry Item { get { return (DocumentEntry)_Item; } } public DocumentEntriesPropertyDescriptor(DocumentEntries collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentEntries) + if (destType == typeof(string) && value is DocumentEntries entries) { // Return department and department role separated by comma. - return ((DocumentEntries)value).Items.Count.ToString() + " Entries"; + return $"{entries.Items.Count} Entries"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntry.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntry.cs index 310f0ffe..f4c84960 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntry.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentEntry.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -170,35 +164,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocumentEntry - protected override object GetIdValue() - { - return MyDocumentEntryUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base DocumentEntry.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocumentEntry - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyDocumentEntryUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -226,8 +198,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -239,72 +211,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocumentEntryUnique = 0; - private static int DocumentEntryUnique - { get { return ++_DocumentEntryUnique; } } - private int _MyDocumentEntryUnique = DocumentEntryUnique; - public int MyDocumentEntryUnique // Absolutely Unique ID - Editable FK - { get { return _MyDocumentEntryUnique; } } - internal static DocumentEntry New(Entry myEntry) - { - return new DocumentEntry(myEntry); - } - internal static DocumentEntry Get(SafeDataReader dr) - { - return new DocumentEntry(dr); - } + private static int DocumentEntryUnique => ++_DocumentEntryUnique; + private readonly int _MyDocumentEntryUnique = DocumentEntryUnique; + // Absolutely Unique ID - Editable FK + public int MyDocumentEntryUnique => _MyDocumentEntryUnique; + internal static DocumentEntry New(Entry myEntry) => new DocumentEntry(myEntry); + internal static DocumentEntry Get(SafeDataReader dr) => new DocumentEntry(dr); public DocumentEntry() { MarkAsChild(); @@ -331,15 +253,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocumentEntry() { _CountFinalized++; @@ -379,33 +297,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Entry.Add(cn, _MyEntry.MyContent, myDocument, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Entry.Add(cn, _MyEntry.MyContent, myDocument, _DTS, _UserID); + } + MarkOld(); } internal void Update(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Entry.Update(cn, _ContentID, myDocument.DocID, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Entry.Update(cn, _ContentID, myDocument.DocID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Entry.Remove(cn, _ContentID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Entry.Remove(cn, _ContentID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - DocumentEntryExtension _DocumentEntryExtension = new DocumentEntryExtension(); + readonly DocumentEntryExtension _DocumentEntryExtension = new DocumentEntryExtension(); [Serializable()] partial class DocumentEntryExtension : extensionBase { @@ -414,14 +345,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -450,57 +375,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentEntry) + if (destType == typeof(string) && value is DocumentEntry entry) { // Return the ToString value - return ((DocumentEntry)value).ToString(); + return entry.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocumentEntryExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DocumentEntry -// { -// partial class DocumentEntryExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfo.cs index 073948a0..7fc7bd0b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class DocumentInfo : ReadOnlyBase, IDisposable { public event DocumentInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(DocumentInfo documentInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(documentInfo)) _CacheList.Remove(documentInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Document _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _DocID; [System.ComponentModel.DataObjectField(true, true)] public int DocID @@ -276,32 +260,19 @@ namespace VEPROMS.CSLA.Library foreach (DocumentInfo tmp in _CacheByPrimaryKey[_DocID.ToString()]) tmp._DocumentPdfCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base DocumentInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocumentInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check DocumentInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocumentInfo - protected override object GetIdValue() - { - return MyDocumentInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyDocumentInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _DocumentInfoUnique = 0; - private static int DocumentInfoUnique - { get { return ++_DocumentInfoUnique; } } - private int _MyDocumentInfoUnique = DocumentInfoUnique; - public int MyDocumentInfoUnique // Absolutely Unique ID - Info - { get { return _MyDocumentInfoUnique; } } + private static int DocumentInfoUnique => ++_DocumentInfoUnique; + private readonly int _MyDocumentInfoUnique = DocumentInfoUnique; + // Absolutely Unique ID - Info + public int MyDocumentInfoUnique => _MyDocumentInfoUnique; protected DocumentInfo() {/* require use of factory methods */ AddToCache(this); @@ -310,15 +281,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocumentInfo() { _CountFinalized++; @@ -335,10 +302,7 @@ namespace VEPROMS.CSLA.Library if (listDocumentInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(DocID.ToString()); // remove the list } - public virtual Document Get() - { - return _Editable = Document.Get(_DocID); - } + public virtual Document Get() => _Editable = Document.Get(_DocID); public static void Refresh(Document tmp) { string key = tmp.DocID.ToString(); @@ -361,8 +325,6 @@ namespace VEPROMS.CSLA.Library } public static DocumentInfo Get(int docID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Document"); try { DocumentInfo tmp = GetCachedByPrimaryKey(docID); @@ -401,13 +363,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - public PKCriteria(int docID) - { - _DocID = docID; - } + private readonly int _DocID; + public int DocID => _DocID; + public PKCriteria(int docID) => _DocID = docID; } private void ReadData(SafeDataReader dr) { @@ -472,7 +430,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - DocumentInfoExtension _DocumentInfoExtension = new DocumentInfoExtension(); + readonly DocumentInfoExtension _DocumentInfoExtension = new DocumentInfoExtension(); [Serializable()] partial class DocumentInfoExtension : extensionBase { } [Serializable()] @@ -488,10 +446,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentInfo) + if (destType == typeof(string) && value is DocumentInfo info) { // Return the ToString value - return ((DocumentInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfoList.cs index e7223ded..9d21bef0 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (DocumentInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~DocumentInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocumentInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DocumentInfoList.Get", ex); } } - /// - /// Reset the list of all DocumentInfo. - /// - public static void Reset() - { - _DocumentInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static DocumentInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on DocumentInfoList.Get", ex); - // } - //} - private DocumentInfoList() + /// + /// Reset the list of all DocumentInfo. + /// + public static void Reset() => _DocumentInfoList = null; + private DocumentInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new DocumentInfo(dr)); + while (dr.Read()) Add(new DocumentInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocumentInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DocumentInfoListPropertyDescriptor pd = new DocumentInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocumentInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private DocumentInfo Item { get { return (DocumentInfo)_Item; } } public DocumentInfoListPropertyDescriptor(DocumentInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentInfoList) + if (destType == typeof(string) && value is DocumentInfoList list) { // Return department and department role separated by comma. - return ((DocumentInfoList)value).Items.Count.ToString() + " Documents"; + return $"{list.Items.Count} Documents"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdf.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdf.cs index dbfedc0e..45f39aa7 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdf.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdf.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _DebugStatus; /// /// > 0 for Debug @@ -171,35 +165,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current DocumentPdf - protected override object GetIdValue() - { - return MyDocumentPdfUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base DocumentPdf.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current DocumentPdf - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyDocumentPdfUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -227,8 +199,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -240,80 +212,21 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DebugStatus, ""); - //AuthorizationRules.AllowRead(TopRow, ""); - //AuthorizationRules.AllowRead(PageLength, ""); - //AuthorizationRules.AllowRead(LeftMargin, ""); - //AuthorizationRules.AllowRead(PageWidth, ""); - //AuthorizationRules.AllowRead(PageCount, ""); - //AuthorizationRules.AllowWrite(PageCount, ""); - //AuthorizationRules.AllowRead(DocPdf, ""); - //AuthorizationRules.AllowWrite(DocPdf, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _DocumentPdfUnique = 0; - private static int DocumentPdfUnique - { get { return ++_DocumentPdfUnique; } } - private int _MyDocumentPdfUnique = DocumentPdfUnique; - public int MyDocumentPdfUnique // Absolutely Unique ID - Editable FK - { get { return _MyDocumentPdfUnique; } } - internal static DocumentPdf New(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount) - { - return new DocumentPdf(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount); - } - internal static DocumentPdf Get(SafeDataReader dr) - { - return new DocumentPdf(dr); - } + private static int DocumentPdfUnique => ++_DocumentPdfUnique; + private readonly int _MyDocumentPdfUnique = DocumentPdfUnique; + // Absolutely Unique ID - Editable FK + public int MyDocumentPdfUnique => _MyDocumentPdfUnique; + internal static DocumentPdf New(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount) => new DocumentPdf(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount); + internal static DocumentPdf Get(SafeDataReader dr) => new DocumentPdf(dr); public DocumentPdf() { MarkAsChild(); @@ -345,15 +258,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~DocumentPdf() { _CountFinalized++; @@ -392,33 +301,45 @@ namespace VEPROMS.CSLA.Library internal void Insert(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Pdf.Add(cn, myDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Pdf.Add(cn, myDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID); + } + MarkOld(); } internal void Update(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Pdf.Update(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Pdf.Update(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } internal void DeleteSelf(Document myDocument) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Pdf.Remove(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Pdf.Remove(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth); + } + MarkNew(); } #endregion // Standard Default Code #region extension - DocumentPdfExtension _DocumentPdfExtension = new DocumentPdfExtension(); + readonly DocumentPdfExtension _DocumentPdfExtension = new DocumentPdfExtension(); [Serializable()] partial class DocumentPdfExtension : extensionBase { @@ -427,14 +348,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -463,57 +378,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentPdf) + if (destType == typeof(string) && value is DocumentPdf docpdf) { // Return the ToString value - return ((DocumentPdf)value).ToString(); + return docpdf.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create DocumentPdfExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class DocumentPdf -// { -// partial class DocumentPdfExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdfs.cs b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdfs.cs index 5753f137..1b8fad0c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdfs.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/DocumentPdfs.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public DocumentPdf this[int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public DocumentPdf this[int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public DocumentPdf GetItem(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) + public new System.Collections.Generic.IList Items => base.Items; + public DocumentPdf GetItem(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { foreach (DocumentPdf pdf in this) if (pdf.DebugStatus == debugStatus && pdf.TopRow == topRow && pdf.PageLength == pageLength && pdf.LeftMargin == leftMargin && pdf.PageWidth == pageWidth) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(debugStatus, topRow, pageLength, leftMargin, pageWidth)) { DocumentPdf pdf = DocumentPdf.New(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount); - this.Add(pdf); + Add(pdf); return pdf; } else @@ -108,23 +100,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (DocumentPdf child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (DocumentPdf child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -142,20 +131,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static DocumentPdfs New() - { - return new DocumentPdfs(); - } - internal static DocumentPdfs Get(SafeDataReader dr) - { - return new DocumentPdfs(dr); - } - public static DocumentPdfs GetByDocID(int docID) + #endregion + #region Factory Methods + internal static DocumentPdfs New() => new DocumentPdfs(); + internal static DocumentPdfs Get(SafeDataReader dr) => new DocumentPdfs(dr); + public static DocumentPdfs GetByDocID(int docID) { try { @@ -166,11 +149,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on DocumentPdfs.GetByDocID", ex); } } - private DocumentPdfs() - { - MarkAsChild(); - } - internal DocumentPdfs(SafeDataReader dr) + private DocumentPdfs() => MarkAsChild(); + internal DocumentPdfs(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -179,16 +159,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~DocumentPdfs() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~DocumentPdfs() { _CountFinalized++; } @@ -203,19 +179,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(DocumentPdf.Get(dr)); - this.RaiseListChangedEvents = true; + Add(DocumentPdf.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class DocIDCriteria { - public DocIDCriteria(int docID) - { - _DocID = docID; - } - private int _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + private int _DocID; public int DocID { get { return _DocID; } @@ -224,7 +197,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(DocIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentPdfs.DataPortal_FetchDocID", GetHashCode()); try { @@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new DocumentPdf(dr)); + while (dr.Read()) Add(new DocumentPdf(dr)); } } } @@ -248,11 +221,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentPdfs.DataPortal_FetchDocID", ex); throw new DbCslaException("DocumentPdfs.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Document document) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -271,49 +244,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection DocumentPdfsPropertyDescriptor pd = new DocumentPdfsPropertyDescriptor(this, i); @@ -330,7 +292,6 @@ namespace VEPROMS.CSLA.Library /// public partial class DocumentPdfsPropertyDescriptor : vlnListPropertyDescriptor { - private DocumentPdf Item { get { return (DocumentPdf)_Item; } } public DocumentPdfsPropertyDescriptor(DocumentPdfs collection, int index) : base(collection, index) { ;} } #endregion @@ -339,10 +300,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is DocumentPdfs) + if (destType == typeof(string) && value is DocumentPdfs pdfs) { // Return department and department role separated by comma. - return ((DocumentPdfs)value).Items.Count.ToString() + " Pdfs"; + return $"{pdfs.Items.Count} Pdfs"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Entry.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Entry.cs index 952061b9..825f6956 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Entry.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Entry.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -57,6 +55,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Entry entry) { @@ -66,6 +65,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(entry)) _CacheList.Remove(entry); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -91,10 +91,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -199,7 +196,7 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)); + return base.IsDirty || (_MyDocument != null && _MyDocument.IsDirtyList(list)); } public override bool IsValid { @@ -208,28 +205,16 @@ namespace VEPROMS.CSLA.Library public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocument == null || _MyDocument.IsValidList(list)); } - // CSLATODO: Replace base Entry.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Entry - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Entry.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Entry - protected override object GetIdValue() - { - return MyEntryUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyEntryUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -258,8 +243,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -288,29 +273,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(DocID, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _EntryExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -318,42 +285,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _EntryExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _EntryUnique = 0; - protected static int EntryUnique - { get { return ++_EntryUnique; } } - private int _MyEntryUnique = EntryUnique; - public int MyEntryUnique // Absolutely Unique ID - Editable - { get { return _MyEntryUnique; } } + protected static int EntryUnique => ++_EntryUnique; + private readonly int _MyEntryUnique = EntryUnique; + // Absolutely Unique ID - Editable + public int MyEntryUnique => _MyEntryUnique; protected Entry() {/* require use of factory methods */ AddToCache(this); @@ -362,15 +301,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Entry() { _CountFinalized++; @@ -395,8 +330,6 @@ namespace VEPROMS.CSLA.Library } public static Entry New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Entry"); try { return DataPortal.Create(); @@ -464,8 +397,6 @@ namespace VEPROMS.CSLA.Library } public static Entry Get(int contentID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Entry"); try { Entry tmp = GetCachedByPrimaryKey(contentID); @@ -491,14 +422,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Entry(dr); return null; } - internal Entry(SafeDataReader dr) - { - ReadData(dr); - } + internal Entry(SafeDataReader dr) => ReadData(dr); public static void Delete(int contentID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Entry"); try { DataPortal.Delete(new PKCriteria(contentID)); @@ -510,12 +436,6 @@ namespace VEPROMS.CSLA.Library } public override Entry Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Entry"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Entry"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Entry"); try { BuildRefreshList(); @@ -535,13 +455,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -609,7 +525,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Entry.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -634,33 +550,39 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyDocument != null) _MyDocument.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyDocument?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addEntry"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@DocID", DocID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addEntry"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@DocID", DocID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.SQLInsert", GetHashCode()); @@ -672,7 +594,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Entry.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Content myContent, Document myDocument, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Add", 0); @@ -689,8 +611,10 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -704,7 +628,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Entry.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -727,38 +651,44 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.SQLUpdate", GetHashCode()); try { - if (_MyDocument != null) _MyDocument.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyDocument?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateEntry"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@DocID", DocID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateEntry"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@DocID", DocID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -771,14 +701,18 @@ namespace VEPROMS.CSLA.Library } internal void Update(Content content) { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Entry.Add(cn, content, MyDocument, _DTS, _UserID); - else - _LastChanged = Entry.Update(cn, content.ContentID, _DocID, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Entry.Add(cn, content, MyDocument, _DTS, _UserID); + else + _LastChanged = Entry.Update(cn, content.ContentID, _DocID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); // B2018-126 & B2018-133: Refresh for library document usage change (note that original checkin had a null check for // _MyDocument.DocumentEntries that was causing a sql Distributed Transaction Coordinator error - this was removed @@ -790,7 +724,7 @@ namespace VEPROMS.CSLA.Library } } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int contentID, int docID, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Update", 0); @@ -808,8 +742,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -823,12 +759,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Entry.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_ContentID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_ContentID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Delete", GetHashCode()); @@ -853,7 +786,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Entry.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int contentID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Remove", 0); @@ -894,16 +827,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ContentID; + private readonly int _ContentID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int contentID) - { - _ContentID = contentID; - } + public bool Exists => _exists; + public ExistsCommand(int contentID) => _ContentID = contentID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Execute", GetHashCode()); @@ -911,7 +838,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -933,7 +860,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - EntryExtension _EntryExtension = new EntryExtension(); + readonly EntryExtension _EntryExtension = new EntryExtension(); [Serializable()] partial class EntryExtension : extensionBase { @@ -942,14 +869,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -978,57 +899,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Entry) + if (destType == typeof(string) && value is Entry entry) { // Return the ToString value - return ((Entry)value).ToString(); + return entry.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create EntryExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Entry -// { -// partial class EntryExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/EntryAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/EntryAudit.cs index 1355ef3f..bce7425e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/EntryAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/EntryAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshEntryAudits.Add(this); } - private void ClearRefreshList() - { - _RefreshEntryAudits = new List(); - } + private void ClearRefreshList() => _RefreshEntryAudits = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(EntryAudit entryAudit) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(entryAudit)) _CacheList.Remove(entryAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -200,40 +191,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base EntryAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current EntryAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check EntryAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current EntryAudit - protected override object GetIdValue() - { - return MyEntryAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyEntryAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -261,8 +226,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -281,33 +246,11 @@ namespace VEPROMS.CSLA.Library _EntryAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(DocID, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); _EntryAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -315,42 +258,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _EntryAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _EntryAuditUnique = 0; - protected static int EntryAuditUnique - { get { return ++_EntryAuditUnique; } } - private int _MyEntryAuditUnique = EntryAuditUnique; - public int MyEntryAuditUnique // Absolutely Unique ID - Editable - { get { return _MyEntryAuditUnique; } } + protected static int EntryAuditUnique => ++_EntryAuditUnique; + private readonly int _MyEntryAuditUnique = EntryAuditUnique; + // Absolutely Unique ID - Editable + public int MyEntryAuditUnique => _MyEntryAuditUnique; protected EntryAudit() {/* require use of factory methods */ AddToCache(this); @@ -359,15 +274,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~EntryAudit() { _CountFinalized++; @@ -392,8 +303,6 @@ namespace VEPROMS.CSLA.Library } public static EntryAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a EntryAudit"); try { return DataPortal.Create(); @@ -431,8 +340,6 @@ namespace VEPROMS.CSLA.Library } public static EntryAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a EntryAudit"); try { EntryAudit tmp = GetCachedByPrimaryKey(auditID); @@ -464,8 +371,6 @@ namespace VEPROMS.CSLA.Library } public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a EntryAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -477,12 +382,6 @@ namespace VEPROMS.CSLA.Library } public override EntryAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a EntryAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a EntryAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a EntryAudit"); try { BuildRefreshList(); @@ -502,13 +401,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -576,7 +471,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("EntryAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -601,33 +496,39 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addEntryAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@DocID", _DocID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addEntryAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@DocID", _DocID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.SQLInsert", GetHashCode()); @@ -639,7 +540,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("EntryAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int contentID, int docID, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Add", 0); @@ -657,8 +558,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -673,7 +576,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("EntryAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -696,34 +599,38 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateEntryAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@DocID", _DocID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateEntryAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@DocID", _DocID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -736,18 +643,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - EntryAudit.Add(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus); - else - EntryAudit.Update(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + EntryAudit.Add(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus); + else + EntryAudit.Update(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int contentID, int docID, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Update", 0); @@ -778,12 +689,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("EntryAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.DataPortal_Delete", GetHashCode()); @@ -808,7 +719,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("EntryAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Remove", 0); @@ -834,7 +745,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - EntryAuditExtension _EntryAuditExtension = new EntryAuditExtension(); + readonly EntryAuditExtension _EntryAuditExtension = new EntryAuditExtension(); [Serializable()] partial class EntryAuditExtension : extensionBase { @@ -871,49 +782,14 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is EntryAudit) + if (destType == typeof(string) && value is EntryAudit audit) { // Return the ToString value - return ((EntryAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion + } // Namespace - - -//// The following is a sample Extension File. You can use it to create EntryAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class EntryAudit -// { -// partial class EntryAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfo.cs index ca468c06..6b9d1493 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class EntryAuditInfo : ReadOnlyBase, IDisposable { public event EntryAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(EntryAuditInfo entryAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(entryAuditInfo)) _CacheList.Remove(entryAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected EntryAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -144,32 +128,19 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base EntryAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current EntryAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check EntryAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current EntryAuditInfo - protected override object GetIdValue() - { - return MyEntryAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyEntryAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _EntryAuditInfoUnique = 0; - private static int EntryAuditInfoUnique - { get { return ++_EntryAuditInfoUnique; } } - private int _MyEntryAuditInfoUnique = EntryAuditInfoUnique; - public int MyEntryAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyEntryAuditInfoUnique; } } + private static int EntryAuditInfoUnique => ++_EntryAuditInfoUnique; + private readonly int _MyEntryAuditInfoUnique = EntryAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyEntryAuditInfoUnique => _MyEntryAuditInfoUnique; protected EntryAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -178,15 +149,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~EntryAuditInfo() { _CountFinalized++; @@ -203,10 +170,7 @@ namespace VEPROMS.CSLA.Library if (listEntryAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual EntryAudit Get() - { - return _Editable = EntryAudit.Get(_AuditID); - } + public virtual EntryAudit Get() => _Editable = EntryAudit.Get(_AuditID); public static void Refresh(EntryAudit tmp) { string key = tmp.AuditID.ToString(); @@ -227,8 +191,6 @@ namespace VEPROMS.CSLA.Library } public static EntryAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a EntryAudit"); try { EntryAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -267,13 +229,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -333,7 +291,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - EntryAuditInfoExtension _EntryAuditInfoExtension = new EntryAuditInfoExtension(); + readonly EntryAuditInfoExtension _EntryAuditInfoExtension = new EntryAuditInfoExtension(); [Serializable()] partial class EntryAuditInfoExtension : extensionBase { } [Serializable()] @@ -349,10 +307,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is EntryAuditInfo) + if (destType == typeof(string) && value is EntryAuditInfo info) { // Return the ToString value - return ((EntryAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfoList.cs index 02cb4faa..c65ac324 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/EntryAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (EntryAuditInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~EntryAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~EntryAuditInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on EntryAuditInfoList.Get", ex); } } - /// - /// Reset the list of all EntryAuditInfo. - /// - public static void Reset() - { - _EntryAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static EntryAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on EntryAuditInfoList.Get", ex); - // } - //} - private EntryAuditInfoList() + /// + /// Reset the list of all EntryAuditInfo. + /// + public static void Reset() => _EntryAuditInfoList = null; + private EntryAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class EntryAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private EntryAuditInfo Item { get { return (EntryAuditInfo)_Item; } } public EntryAuditInfoListPropertyDescriptor(EntryAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is EntryAuditInfoList) + if (destType == typeof(string) && value is EntryAuditInfoList list) { // Return department and department role separated by comma. - return ((EntryAuditInfoList)value).Items.Count.ToString() + " EntryAudits"; + return $"{list.Items.Count} EntryAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfo.cs index 070f426c..06e4d74b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class EntryInfo : ReadOnlyBase, IDisposable { public event EntryInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(EntryInfo entryInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(entryInfo)) _CacheList.Remove(entryInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Entry _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -149,32 +133,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base EntryInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current EntryInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check EntryInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current EntryInfo - protected override object GetIdValue() - { - return MyEntryInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyEntryInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _EntryInfoUnique = 0; - private static int EntryInfoUnique - { get { return ++_EntryInfoUnique; } } - private int _MyEntryInfoUnique = EntryInfoUnique; - public int MyEntryInfoUnique // Absolutely Unique ID - Info - { get { return _MyEntryInfoUnique; } } + private static int EntryInfoUnique => ++_EntryInfoUnique; + private readonly int _MyEntryInfoUnique = EntryInfoUnique; + // Absolutely Unique ID - Info + public int MyEntryInfoUnique => _MyEntryInfoUnique; protected EntryInfo() {/* require use of factory methods */ AddToCache(this); @@ -183,15 +154,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~EntryInfo() { _CountFinalized++; @@ -208,10 +175,7 @@ namespace VEPROMS.CSLA.Library if (listEntryInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list } - public virtual Entry Get() - { - return _Editable = Entry.Get(_ContentID); - } + public virtual Entry Get() => _Editable = Entry.Get(_ContentID); public static void Refresh(Entry tmp) { string key = tmp.ContentID.ToString(); @@ -224,11 +188,11 @@ namespace VEPROMS.CSLA.Library { if (_DocID != tmp.DocID) { - if (MyDocument != null) MyDocument.RefreshDocumentEntries(); // Update List for old value + MyDocument?.RefreshDocumentEntries(); // Update List for old value _DocID = tmp.DocID; // Update the value } _MyDocument = null; // Reset list so that the next line gets a new list - if (MyDocument != null) MyDocument.RefreshDocumentEntries(); // Update List for new value + MyDocument?.RefreshDocumentEntries(); // Update List for new value _DTS = tmp.DTS; _UserID = tmp.UserID; _EntryInfoExtension.Refresh(this); @@ -251,8 +215,6 @@ namespace VEPROMS.CSLA.Library } public static EntryInfo Get(int contentID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Entry"); try { EntryInfo tmp = GetCachedByPrimaryKey(contentID); @@ -291,13 +253,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } private void ReadData(SafeDataReader dr) { @@ -355,7 +313,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - EntryInfoExtension _EntryInfoExtension = new EntryInfoExtension(); + readonly EntryInfoExtension _EntryInfoExtension = new EntryInfoExtension(); [Serializable()] partial class EntryInfoExtension : extensionBase { } [Serializable()] @@ -371,10 +329,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is EntryInfo) + if (destType == typeof(string) && value is EntryInfo info) { // Return the ToString value - return ((EntryInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfoList.cs index 9349c912..33b52e32 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/EntryInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (EntryInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~EntryInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~EntryInfoList() { _CountFinalized++; } @@ -104,18 +97,6 @@ namespace VEPROMS.CSLA.Library { _EntryInfoList = null; } - // CSLATODO: Add alternative gets - - //public static EntryInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on EntryInfoList.Get", ex); - // } - //} public static EntryInfoList GetByContentID(int contentID) { try @@ -180,11 +161,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -224,11 +202,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class DocIDCriteria { - public DocIDCriteria(int docID) - { - _DocID = docID; - } - private int _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + private int _DocID; public int DocID { get { return _DocID; } @@ -265,41 +240,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -321,7 +285,6 @@ namespace VEPROMS.CSLA.Library /// public partial class EntryInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private EntryInfo Item { get { return (EntryInfo)_Item; } } public EntryInfoListPropertyDescriptor(EntryInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +293,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is EntryInfoList) + if (destType == typeof(string) && value is EntryInfoList list) { // Return department and department role separated by comma. - return ((EntryInfoList)value).Items.Count.ToString() + " Entries"; + return $"{list.Items.Count} Entries"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Figure.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Figure.cs index 03cbc464..7ba5d181 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Figure.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Figure.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -58,6 +56,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List
_CacheList = new List
(); protected static void AddToCache(Figure figure) { @@ -67,7 +66,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(figure)) _CacheList.Remove(figure); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByROFstID_ImageID = new Dictionary>(); private static void ConvertListToDictionary() { @@ -102,15 +103,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextFigureID = -1; - public static int NextFigureID - { - get { return _nextFigureID--; } - } + public static int NextFigureID => _nextFigureID--; private int _FigureID; [System.ComponentModel.DataObjectField(true, true)] public int FigureID @@ -252,37 +247,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyROFst == null ? false : _MyROFst.IsDirtyList(list)) || (_MyROImage == null ? false : _MyROImage.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyROFst != null && _MyROFst.IsDirtyList(list)) || (_MyROImage != null && _MyROImage.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyROFst == null ? true : _MyROFst.IsValidList(list)) && (_MyROImage == null ? true : _MyROImage.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyROFst == null || _MyROFst.IsValidList(list)) && (_MyROImage == null || _MyROImage.IsValidList(list)); } - // CSLATODO: Replace base Figure.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Figure - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Figure.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Figure - protected override object GetIdValue() - { - return MyFigureUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFigureUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -312,8 +292,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -355,33 +335,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FigureID, ""); - //AuthorizationRules.AllowRead(ROFstID, ""); - //AuthorizationRules.AllowRead(ImageID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ROFstID, ""); - //AuthorizationRules.AllowWrite(ImageID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _FigureExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -389,42 +347,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _FigureExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FigureUnique = 0; - protected static int FigureUnique - { get { return ++_FigureUnique; } } - private int _MyFigureUnique = FigureUnique; - public int MyFigureUnique // Absolutely Unique ID - Editable - { get { return _MyFigureUnique; } } + protected static int FigureUnique => ++_FigureUnique; + private readonly int _MyFigureUnique = FigureUnique; + // Absolutely Unique ID - Editable + public int MyFigureUnique => _MyFigureUnique; protected Figure() {/* require use of factory methods */ AddToCache(this); @@ -433,15 +363,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Figure() { _CountFinalized++; @@ -478,8 +404,6 @@ namespace VEPROMS.CSLA.Library } public static Figure New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Figure"); try { return DataPortal.Create
(); @@ -548,8 +472,6 @@ namespace VEPROMS.CSLA.Library } public static Figure Get(int figureID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Figure"); try { Figure tmp = GetCachedByPrimaryKey(figureID); @@ -572,8 +494,6 @@ namespace VEPROMS.CSLA.Library } public static Figure GetByROFstID_ImageID(int rOFstID, int imageID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Figure"); try { Figure tmp = GetCachedByROFstID_ImageID(rOFstID, imageID); @@ -599,14 +519,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Figure(dr); return null; } - internal Figure(SafeDataReader dr) - { - ReadData(dr); - } + internal Figure(SafeDataReader dr) => ReadData(dr); public static void Delete(int figureID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Figure"); try { DataPortal.Delete(new PKCriteria(figureID)); @@ -618,12 +533,6 @@ namespace VEPROMS.CSLA.Library } public override Figure Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Figure"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Figure"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Figure"); try { BuildRefreshList(); @@ -643,23 +552,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _FigureID; - public int FigureID - { get { return _FigureID; } } - public PKCriteria(int figureID) - { - _FigureID = figureID; - } + private readonly int _FigureID; + public int FigureID => _FigureID; + public PKCriteria(int figureID) => _FigureID = figureID; } [Serializable()] private class ROFstID_ImageIDCriteria { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - private int _ImageID; - public int ImageID - { get { return _ImageID; } } + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + private readonly int _ImageID; + public int ImageID => _ImageID; public ROFstID_ImageIDCriteria(int rOFstID, int imageID) { _ROFstID = rOFstID; @@ -771,7 +674,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Figure.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -796,39 +699,47 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyROFst != null) _MyROFst.Update(); - if (_MyROImage != null) _MyROImage.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyROFst?.Update(); + _MyROImage?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addFigure"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ROFstID", ROFstID); - cm.Parameters.AddWithValue("@ImageID", ImageID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int); - param_FigureID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_FigureID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _FigureID = (int)cm.Parameters["@newFigureID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addFigure"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ROFstID", ROFstID); + cm.Parameters.AddWithValue("@ImageID", ImageID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_FigureID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _FigureID = (int)cm.Parameters["@newFigureID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.SQLInsert", GetHashCode()); @@ -840,7 +751,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Figure.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int figureID, ROFst myROFst, ROImage myROImage, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Add", 0); @@ -858,11 +769,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int); - param_FigureID.Direction = ParameterDirection.Output; + SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_FigureID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -877,7 +792,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Figure.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -900,41 +815,47 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.SQLUpdate", GetHashCode()); try { - if (_MyROFst != null) _MyROFst.Update(); - if (_MyROImage != null) _MyROImage.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyROFst?.Update(); + _MyROImage?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateFigure"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@FigureID", _FigureID); - cm.Parameters.AddWithValue("@ROFstID", ROFstID); - cm.Parameters.AddWithValue("@ImageID", ImageID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateFigure"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@FigureID", _FigureID); + cm.Parameters.AddWithValue("@ROFstID", ROFstID); + cm.Parameters.AddWithValue("@ImageID", ImageID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -947,18 +868,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Figure.Add(cn, ref _FigureID, _MyROFst, _MyROImage, _Config, _DTS, _UserID); - else - _LastChanged = Figure.Update(cn, ref _FigureID, _ROFstID, _ImageID, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Figure.Add(cn, ref _FigureID, _MyROFst, _MyROImage, _Config, _DTS, _UserID); + else + _LastChanged = Figure.Update(cn, ref _FigureID, _ROFstID, _ImageID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int figureID, int rOFstID, int imageID, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Update", 0); @@ -978,8 +903,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -993,12 +920,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Figure.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_FigureID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Delete", GetHashCode()); @@ -1023,7 +950,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Figure.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int figureID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Remove", 0); @@ -1064,16 +991,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _FigureID; + private readonly int _FigureID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int figureID) - { - _FigureID = figureID; - } + public bool Exists => _exists; + public ExistsCommand(int figureID) => _FigureID = figureID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Execute", GetHashCode()); @@ -1081,7 +1002,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1103,7 +1024,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - FigureExtension _FigureExtension = new FigureExtension(); + readonly FigureExtension _FigureExtension = new FigureExtension(); [Serializable()] partial class FigureExtension : extensionBase { @@ -1112,14 +1033,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1148,57 +1063,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Figure) + if (destType == typeof(string) && value is Figure figure) { // Return the ToString value - return ((Figure)value).ToString(); + return figure.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FigureExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Figure -// { -// partial class FigureExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfo.cs index 9d2167f6..8453a2f7 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class FigureInfo : ReadOnlyBase, IDisposable { public event FigureInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(FigureInfo figureInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(figureInfo)) _CacheList.Remove(figureInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Figure _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _FigureID; [System.ComponentModel.DataObjectField(true, true)] public int FigureID @@ -166,32 +150,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base FigureInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current FigureInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check FigureInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FigureInfo - protected override object GetIdValue() - { - return MyFigureInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFigureInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _FigureInfoUnique = 0; - private static int FigureInfoUnique - { get { return ++_FigureInfoUnique; } } - private int _MyFigureInfoUnique = FigureInfoUnique; - public int MyFigureInfoUnique // Absolutely Unique ID - Info - { get { return _MyFigureInfoUnique; } } + private static int FigureInfoUnique => ++_FigureInfoUnique; + private readonly int _MyFigureInfoUnique = FigureInfoUnique; + // Absolutely Unique ID - Info + public int MyFigureInfoUnique => _MyFigureInfoUnique; protected FigureInfo() {/* require use of factory methods */ AddToCache(this); @@ -200,15 +171,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FigureInfo() { _CountFinalized++; @@ -225,10 +192,7 @@ namespace VEPROMS.CSLA.Library if (listFigureInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(FigureID.ToString()); // remove the list } - public virtual Figure Get() - { - return _Editable = Figure.Get(_FigureID); - } + public virtual Figure Get() => _Editable = Figure.Get(_FigureID); public static void Refresh(Figure tmp) { string key = tmp.FigureID.ToString(); @@ -241,18 +205,18 @@ namespace VEPROMS.CSLA.Library { if (_ROFstID != tmp.ROFstID) { - if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for old value + MyROFst?.RefreshROFstFigures(); // Update List for old value _ROFstID = tmp.ROFstID; // Update the value } _MyROFst = null; // Reset list so that the next line gets a new list - if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for new value + MyROFst?.RefreshROFstFigures(); // Update List for new value if (_ImageID != tmp.ImageID) { - if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for old value + MyROImage?.RefreshROImageFigures(); // Update List for old value _ImageID = tmp.ImageID; // Update the value } _MyROImage = null; // Reset list so that the next line gets a new list - if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for new value + MyROImage?.RefreshROImageFigures(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -271,11 +235,11 @@ namespace VEPROMS.CSLA.Library { if (_ImageID != tmp.ImageID) { - if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for old value + MyROImage?.RefreshROImageFigures(); // Update List for old value _ImageID = tmp.ImageID; // Update the value } _MyROImage = null; // Reset list so that the next line gets a new list - if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for new value + MyROImage?.RefreshROImageFigures(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -294,11 +258,11 @@ namespace VEPROMS.CSLA.Library { if (_ROFstID != tmp.ROFstID) { - if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for old value + MyROFst?.RefreshROFstFigures(); // Update List for old value _ROFstID = tmp.ROFstID; // Update the value } _MyROFst = null; // Reset list so that the next line gets a new list - if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for new value + MyROFst?.RefreshROFstFigures(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -307,8 +271,6 @@ namespace VEPROMS.CSLA.Library } public static FigureInfo Get(int figureID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Figure"); try { FigureInfo tmp = GetCachedByPrimaryKey(figureID); @@ -347,13 +309,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _FigureID; - public int FigureID - { get { return _FigureID; } } - public PKCriteria(int figureID) - { - _FigureID = figureID; - } + private readonly int _FigureID; + public int FigureID => _FigureID; + public PKCriteria(int figureID) => _FigureID = figureID; } private string _ROImage_FileName = string.Empty; public string ROImage_FileName @@ -427,7 +385,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - FigureInfoExtension _FigureInfoExtension = new FigureInfoExtension(); + readonly FigureInfoExtension _FigureInfoExtension = new FigureInfoExtension(); [Serializable()] partial class FigureInfoExtension : extensionBase { } [Serializable()] @@ -443,10 +401,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FigureInfo) + if (destType == typeof(string) && value is FigureInfo info) { // Return the ToString value - return ((FigureInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfoList.cs index 2c206538..d4300091 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FigureInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (FigureInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FigureInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FigureInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FigureInfoList.Get", ex); } } - /// - /// Reset the list of all FigureInfo. - /// - public static void Reset() - { - _FigureInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static FigureInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on FigureInfoList.Get", ex); - // } - //} - public static FigureInfoList GetByROFstID(int rOFstID) + /// + /// Reset the list of all FigureInfo. + /// + public static void Reset() => _FigureInfoList = null; + public static FigureInfoList GetByROFstID(int rOFstID) { try { @@ -180,11 +158,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ROFstIDCriteria { - public ROFstIDCriteria(int rOFstID) - { - _ROFstID = rOFstID; - } - private int _ROFstID; + public ROFstIDCriteria(int rOFstID) => _ROFstID = rOFstID; + private int _ROFstID; public int ROFstID { get { return _ROFstID; } @@ -224,11 +199,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ImageIDCriteria { - public ImageIDCriteria(int imageID) - { - _ImageID = imageID; - } - private int _ImageID; + public ImageIDCriteria(int imageID) => _ImageID = imageID; + private int _ImageID; public int ImageID { get { return _ImageID; } @@ -265,41 +237,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -321,7 +282,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FigureInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private FigureInfo Item { get { return (FigureInfo)_Item; } } public FigureInfoListPropertyDescriptor(FigureInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +290,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FigureInfoList) + if (destType == typeof(string) && value is FigureInfoList list) { // Return department and department role separated by comma. - return ((FigureInfoList)value).Items.Count.ToString() + " Figures"; + return $"{list.Items.Count} Figures"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Folder.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Folder.cs index 0232759d..b8832359 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Folder.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Folder.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -91,6 +89,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Folder folder) { @@ -100,7 +99,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(folder)) _CacheList.Remove(folder); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByParentID_Name = new Dictionary>(); private static void ConvertListToDictionary() { @@ -135,15 +136,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextFolderID = -1; - public static int NextFolderID - { - get { return _nextFolderID--; } - } + public static int NextFolderID => _nextFolderID--; private int _FolderID; [System.ComponentModel.DataObjectField(true, true)] public int FolderID @@ -407,10 +402,7 @@ namespace VEPROMS.CSLA.Library return _FolderAssignments; } } - public void Reset_FolderAssignments() - { - _FolderAssignmentCount = -1; - } + public void Reset_FolderAssignments() => _FolderAssignmentCount = -1; private int _FolderDocVersionCount = 0; /// /// Count of FolderDocVersions for this Folder @@ -442,10 +434,7 @@ namespace VEPROMS.CSLA.Library return _FolderDocVersions; } } - public void Reset_FolderDocVersions() - { - _FolderDocVersionCount = -1; - } + public void Reset_FolderDocVersions() => _FolderDocVersionCount = -1; private int _ChildFolderCount = 0; /// /// Count of ChildFolders for this Folder @@ -477,10 +466,7 @@ namespace VEPROMS.CSLA.Library return _ChildFolders; } } - public void Reset_ChildFolders() - { - _ChildFolderCount = -1; - } + public void Reset_ChildFolders() => _ChildFolderCount = -1; public override bool IsDirty { get @@ -495,37 +481,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_FolderAssignments == null ? false : _FolderAssignments.IsDirtyList(list)) || (_FolderDocVersions == null ? false : _FolderDocVersions.IsDirtyList(list)) || (_ChildFolders == null ? false : _ChildFolders.IsDirtyList(list)) || (_MyConnection == null ? false : _MyConnection.IsDirtyList(list)) || (_MyFormat == null ? false : _MyFormat.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_FolderAssignments != null && _FolderAssignments.IsDirtyList(list)) || (_FolderDocVersions != null && _FolderDocVersions.IsDirtyList(list)) || (_ChildFolders != null && _ChildFolders.IsDirtyList(list)) || (_MyConnection != null && _MyConnection.IsDirtyList(list)) || (_MyFormat != null && _MyFormat.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_FolderAssignments == null ? true : _FolderAssignments.IsValidList(list)) && (_FolderDocVersions == null ? true : _FolderDocVersions.IsValidList(list)) && (_ChildFolders == null ? true : _ChildFolders.IsValidList(list)) && (_MyConnection == null ? true : _MyConnection.IsValidList(list)) && (_MyFormat == null ? true : _MyFormat.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_FolderAssignments == null || _FolderAssignments.IsValidList(list)) && (_FolderDocVersions == null || _FolderDocVersions.IsValidList(list)) && (_ChildFolders == null || _ChildFolders.IsValidList(list)) && (_MyConnection == null || _MyConnection.IsValidList(list)) && (_MyFormat == null || _MyFormat.IsValidList(list)); } - // CSLATODO: Replace base Folder.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Folder - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Folder.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Folder - protected override object GetIdValue() - { - return MyFolderUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFolderUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -558,8 +529,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -604,43 +575,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowRead(ParentID, ""); - //AuthorizationRules.AllowRead(DBID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowRead(ShortName, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowRead(ManualOrder, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(ParentID, ""); - //AuthorizationRules.AllowWrite(DBID, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowWrite(ShortName, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowWrite(ManualOrder, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); _FolderExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -648,57 +587,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _FolderExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _FolderAssignmentCount; - usedByCount += _FolderDocVersionCount; - usedByCount += _ChildFolderCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FolderUnique = 0; - protected static int FolderUnique - { get { return ++_FolderUnique; } } - private int _MyFolderUnique = FolderUnique; - public int MyFolderUnique // Absolutely Unique ID - Editable - { get { return _MyFolderUnique; } } + protected static int FolderUnique => ++_FolderUnique; + private readonly int _MyFolderUnique = FolderUnique; + // Absolutely Unique ID - Editable + public int MyFolderUnique => _MyFolderUnique; protected Folder() {/* require use of factory methods */ AddToCache(this); @@ -707,15 +603,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Folder() { _CountFinalized++; @@ -752,8 +644,6 @@ namespace VEPROMS.CSLA.Library } public static Folder New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Folder"); try { return DataPortal.Create(); @@ -860,8 +750,6 @@ namespace VEPROMS.CSLA.Library } public static Folder Get(int folderID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Folder"); try { Folder tmp = GetCachedByPrimaryKey(folderID); @@ -884,8 +772,6 @@ namespace VEPROMS.CSLA.Library } public static Folder GetByParentID_Name(int parentID, string name) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Folder"); try { Folder tmp = GetCachedByParentID_Name(parentID, name); @@ -911,15 +797,14 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Folder(dr, parent); return null; } - internal Folder(SafeDataReader dr) - { - ReadData(dr); - } + internal Folder(SafeDataReader dr) => ReadData(dr); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] private Folder(SafeDataReader dr, Folder parent) { ReadData(dr); MarkAsChild(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal Folder(SafeDataReader dr, int parentID) { ReadData(dr); @@ -927,8 +812,6 @@ namespace VEPROMS.CSLA.Library } public static void Delete(int folderID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Folder"); try { // B2019-060: On delete, remove the folder from cache: @@ -943,12 +826,6 @@ namespace VEPROMS.CSLA.Library } public override Folder Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Folder"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Folder"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Folder"); try { BuildRefreshList(); @@ -968,23 +845,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _FolderID; - public int FolderID - { get { return _FolderID; } } - public PKCriteria(int folderID) - { - _FolderID = folderID; - } + private readonly int _FolderID; + public int FolderID => _FolderID; + public PKCriteria(int folderID) => _FolderID = folderID; } [Serializable()] private class ParentID_NameCriteria { - private int _ParentID; - public int ParentID - { get { return _ParentID; } } - private string _Name; - public string Name - { get { return _Name; } } + private readonly int _ParentID; + public int ParentID => _ParentID; + private readonly string _Name; + public string Name => _Name; public ParentID_NameCriteria(int parentID, string name) { _ParentID = parentID; @@ -1112,7 +983,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Folder.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -1137,49 +1008,57 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyConnection != null) _MyConnection.Update(); - if (_MyFormat != null) _MyFormat.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyConnection?.Update(); + _MyFormat?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addFolder"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ParentID", ParentID); - cm.Parameters.AddWithValue("@DBID", DBID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - cm.Parameters.AddWithValue("@ShortName", _ShortName); - cm.Parameters.AddWithValue("@FormatID", FormatID); - cm.Parameters.AddWithValue("@ManualOrder", _ManualOrder); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_FolderID = new SqlParameter("@newFolderID", SqlDbType.Int); - param_FolderID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_FolderID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _FolderID = (int)cm.Parameters["@newFolderID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addFolder"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ParentID", ParentID); + cm.Parameters.AddWithValue("@DBID", DBID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + cm.Parameters.AddWithValue("@ShortName", _ShortName); + cm.Parameters.AddWithValue("@FormatID", FormatID); + cm.Parameters.AddWithValue("@ManualOrder", _ManualOrder); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_FolderID = new SqlParameter("@newFolderID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_FolderID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _FolderID = (int)cm.Parameters["@newFolderID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_FolderAssignments != null) _FolderAssignments.Update(this); - if (_FolderDocVersions != null) _FolderDocVersions.Update(this); - if (_ChildFolders != null) _ChildFolders.Update(this); + _FolderAssignments?.Update(this); + _FolderDocVersions?.Update(this); + _ChildFolders?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -1189,7 +1068,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Folder.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int folderID, Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Add", 0); @@ -1212,11 +1091,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_FolderID = new SqlParameter("@newFolderID", SqlDbType.Int); - param_FolderID.Direction = ParameterDirection.Output; + SqlParameter param_FolderID = new SqlParameter("@newFolderID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_FolderID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1231,7 +1114,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Folder.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1256,51 +1139,57 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.SQLUpdate", GetHashCode()); try { - if (_MyConnection != null) _MyConnection.Update(); - if (_MyFormat != null) _MyFormat.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyConnection?.Update(); + _MyFormat?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateFolder"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@FolderID", _FolderID); - cm.Parameters.AddWithValue("@ParentID", ParentID); - cm.Parameters.AddWithValue("@DBID", DBID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - cm.Parameters.AddWithValue("@ShortName", _ShortName); - cm.Parameters.AddWithValue("@FormatID", FormatID); - cm.Parameters.AddWithValue("@ManualOrder", _ManualOrder); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateFolder"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@FolderID", _FolderID); + cm.Parameters.AddWithValue("@ParentID", ParentID); + cm.Parameters.AddWithValue("@DBID", DBID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + cm.Parameters.AddWithValue("@ShortName", _ShortName); + cm.Parameters.AddWithValue("@FormatID", FormatID); + cm.Parameters.AddWithValue("@ManualOrder", _ManualOrder); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_FolderAssignments != null) _FolderAssignments.Update(this); - if (_FolderDocVersions != null) _FolderDocVersions.Update(this); - if (_ChildFolders != null) _ChildFolders.Update(this); + _FolderAssignments?.Update(this); + _FolderDocVersions?.Update(this); + _ChildFolders?.Update(this); } catch (Exception ex) { @@ -1313,31 +1202,40 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Folder.Add(cn, ref _FolderID, _MyParent, _MyConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID); - else - _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, _DBID, _Name, _Title, _ShortName, _FormatID, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Folder.Add(cn, ref _FolderID, _MyParent, _MyConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID); + else + _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, _DBID, _Name, _Title, _ShortName, _FormatID, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } - if (_FolderAssignments != null) _FolderAssignments.Update(this); - if (_FolderDocVersions != null) _FolderDocVersions.Update(this); - if (_ChildFolders != null) _ChildFolders.Update(this); + _FolderAssignments?.Update(this); + _FolderDocVersions?.Update(this); + _ChildFolders?.Update(this); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Folder folder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Folder.Remove(cn, _FolderID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Folder.Remove(cn, _FolderID); + } + MarkNew(); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int folderID, int parentID, int dbid, string name, string title, string shortName, int? formatID, double? manualOrder, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Update", 0); @@ -1362,8 +1260,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1377,12 +1277,9 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Folder.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] - protected override void DataPortal_DeleteSelf() - { - DataPortal_Delete(new PKCriteria(_FolderID)); - } - [Transactional(TransactionalTypes.TransactionScope)] + + protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_FolderID)); + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.DataPortal_Delete", GetHashCode()); @@ -1407,7 +1304,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Folder.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int folderID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Remove", 0); @@ -1431,7 +1328,7 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void DeleteFolderAdmin(int folderID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Remove", 0); @@ -1473,16 +1370,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _FolderID; + private readonly int _FolderID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int folderID) - { - _FolderID = folderID; - } + public bool Exists => _exists; + public ExistsCommand(int folderID) => _FolderID = folderID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.DataPortal_Execute", GetHashCode()); @@ -1490,7 +1381,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1512,7 +1403,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - FolderExtension _FolderExtension = new FolderExtension(); + readonly FolderExtension _FolderExtension = new FolderExtension(); [Serializable()] partial class FolderExtension : extensionBase { @@ -1521,22 +1412,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultParentID - { - get { return 1; } - } - public virtual int DefaultDBID - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultParentID => 1; + public virtual int DefaultDBID => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1565,65 +1444,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Folder) + if (destType == typeof(string) && value is Folder folder) { // Return the ToString value - return ((Folder)value).ToString(); + return folder.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FolderExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Folder -// { -// partial class FolderExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultParentID -// { -// get { return 1; } -// } -// public virtual int DefaultDBID -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignment.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignment.cs index c0ac2e5f..7bb1fbad 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignment.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignment.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _AID; [System.ComponentModel.DataObjectField(true, true)] public int AID @@ -298,19 +292,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FolderAssignment - protected override object GetIdValue() - { - return MyFolderAssignmentUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base FolderAssignment.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current FolderAssignment - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyFolderAssignmentUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -325,18 +307,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyGroup == null ? false : _MyGroup.IsDirtyList(list)) || (_MyRole == null ? false : _MyRole.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyGroup != null && _MyGroup.IsDirtyList(list)) || (_MyRole != null && _MyRole.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyGroup == null ? true : _MyGroup.IsValidList(list)) && (_MyRole == null ? true : _MyRole.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyGroup == null || _MyGroup.IsValidList(list)) && (_MyRole == null || _MyRole.IsValidList(list)); } #endregion #region ValidationRules @@ -367,8 +346,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -430,80 +409,21 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AID, ""); - //AuthorizationRules.AllowRead(GID, ""); - //AuthorizationRules.AllowWrite(GID, ""); - //AuthorizationRules.AllowRead(RID, ""); - //AuthorizationRules.AllowWrite(RID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FolderAssignmentUnique = 0; - private static int FolderAssignmentUnique - { get { return ++_FolderAssignmentUnique; } } - private int _MyFolderAssignmentUnique = FolderAssignmentUnique; - public int MyFolderAssignmentUnique // Absolutely Unique ID - Editable FK - { get { return _MyFolderAssignmentUnique; } } - internal static FolderAssignment New(Group myGroup, Role myRole) - { - return new FolderAssignment(myGroup, myRole); - } - internal static FolderAssignment Get(SafeDataReader dr) - { - return new FolderAssignment(dr); - } + private static int FolderAssignmentUnique => ++_FolderAssignmentUnique; + private readonly int _MyFolderAssignmentUnique = FolderAssignmentUnique; + // Absolutely Unique ID - Editable FK + public int MyFolderAssignmentUnique => _MyFolderAssignmentUnique; + internal static FolderAssignment New(Group myGroup, Role myRole) => new FolderAssignment(myGroup, myRole); + internal static FolderAssignment Get(SafeDataReader dr) => new FolderAssignment(dr); public FolderAssignment() { MarkAsChild(); @@ -534,15 +454,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FolderAssignment() { _CountFinalized++; @@ -588,33 +504,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Folder myFolder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, _MyRole, myFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, _MyRole, myFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + } + MarkOld(); } internal void Update(Folder myFolder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Assignment.Update(cn, ref _AID, _GID, _RID, myFolder.FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Assignment.Update(cn, ref _AID, _GID, _RID, myFolder.FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Folder myFolder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Assignment.Remove(cn, _AID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Assignment.Remove(cn, _AID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - FolderAssignmentExtension _FolderAssignmentExtension = new FolderAssignmentExtension(); + readonly FolderAssignmentExtension _FolderAssignmentExtension = new FolderAssignmentExtension(); [Serializable()] partial class FolderAssignmentExtension : extensionBase { @@ -623,18 +552,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -663,61 +583,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FolderAssignment) + if (destType == typeof(string) && value is FolderAssignment assignment) { // Return the ToString value - return ((FolderAssignment)value).ToString(); + return assignment.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FolderAssignmentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class FolderAssignment -// { -// partial class FolderAssignmentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignments.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignments.cs index cb9d4afe..75cac8dd 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignments.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FolderAssignments.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public FolderAssignment this[Assignment myAssignment] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public FolderAssignment this[Assignment myAssignment] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public FolderAssignment GetItem(Assignment myAssignment) + public new System.Collections.Generic.IList Items => base.Items; + public FolderAssignment GetItem(Assignment myAssignment) { foreach (FolderAssignment assignment in this) if (assignment.AID == myAssignment.AID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public FolderAssignment Add(Group myGroup, Role myRole) // One to Many { FolderAssignment assignment = FolderAssignment.New(myGroup, myRole); - this.Add(assignment); + Add(assignment); return assignment; } public void Remove(Assignment myAssignment) @@ -103,11 +95,8 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid - { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { // run through all the child objects // and if any are invalid then the @@ -137,7 +126,7 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } #endregion @@ -161,11 +150,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FolderAssignments.GetByFolderID", ex); } } - private FolderAssignments() - { - MarkAsChild(); - } - internal FolderAssignments(SafeDataReader dr) + private FolderAssignments() => MarkAsChild(); + internal FolderAssignments(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +160,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FolderAssignments() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FolderAssignments() { _CountFinalized++; } @@ -198,10 +180,10 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(FolderAssignment.Get(dr)); - this.RaiseListChangedEvents = true; + Add(FolderAssignment.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class FolderIDCriteria @@ -219,7 +201,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FolderIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FolderAssignments.DataPortal_FetchFolderID", GetHashCode()); try { @@ -233,7 +215,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new FolderAssignment(dr)); + while (dr.Read()) Add(new FolderAssignment(dr)); } } } @@ -243,11 +225,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("FolderAssignments.DataPortal_FetchFolderID", ex); throw new DbCslaException("FolderAssignments.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Folder folder) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +248,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public String GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public String GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection FolderAssignmentsPropertyDescriptor pd = new FolderAssignmentsPropertyDescriptor(this, i); @@ -325,7 +296,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FolderAssignmentsPropertyDescriptor : vlnListPropertyDescriptor { - private FolderAssignment Item { get { return (FolderAssignment)_Item; } } public FolderAssignmentsPropertyDescriptor(FolderAssignments collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +304,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FolderAssignments) + if (destType == typeof(string) && value is FolderAssignments assignments) { // Return department and department role separated by comma. - return ((FolderAssignments)value).Items.Count.ToString() + " Assignments"; + return $"{assignments.Items.Count} Assignments"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersion.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersion.cs index 6f7b15ed..15b8b309 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersion.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersion.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -239,35 +233,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FolderDocVersion - protected override object GetIdValue() - { - return MyFolderDocVersionUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base FolderDocVersion.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current FolderDocVersion - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyFolderDocVersionUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -297,8 +269,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -321,84 +293,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(VersionType, ""); - //AuthorizationRules.AllowWrite(VersionType, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FolderDocVersionUnique = 0; - private static int FolderDocVersionUnique - { get { return ++_FolderDocVersionUnique; } } - private int _MyFolderDocVersionUnique = FolderDocVersionUnique; - public int MyFolderDocVersionUnique // Absolutely Unique ID - Editable FK - { get { return _MyFolderDocVersionUnique; } } - internal static FolderDocVersion New(string name) - { - return new FolderDocVersion(name); - } - internal static FolderDocVersion Get(SafeDataReader dr) - { - return new FolderDocVersion(dr); - } + private static int FolderDocVersionUnique => ++_FolderDocVersionUnique; + private readonly int _MyFolderDocVersionUnique = FolderDocVersionUnique; + // Absolutely Unique ID - Editable FK + public int MyFolderDocVersionUnique => _MyFolderDocVersionUnique; + internal static FolderDocVersion New(string name) => new FolderDocVersion(name); + internal static FolderDocVersion Get(SafeDataReader dr) => new FolderDocVersion(dr); public FolderDocVersion() { MarkAsChild(); @@ -428,15 +338,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FolderDocVersion() { _CountFinalized++; @@ -475,33 +381,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Folder myFolder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DocVersion.Add(cn, ref _VersionID, myFolder, _VersionType, _Name, _Title, _MyItem, _MyFormat, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DocVersion.Add(cn, ref _VersionID, myFolder, _VersionType, _Name, _Title, _MyItem, _MyFormat, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Folder myFolder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DocVersion.Update(cn, ref _VersionID, myFolder.FolderID, _VersionType, _Name, _Title, _ItemID, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DocVersion.Update(cn, ref _VersionID, myFolder.FolderID, _VersionType, _Name, _Title, _ItemID, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Folder myFolder) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - DocVersion.Remove(cn, _VersionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + DocVersion.Remove(cn, _VersionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - FolderDocVersionExtension _FolderDocVersionExtension = new FolderDocVersionExtension(); + readonly FolderDocVersionExtension _FolderDocVersionExtension = new FolderDocVersionExtension(); [Serializable()] partial class FolderDocVersionExtension : extensionBase { @@ -510,18 +429,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultVersionType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultVersionType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -550,61 +460,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FolderDocVersion) + if (destType == typeof(string) && value is FolderDocVersion version) { // Return the ToString value - return ((FolderDocVersion)value).ToString(); + return version.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FolderDocVersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class FolderDocVersion -// { -// partial class FolderDocVersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultVersionType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersions.cs index 4a2c4d4d..d09c1fc2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FolderDocVersions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public FolderDocVersion this[DocVersion myDocVersion] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public FolderDocVersion this[DocVersion myDocVersion] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public FolderDocVersion GetItem(DocVersion myDocVersion) + public new System.Collections.Generic.IList Items => base.Items; + public FolderDocVersion GetItem(DocVersion myDocVersion) { foreach (FolderDocVersion docVersion in this) if (docVersion.VersionID == myDocVersion.VersionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public FolderDocVersion Add(string name) // One to Many { FolderDocVersion docVersion = FolderDocVersion.New(name); - this.Add(docVersion); + Add(docVersion); return docVersion; } public void Remove(DocVersion myDocVersion) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (FolderDocVersion child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (FolderDocVersion child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static FolderDocVersions New() - { - return new FolderDocVersions(); - } - internal static FolderDocVersions Get(SafeDataReader dr) - { - return new FolderDocVersions(dr); - } - public static FolderDocVersions GetByFolderID(int folderID) + #endregion + #region Factory Methods + internal static FolderDocVersions New() => new FolderDocVersions(); + internal static FolderDocVersions Get(SafeDataReader dr) => new FolderDocVersions(dr); + public static FolderDocVersions GetByFolderID(int folderID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FolderDocVersions.GetByFolderID", ex); } } - private FolderDocVersions() - { - MarkAsChild(); - } - internal FolderDocVersions(SafeDataReader dr) + private FolderDocVersions() => MarkAsChild(); + internal FolderDocVersions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FolderDocVersions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FolderDocVersions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(FolderDocVersion.Get(dr)); - this.RaiseListChangedEvents = true; + Add(FolderDocVersion.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class FolderIDCriteria { - public FolderIDCriteria(int folderID) - { - _FolderID = folderID; - } - private int _FolderID; + public FolderIDCriteria(int folderID) => _FolderID = folderID; + private int _FolderID; public int FolderID { get { return _FolderID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FolderIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FolderDocVersions.DataPortal_FetchFolderID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new FolderDocVersion(dr)); + while (dr.Read()) Add(new FolderDocVersion(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("FolderDocVersions.DataPortal_FetchFolderID", ex); throw new DbCslaException("FolderDocVersions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Folder folder) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection FolderDocVersionsPropertyDescriptor pd = new FolderDocVersionsPropertyDescriptor(this, i); @@ -334,10 +296,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FolderDocVersions) + if (destType == typeof(string) && value is FolderDocVersions versions) { // Return department and department role separated by comma. - return ((FolderDocVersions)value).Items.Count.ToString() + " DocVersions"; + return $"{versions.Items.Count} DocVersions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfo.cs index e7de686d..6d28d174 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class FolderInfo : ReadOnlyBase, IDisposable { public event FolderInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(FolderInfo folderInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(folderInfo)) _CacheList.Remove(folderInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Folder _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _FolderID; [System.ComponentModel.DataObjectField(true, true)] public int FolderID @@ -330,32 +314,19 @@ namespace VEPROMS.CSLA.Library foreach (FolderInfo tmp in _CacheByPrimaryKey[_FolderID.ToString()]) tmp._ChildFolderCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base FolderInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current FolderInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check FolderInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FolderInfo - protected override object GetIdValue() - { - return MyFolderInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFolderInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _FolderInfoUnique = 0; - private static int FolderInfoUnique - { get { return ++_FolderInfoUnique; } } - private int _MyFolderInfoUnique = FolderInfoUnique; - public int MyFolderInfoUnique // Absolutely Unique ID - Info - { get { return _MyFolderInfoUnique; } } + private static int FolderInfoUnique => ++_FolderInfoUnique; + private readonly int _MyFolderInfoUnique = FolderInfoUnique; + // Absolutely Unique ID - Info + public int MyFolderInfoUnique => _MyFolderInfoUnique; protected FolderInfo() {/* require use of factory methods */ AddToCache(this); @@ -364,15 +335,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FolderInfo() { _CountFinalized++; @@ -389,10 +356,7 @@ namespace VEPROMS.CSLA.Library if (listFolderInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(FolderID.ToString()); // remove the list } - public virtual Folder Get() - { - return _Editable = Folder.Get(_FolderID); - } + public virtual Folder Get() => _Editable = Folder.Get(_FolderID); public static void Refresh(Folder tmp) { string key = tmp.FolderID.ToString(); @@ -405,28 +369,28 @@ namespace VEPROMS.CSLA.Library { if (_ParentID != tmp.ParentID) { - if (MyParent != null) MyParent.RefreshChildFolders(); // Update List for old value + MyParent?.RefreshChildFolders(); // Update List for old value _ParentID = tmp.ParentID; // Update the value } _MyParent = null; // Reset list so that the next line gets a new list - if (MyParent != null) MyParent.RefreshChildFolders(); // Update List for new value + MyParent?.RefreshChildFolders(); // Update List for new value if (_DBID != tmp.DBID) { - if (MyConnection != null) MyConnection.RefreshConnectionFolders(); // Update List for old value + MyConnection?.RefreshConnectionFolders(); // Update List for old value _DBID = tmp.DBID; // Update the value } _MyConnection = null; // Reset list so that the next line gets a new list - if (MyConnection != null) MyConnection.RefreshConnectionFolders(); // Update List for new value + MyConnection?.RefreshConnectionFolders(); // Update List for new value _Name = tmp.Name; _Title = tmp.Title; _ShortName = tmp.ShortName; if (_FormatID != tmp.FormatID) { - if (MyFormat != null) MyFormat.RefreshFormatFolders(); // Update List for old value + MyFormat?.RefreshFormatFolders(); // Update List for old value _FormatID = tmp.FormatID; // Update the value } _MyFormat = null; // Reset list so that the next line gets a new list - if (MyFormat != null) MyFormat.RefreshFormatFolders(); // Update List for new value + MyFormat?.RefreshFormatFolders(); // Update List for new value _ManualOrder = tmp.ManualOrder; _Config = tmp.Config; _DTS = tmp.DTS; @@ -446,21 +410,21 @@ namespace VEPROMS.CSLA.Library { if (_ParentID != tmp.ParentID) { - if (MyParent != null) MyParent.RefreshChildFolders(); // Update List for old value + MyParent?.RefreshChildFolders(); // Update List for old value _ParentID = tmp.ParentID; // Update the value } _MyParent = null; // Reset list so that the next line gets a new list - if (MyParent != null) MyParent.RefreshChildFolders(); // Update List for new value + MyParent?.RefreshChildFolders(); // Update List for new value _Name = tmp.Name; _Title = tmp.Title; _ShortName = tmp.ShortName; if (_FormatID != tmp.FormatID) { - if (MyFormat != null) MyFormat.RefreshFormatFolders(); // Update List for old value + MyFormat?.RefreshFormatFolders(); // Update List for old value _FormatID = tmp.FormatID; // Update the value } _MyFormat = null; // Reset list so that the next line gets a new list - if (MyFormat != null) MyFormat.RefreshFormatFolders(); // Update List for new value + MyFormat?.RefreshFormatFolders(); // Update List for new value _ManualOrder = tmp.ManualOrder; _Config = tmp.Config; _DTS = tmp.DTS; @@ -480,18 +444,18 @@ namespace VEPROMS.CSLA.Library { if (_ParentID != tmp.ParentID) { - if (MyParent != null) MyParent.RefreshChildFolders(); // Update List for old value + MyParent?.RefreshChildFolders(); // Update List for old value _ParentID = tmp.ParentID; // Update the value } _MyParent = null; // Reset list so that the next line gets a new list - if (MyParent != null) MyParent.RefreshChildFolders(); // Update List for new value + MyParent?.RefreshChildFolders(); // Update List for new value if (_DBID != tmp.DBID) { - if (MyConnection != null) MyConnection.RefreshConnectionFolders(); // Update List for old value + MyConnection?.RefreshConnectionFolders(); // Update List for old value _DBID = tmp.DBID; // Update the value } _MyConnection = null; // Reset list so that the next line gets a new list - if (MyConnection != null) MyConnection.RefreshConnectionFolders(); // Update List for new value + MyConnection?.RefreshConnectionFolders(); // Update List for new value _Name = tmp.Name; _Title = tmp.Title; _ShortName = tmp.ShortName; @@ -513,8 +477,6 @@ namespace VEPROMS.CSLA.Library public static FolderInfo Get(int folderID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Folder"); try { FolderInfo tmp = GetCachedByPrimaryKey(folderID); @@ -553,13 +515,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _FolderID; - public int FolderID - { get { return _FolderID; } } - public PKCriteria(int folderID) - { - _FolderID = folderID; - } + private readonly int _FolderID; + public int FolderID => _FolderID; + public PKCriteria(int folderID) => _FolderID = folderID; } private void ReadData(SafeDataReader dr) { @@ -627,7 +585,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - FolderInfoExtension _FolderInfoExtension = new FolderInfoExtension(); + readonly FolderInfoExtension _FolderInfoExtension = new FolderInfoExtension(); [Serializable()] partial class FolderInfoExtension : extensionBase { } [Serializable()] @@ -643,10 +601,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FolderInfo) + if (destType == typeof(string) && value is FolderInfo info) { // Return the ToString value - return ((FolderInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfoList.cs index 7e2f6fff..e173f8b1 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FolderInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (FolderInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FolderInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FolderInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FolderInfoList.Get", ex); } } - /// - /// Reset the list of all FolderInfo. - /// - public static void Reset() - { - _FolderInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static FolderInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on FolderInfoList.Get", ex); - // } - //} - public static FolderInfoList GetChildren(int parentID) + /// + /// Reset the list of all FolderInfo. + /// + public static void Reset() => _FolderInfoList = null; + public static FolderInfoList GetChildren(int parentID) { try { @@ -194,11 +172,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ParentIDCriteria { - public ParentIDCriteria(int parentID) - { - _ParentID = parentID; - } - private int _ParentID; + public ParentIDCriteria(int parentID) => _ParentID = parentID; + private int _ParentID; public int ParentID { get { return _ParentID; } @@ -238,11 +213,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class DBIDCriteria { - public DBIDCriteria(int dbid) - { - _DBID = dbid; - } - private int _DBID; + public DBIDCriteria(int dbid) => _DBID = dbid; + private int _DBID; public int DBID { get { return _DBID; } @@ -282,11 +254,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class FormatIDCriteria { - public FormatIDCriteria(int? formatID) - { - _FormatID = formatID; - } - private int? _FormatID; + public FormatIDCriteria(int? formatID) => _FormatID = formatID; + private int? _FormatID; public int? FormatID { get { return _FormatID; } @@ -323,41 +292,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -379,7 +337,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FolderInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private FolderInfo Item { get { return (FolderInfo)_Item; } } public FolderInfoListPropertyDescriptor(FolderInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -388,10 +345,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FolderInfoList) + if (destType == typeof(string) && value is FolderInfoList list) { // Return department and department role separated by comma. - return ((FolderInfoList)value).Items.Count.ToString() + " Folders"; + return $"{list.Items.Count} Folders"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Format.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Format.cs index c06509bf..e7824e95 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Format.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Format.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -102,6 +100,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Format format) { @@ -111,7 +110,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(format)) _CacheList.Remove(format); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByParentID_Name = new Dictionary>(); private static void ConvertListToDictionary() { @@ -154,15 +155,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextFormatID = -1; - public static int NextFormatID - { - get { return _nextFormatID--; } - } + public static int NextFormatID => _nextFormatID--; private int _FormatID; [System.ComponentModel.DataObjectField(true, true)] public int FormatID @@ -367,10 +362,7 @@ namespace VEPROMS.CSLA.Library return _FormatContents; } } - public void Reset_FormatContents() - { - _FormatContentCount = -1; - } + public void Reset_FormatContents() => _FormatContentCount = -1; private int _FormatDocVersionCount = 0; /// /// Count of FormatDocVersions for this Format @@ -402,10 +394,7 @@ namespace VEPROMS.CSLA.Library return _FormatDocVersions; } } - public void Reset_FormatDocVersions() - { - _FormatDocVersionCount = -1; - } + public void Reset_FormatDocVersions() => _FormatDocVersionCount = -1; private int _FormatFolderCount = 0; /// /// Count of FormatFolders for this Format @@ -472,10 +461,7 @@ namespace VEPROMS.CSLA.Library return _ChildFormats; } } - public void Reset_ChildFormats() - { - _ChildFormatCount = -1; - } + public void Reset_ChildFormats() => _ChildFormatCount = -1; public override bool IsDirty { get @@ -490,37 +476,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_FormatContents == null ? false : _FormatContents.IsDirtyList(list)) || (_FormatDocVersions == null ? false : _FormatDocVersions.IsDirtyList(list)) || (_FormatFolders == null ? false : _FormatFolders.IsDirtyList(list)) || (_ChildFormats == null ? false : _ChildFormats.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_FormatContents != null && _FormatContents.IsDirtyList(list)) || (_FormatDocVersions != null && _FormatDocVersions.IsDirtyList(list)) || (_FormatFolders != null && _FormatFolders.IsDirtyList(list)) || (_ChildFormats != null && _ChildFormats.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_FormatContents == null ? true : _FormatContents.IsValidList(list)) && (_FormatDocVersions == null ? true : _FormatDocVersions.IsValidList(list)) && (_FormatFolders == null ? true : _FormatFolders.IsValidList(list)) && (_ChildFormats == null ? true : _ChildFormats.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_FormatContents == null || _FormatContents.IsValidList(list)) && (_FormatDocVersions == null || _FormatDocVersions.IsValidList(list)) && (_FormatFolders == null || _FormatFolders.IsValidList(list)) && (_ChildFormats == null || _ChildFormats.IsValidList(list)); } - // CSLATODO: Replace base Format.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Format - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Format.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Format - protected override object GetIdValue() - { - return MyFormatUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFormatUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -552,8 +523,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -566,8 +537,6 @@ namespace VEPROMS.CSLA.Library ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("Description", 250)); - //ValidationRules.AddRule( - // Csla.Validation.CommonRules.StringRequired, "Data"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("Data", 1073741823)); @@ -591,37 +560,11 @@ namespace VEPROMS.CSLA.Library _FormatExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowRead(ParentID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Description, ""); - //AuthorizationRules.AllowRead(Data, ""); - //AuthorizationRules.AllowRead(GenMac, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ParentID, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Description, ""); - //AuthorizationRules.AllowWrite(Data, ""); - //AuthorizationRules.AllowWrite(GenMac, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _FormatExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -629,58 +572,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _FormatExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _FormatContentCount; - usedByCount += _FormatDocVersionCount; - usedByCount += _FormatFolderCount; - usedByCount += _ChildFormatCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FormatUnique = 0; - protected static int FormatUnique - { get { return ++_FormatUnique; } } - private int _MyFormatUnique = FormatUnique; - public int MyFormatUnique // Absolutely Unique ID - Editable - { get { return _MyFormatUnique; } } + protected static int FormatUnique => ++_FormatUnique; + private readonly int _MyFormatUnique = FormatUnique; + // Absolutely Unique ID - Editable + public int MyFormatUnique => _MyFormatUnique; protected Format() {/* require use of factory methods */ AddToCache(this); @@ -689,15 +588,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Format() { _CountFinalized++; @@ -734,8 +629,6 @@ namespace VEPROMS.CSLA.Library } public static Format New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Format"); try { return DataPortal.Create(); @@ -811,8 +704,6 @@ namespace VEPROMS.CSLA.Library } public static Format Get(int formatID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Format"); try { Format tmp = GetCachedByPrimaryKey(formatID); @@ -835,8 +726,6 @@ namespace VEPROMS.CSLA.Library } public static Format GetByParentID_Name(int parentID, string name) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Format"); try { Format tmp = GetCachedByParentID_Name(parentID, name); @@ -862,15 +751,14 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Format(dr, parent); return null; } - internal Format(SafeDataReader dr) - { - ReadData(dr); - } + internal Format(SafeDataReader dr) => ReadData(dr); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] private Format(SafeDataReader dr, Format parent) { ReadData(dr); MarkAsChild(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal Format(SafeDataReader dr, int parentID) { ReadData(dr); @@ -878,8 +766,6 @@ namespace VEPROMS.CSLA.Library } public static void Delete(int formatID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Format"); try { DataPortal.Delete(new PKCriteria(formatID)); @@ -891,12 +777,6 @@ namespace VEPROMS.CSLA.Library } public override Format Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Format"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Format"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Format"); try { BuildRefreshList(); @@ -916,23 +796,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _FormatID; - public int FormatID - { get { return _FormatID; } } - public PKCriteria(int formatID) - { - _FormatID = formatID; - } + private readonly int _FormatID; + public int FormatID => _FormatID; + public PKCriteria(int formatID) => _FormatID = formatID; } [Serializable()] private class ParentID_NameCriteria { - private int _ParentID; - public int ParentID - { get { return _ParentID; } } - private string _Name; - public string Name - { get { return _Name; } } + private readonly int _ParentID; + public int ParentID => _ParentID; + private readonly string _Name; + public string Name => _Name; public ParentID_NameCriteria(int parentID, string name) { _ParentID = parentID; @@ -1076,7 +950,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Format.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -1101,46 +975,54 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addFormat"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ParentID", ParentID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Description", _Description); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - cm.Parameters.AddWithValue("@GenMac", _GenMac); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_FormatID = new SqlParameter("@newFormatID", SqlDbType.Int); - param_FormatID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_FormatID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _FormatID = (int)cm.Parameters["@newFormatID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addFormat"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ParentID", ParentID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Description", _Description); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + cm.Parameters.AddWithValue("@GenMac", _GenMac); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_FormatID = new SqlParameter("@newFormatID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_FormatID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _FormatID = (int)cm.Parameters["@newFormatID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_FormatFolders != null) _FormatFolders.Update(this); - if (_FormatContents != null) _FormatContents.Update(this); - if (_FormatDocVersions != null) _FormatDocVersions.Update(this); - if (_ChildFormats != null) _ChildFormats.Update(this); + _FormatFolders?.Update(this); + _FormatContents?.Update(this); + _FormatDocVersions?.Update(this); + _ChildFormats?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -1150,7 +1032,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Format.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int formatID, Format myParent, string name, string description, string data, string config, string genMac, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.Add", 0); @@ -1171,11 +1053,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_FormatID = new SqlParameter("@newFormatID", SqlDbType.Int); - param_FormatID.Direction = ParameterDirection.Output; + SqlParameter param_FormatID = new SqlParameter("@newFormatID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_FormatID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1190,7 +1076,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Format.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1213,48 +1099,54 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateFormat"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@FormatID", _FormatID); - cm.Parameters.AddWithValue("@ParentID", ParentID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Description", _Description); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - cm.Parameters.AddWithValue("@GenMac", _GenMac); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateFormat"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@FormatID", _FormatID); + cm.Parameters.AddWithValue("@ParentID", ParentID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Description", _Description); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + cm.Parameters.AddWithValue("@GenMac", _GenMac); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_FormatFolders != null) _FormatFolders.Update(this); - if (_FormatContents != null) _FormatContents.Update(this); - if (_FormatDocVersions != null) _FormatDocVersions.Update(this); - if (_ChildFormats != null) _ChildFormats.Update(this); + _FormatFolders?.Update(this); + _FormatContents?.Update(this); + _FormatDocVersions?.Update(this); + _ChildFormats?.Update(this); } catch (Exception ex) { @@ -1265,32 +1157,41 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Format.Add(cn, ref _FormatID, _MyParent, _Name, _Description, _Data, _Config, _GenMac, _DTS, _UserID); - else - _LastChanged = Format.Update(cn, ref _FormatID, _ParentID, _Name, _Description, _Data, _Config, _GenMac, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Format.Add(cn, ref _FormatID, _MyParent, _Name, _Description, _Data, _Config, _GenMac, _DTS, _UserID); + else + _LastChanged = Format.Update(cn, ref _FormatID, _ParentID, _Name, _Description, _Data, _Config, _GenMac, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_FormatFolders != null) _FormatFolders.Update(this); - if (_FormatContents != null) _FormatContents.Update(this); - if (_FormatDocVersions != null) _FormatDocVersions.Update(this); - if (_ChildFormats != null) _ChildFormats.Update(this); + _FormatFolders?.Update(this); + _FormatContents?.Update(this); + _FormatDocVersions?.Update(this); + _ChildFormats?.Update(this); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Format format) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Format.Remove(cn, _FormatID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Format.Remove(cn, _FormatID); + } + MarkNew(); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int formatID, int parentID, string name, string description, string data, string config, string genMac, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.Update", 0); @@ -1313,8 +1214,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1328,12 +1231,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Format.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_FormatID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.DataPortal_Delete", GetHashCode()); @@ -1358,7 +1261,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Format.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int formatID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.Remove", 0); @@ -1399,16 +1302,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _FormatID; + private readonly int _FormatID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int formatID) - { - _FormatID = formatID; - } + public bool Exists => _exists; + public ExistsCommand(int formatID) => _FormatID = formatID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.DataPortal_Execute", GetHashCode()); @@ -1416,7 +1313,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1438,7 +1335,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - FormatExtension _FormatExtension = new FormatExtension(); + readonly FormatExtension _FormatExtension = new FormatExtension(); [Serializable()] partial class FormatExtension : extensionBase { @@ -1447,18 +1344,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultParentID - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultParentID => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1487,61 +1375,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Format) + if (destType == typeof(string) && value is Format format) { // Return the ToString value - return ((Format)value).ToString(); + return format.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FormatExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Format -// { -// partial class FormatExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultParentID -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatContent.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatContent.cs index d70e2dde..bea21903 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatContent.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatContent.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -182,10 +176,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FormatContent - protected override object GetIdValue() - { - return MyFormatContentUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFormatContentUnique; // Absolutely Unique ID // CSLATODO: Replace base FormatContent.ToString function as necessary /// /// Overrides Base ToString @@ -195,22 +186,12 @@ namespace VEPROMS.CSLA.Library //{ // return base.ToString(); //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -239,7 +220,7 @@ namespace VEPROMS.CSLA.Library { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -260,80 +241,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(Number, ""); - //AuthorizationRules.AllowWrite(Number, ""); - //AuthorizationRules.AllowRead(Text, ""); - //AuthorizationRules.AllowWrite(Text, ""); - //AuthorizationRules.AllowRead(Type, ""); - //AuthorizationRules.AllowWrite(Type, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FormatContentUnique = 0; - private static int FormatContentUnique - { get { return ++_FormatContentUnique; } } - private int _MyFormatContentUnique = FormatContentUnique; - public int MyFormatContentUnique // Absolutely Unique ID - Editable FK - { get { return _MyFormatContentUnique; } } - internal static FormatContent New() - { - return new FormatContent(); - } - internal static FormatContent Get(SafeDataReader dr) - { - return new FormatContent(dr); - } + private static int FormatContentUnique => ++_FormatContentUnique; + private readonly int _MyFormatContentUnique = FormatContentUnique; + // Absolutely Unique ID - Editable FK + public int MyFormatContentUnique => _MyFormatContentUnique; + internal static FormatContent New() => new FormatContent(); + internal static FormatContent Get(SafeDataReader dr) => new FormatContent(dr); public FormatContent() { MarkAsChild(); @@ -351,15 +274,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FormatContent() { _CountFinalized++; @@ -397,32 +316,45 @@ namespace VEPROMS.CSLA.Library { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Content.Add(cn, ref _ContentID, _Number, _Text, _Type, myFormat, _Config, _DTS, _UserID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Content.Add(cn, ref _ContentID, _Number, _Text, _Type, myFormat, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Format myFormat) { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Content.Update(cn, ref _ContentID, _Number, _Text, _Type, myFormat != null ? (int?)myFormat.FormatID : (int?)null, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Content.Update(cn, ref _ContentID, _Number, _Text, _Type, myFormat != null ? (int?)myFormat.FormatID : (int?)null, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Format myFormat) { // if we're not dirty then don't update the database if (!this.IsDirty) return; // if we're new then don't update the database if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Content.Remove(cn, _ContentID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Content.Remove(cn, _ContentID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - FormatContentExtension _FormatContentExtension = new FormatContentExtension(); + readonly FormatContentExtension _FormatContentExtension = new FormatContentExtension(); [Serializable()] partial class FormatContentExtension : extensionBase { @@ -431,14 +363,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -467,57 +393,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatContent) + if (destType == typeof(string) && value is FormatContent content) { // Return the ToString value - return ((FormatContent)value).ToString(); + return content.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FormatContentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class FormatContent -// { -// partial class FormatContentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatContents.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatContents.cs index d8bad0ba..6adf1078 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatContents.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatContents.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public FormatContent this[Content myContent] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public FormatContent this[Content myContent] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public FormatContent GetItem(Content myContent) + public new System.Collections.Generic.IList Items => base.Items; + public FormatContent GetItem(Content myContent) { foreach (FormatContent content in this) if (content.ContentID == myContent.ContentID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public FormatContent Add() // One to Many { FormatContent content = FormatContent.New(); - this.Add(content); + Add(content); return content; } public void Remove(Content myContent) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (FormatContent child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (FormatContent child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static FormatContents New() - { - return new FormatContents(); - } - internal static FormatContents Get(SafeDataReader dr) - { - return new FormatContents(dr); - } - public static FormatContents GetByFormatID(int formatID) + #endregion + #region Factory Methods + internal static FormatContents New() => new FormatContents(); + internal static FormatContents Get(SafeDataReader dr) => new FormatContents(dr); + public static FormatContents GetByFormatID(int formatID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FormatContents.GetByFormatID", ex); } } - private FormatContents() - { - MarkAsChild(); - } - internal FormatContents(SafeDataReader dr) + private FormatContents() => MarkAsChild(); + internal FormatContents(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FormatContents() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FormatContents() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(FormatContent.Get(dr)); - this.RaiseListChangedEvents = true; + Add(FormatContent.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class FormatIDCriteria { - public FormatIDCriteria(int formatID) - { - _FormatID = formatID; - } - private int _FormatID; + public FormatIDCriteria(int formatID) => _FormatID = formatID; + private int _FormatID; public int FormatID { get { return _FormatID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FormatIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatContents.DataPortal_FetchFormatID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new FormatContent(dr)); + while (dr.Read()) Add(new FormatContent(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("FormatContents.DataPortal_FetchFormatID", ex); throw new DbCslaException("FormatContents.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Format format) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection FormatContentsPropertyDescriptor pd = new FormatContentsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FormatContentsPropertyDescriptor : vlnListPropertyDescriptor { - private FormatContent Item { get { return (FormatContent)_Item; } } public FormatContentsPropertyDescriptor(FormatContents collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatContents) + if (destType == typeof(string) && value is FormatContents contents) { // Return department and department role separated by comma. - return ((FormatContents)value).Items.Count.ToString() + " Contents"; + return $"{contents.Items.Count} Contents"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersion.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersion.cs index 76da2512..3a6c8cad 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersion.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersion.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -329,10 +323,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FormatDocVersion - protected override object GetIdValue() - { - return MyFormatDocVersionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFormatDocVersionUnique; // Absolutely Unique ID // CSLATODO: Replace base FormatDocVersion.ToString function as necessary /// /// Overrides Base ToString @@ -356,18 +347,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyFolder != null && _MyFolder.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyFolder == null || _MyFolder.IsValidList(list)); } #endregion #region ValidationRules @@ -398,8 +386,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -432,84 +420,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowWrite(FolderID, ""); - //AuthorizationRules.AllowRead(VersionType, ""); - //AuthorizationRules.AllowWrite(VersionType, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FormatDocVersionUnique = 0; - private static int FormatDocVersionUnique - { get { return ++_FormatDocVersionUnique; } } - private int _MyFormatDocVersionUnique = FormatDocVersionUnique; - public int MyFormatDocVersionUnique // Absolutely Unique ID - Editable FK - { get { return _MyFormatDocVersionUnique; } } - internal static FormatDocVersion New(Folder myFolder, string name) - { - return new FormatDocVersion(myFolder, name); - } - internal static FormatDocVersion Get(SafeDataReader dr) - { - return new FormatDocVersion(dr); - } + private static int FormatDocVersionUnique => ++_FormatDocVersionUnique; + private readonly int _MyFormatDocVersionUnique = FormatDocVersionUnique; + // Absolutely Unique ID - Editable FK + public int MyFormatDocVersionUnique => _MyFormatDocVersionUnique; + internal static FormatDocVersion New(Folder myFolder, string name) => new FormatDocVersion(myFolder, name); + internal static FormatDocVersion Get(SafeDataReader dr) => new FormatDocVersion(dr); public FormatDocVersion() { MarkAsChild(); @@ -540,15 +466,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FormatDocVersion() { _CountFinalized++; @@ -597,33 +519,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Format myFormat) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, _MyItem, myFormat, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, _MyItem, myFormat, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Format myFormat) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, _ItemID, myFormat != null ? (int?)myFormat.FormatID : (int?)null, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, _ItemID, myFormat != null ? (int?)myFormat.FormatID : (int?)null, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Format myFormat) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - DocVersion.Remove(cn, _VersionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + DocVersion.Remove(cn, _VersionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - FormatDocVersionExtension _FormatDocVersionExtension = new FormatDocVersionExtension(); + readonly FormatDocVersionExtension _FormatDocVersionExtension = new FormatDocVersionExtension(); [Serializable()] partial class FormatDocVersionExtension : extensionBase { @@ -632,18 +567,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultVersionType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultVersionType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -672,61 +598,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatDocVersion) + if (destType == typeof(string) && value is FormatDocVersion version) { // Return the ToString value - return ((FormatDocVersion)value).ToString(); + return version.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FormatDocVersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class FormatDocVersion -// { -// partial class FormatDocVersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultVersionType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersions.cs index b80005c5..80a4ec94 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatDocVersions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public FormatDocVersion this[DocVersion myDocVersion] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public FormatDocVersion this[DocVersion myDocVersion] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public FormatDocVersion GetItem(DocVersion myDocVersion) + public new System.Collections.Generic.IList Items => base.Items; + public FormatDocVersion GetItem(DocVersion myDocVersion) { foreach (FormatDocVersion docVersion in this) if (docVersion.VersionID == myDocVersion.VersionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public FormatDocVersion Add(Folder myFolder, string name) // One to Many { FormatDocVersion docVersion = FormatDocVersion.New(myFolder, name); - this.Add(docVersion); + Add(docVersion); return docVersion; } public void Remove(DocVersion myDocVersion) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (FormatDocVersion child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (FormatDocVersion child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static FormatDocVersions New() - { - return new FormatDocVersions(); - } - internal static FormatDocVersions Get(SafeDataReader dr) - { - return new FormatDocVersions(dr); - } - public static FormatDocVersions GetByFormatID(int formatID) + #endregion + #region Factory Methods + internal static FormatDocVersions New() => new FormatDocVersions(); + internal static FormatDocVersions Get(SafeDataReader dr) => new FormatDocVersions(dr); + public static FormatDocVersions GetByFormatID(int formatID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FormatDocVersions.GetByFormatID", ex); } } - private FormatDocVersions() - { - MarkAsChild(); - } - internal FormatDocVersions(SafeDataReader dr) + private FormatDocVersions() => MarkAsChild(); + internal FormatDocVersions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FormatDocVersions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FormatDocVersions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(FormatDocVersion.Get(dr)); - this.RaiseListChangedEvents = true; + Add(FormatDocVersion.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class FormatIDCriteria { - public FormatIDCriteria(int formatID) - { - _FormatID = formatID; - } - private int _FormatID; + public FormatIDCriteria(int formatID) => _FormatID = formatID; + private int _FormatID; public int FormatID { get { return _FormatID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FormatIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatDocVersions.DataPortal_FetchFormatID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new FormatDocVersion(dr)); + while (dr.Read()) Add(new FormatDocVersion(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("FormatDocVersions.DataPortal_FetchFormatID", ex); throw new DbCslaException("FormatDocVersions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Format format) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection FormatDocVersionsPropertyDescriptor pd = new FormatDocVersionsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FormatDocVersionsPropertyDescriptor : vlnListPropertyDescriptor { - private FormatDocVersion Item { get { return (FormatDocVersion)_Item; } } public FormatDocVersionsPropertyDescriptor(FormatDocVersions collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatDocVersions) + if (destType == typeof(string) && value is FormatDocVersions versions) { // Return department and department role separated by comma. - return ((FormatDocVersions)value).Items.Count.ToString() + " DocVersions"; + return $"{versions.Items.Count} DocVersions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolder.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolder.cs index c9dfe407..f8874c22 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolder.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolder.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _FolderID; [System.ComponentModel.DataObjectField(true, true)] public int FolderID @@ -321,19 +315,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FormatFolder - protected override object GetIdValue() - { - return MyFormatFolderUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base FormatFolder.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current FormatFolder - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyFormatFolderUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -348,18 +330,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)) || (_MyConnection == null ? false : _MyConnection.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyFolder != null && _MyFolder.IsDirtyList(list)) || (_MyConnection != null && _MyConnection.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)) && (_MyConnection == null ? true : _MyConnection.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyFolder == null || _MyFolder.IsValidList(list)) && (_MyConnection == null || _MyConnection.IsValidList(list)); } #endregion #region ValidationRules @@ -390,8 +369,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -439,86 +418,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { - //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowRead(ParentID, ""); - //AuthorizationRules.AllowWrite(ParentID, ""); - //AuthorizationRules.AllowRead(DBID, ""); - //AuthorizationRules.AllowWrite(DBID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowRead(ShortName, ""); - //AuthorizationRules.AllowWrite(ShortName, ""); - //AuthorizationRules.AllowRead(ManualOrder, ""); - //AuthorizationRules.AllowWrite(ManualOrder, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; + } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _FormatFolderUnique = 0; - private static int FormatFolderUnique - { get { return ++_FormatFolderUnique; } } - private int _MyFormatFolderUnique = FormatFolderUnique; - public int MyFormatFolderUnique // Absolutely Unique ID - Editable FK - { get { return _MyFormatFolderUnique; } } - internal static FormatFolder New(Folder myParent, string name, string shortName) - { - return new FormatFolder(myParent, name, shortName); - } - internal static FormatFolder Get(SafeDataReader dr) - { - return new FormatFolder(dr); - } + private static int FormatFolderUnique => ++_FormatFolderUnique; + private readonly int _MyFormatFolderUnique = FormatFolderUnique; + // Absolutely Unique ID - Editable FK + public int MyFormatFolderUnique => _MyFormatFolderUnique; + internal static FormatFolder New(Folder myParent, string name, string shortName) => new FormatFolder(myParent, name, shortName); + internal static FormatFolder Get(SafeDataReader dr) => new FormatFolder(dr); public FormatFolder() { MarkAsChild(); @@ -552,15 +467,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FormatFolder() { _CountFinalized++; @@ -607,33 +518,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Format myFormat) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Folder.Add(cn, ref _FolderID, Folder.Get(_ParentID), _MyConnection, _Name, _Title, _ShortName, myFormat, _ManualOrder, _Config, _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Folder.Add(cn, ref _FolderID, Folder.Get(_ParentID), _MyConnection, _Name, _Title, _ShortName, myFormat, _ManualOrder, _Config, _DTS, _UsrID); + } + MarkOld(); } internal void Update(Format myFormat) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, _DBID, _Name, _Title, _ShortName, myFormat != null ? (int?)myFormat.FormatID : (int?)null, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, _DBID, _Name, _Title, _ShortName, myFormat != null ? (int?)myFormat.FormatID : (int?)null, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Format myFormat) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Folder.Remove(cn, _FolderID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Folder.Remove(cn, _FolderID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - FormatFolderExtension _FormatFolderExtension = new FormatFolderExtension(); + readonly FormatFolderExtension _FormatFolderExtension = new FormatFolderExtension(); [Serializable()] partial class FormatFolderExtension : extensionBase { @@ -642,22 +566,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultParentID - { - get { return 1; } - } - public virtual int DefaultDBID - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultParentID => 1; + public virtual int DefaultDBID => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -686,65 +598,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatFolder) + if (destType == typeof(string) && value is FormatFolder folder) { // Return the ToString value - return ((FormatFolder)value).ToString(); + return folder.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create FormatFolderExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class FormatFolder -// { -// partial class FormatFolderExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultParentID -// { -// get { return 1; } -// } -// public virtual int DefaultDBID -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolders.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolders.cs index d1d94102..bcd3fa11 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolders.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatFolders.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public FormatFolder this[Folder myFolder] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public FormatFolder this[Folder myFolder] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public FormatFolder GetItem(Folder myFolder) + public new System.Collections.Generic.IList Items => base.Items; + public FormatFolder GetItem(Folder myFolder) { foreach (FormatFolder folder in this) if (folder.FolderID == myFolder.FolderID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public FormatFolder Add(Folder myParent, string name, string shortName) // One to Many { FormatFolder folder = FormatFolder.New(myParent, name, shortName); - this.Add(folder); + Add(folder); return folder; } public void Remove(Folder myFolder) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (FormatFolder child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (FormatFolder child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return (hasBrokenRules?.BrokenRules); } } - #endregion - #region Factory Methods - internal static FormatFolders New() - { - return new FormatFolders(); - } - internal static FormatFolders Get(SafeDataReader dr) - { - return new FormatFolders(dr); - } - public static FormatFolders GetByFormatID(int formatID) + #endregion + #region Factory Methods + internal static FormatFolders New() => new FormatFolders(); + internal static FormatFolders Get(SafeDataReader dr) => new FormatFolders(dr); + public static FormatFolders GetByFormatID(int formatID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on FormatFolders.GetByFormatID", ex); } } - private FormatFolders() - { - MarkAsChild(); - } - internal FormatFolders(SafeDataReader dr) + private FormatFolders() => MarkAsChild(); + internal FormatFolders(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~FormatFolders() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FormatFolders() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(FormatFolder.Get(dr)); - this.RaiseListChangedEvents = true; + Add(FormatFolder.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class FormatIDCriteria { - public FormatIDCriteria(int formatID) - { - _FormatID = formatID; - } - private int _FormatID; + public FormatIDCriteria(int formatID) => _FormatID = formatID; + private int _FormatID; public int FormatID { get { return _FormatID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FormatIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatFolders.DataPortal_FetchFormatID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new FormatFolder(dr)); + while (dr.Read()) Add(new FormatFolder(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("FormatFolders.DataPortal_FetchFormatID", ex); throw new DbCslaException("FormatFolders.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Format format) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,39 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection FormatFoldersPropertyDescriptor pd = new FormatFoldersPropertyDescriptor(this, i); @@ -325,7 +288,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FormatFoldersPropertyDescriptor : vlnListPropertyDescriptor { - private FormatFolder Item { get { return (FormatFolder)_Item; } } public FormatFoldersPropertyDescriptor(FormatFolders collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +296,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatFolders) + if (destType == typeof(string) && value is FormatFolders folders) { // Return department and department role separated by comma. - return ((FormatFolders)value).Items.Count.ToString() + " Folders"; + return $"{folders.Items.Count} Folders"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfo.cs index decc8dab..b9473022 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class FormatInfo : ReadOnlyBase, IDisposable { public event FormatInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(FormatInfo formatInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(formatInfo)) _CacheList.Remove(formatInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -81,21 +78,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Format _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _FormatID; [System.ComponentModel.DataObjectField(true, true)] public int FormatID @@ -342,32 +326,19 @@ namespace VEPROMS.CSLA.Library foreach (FormatInfo tmp in _CacheByPrimaryKey[_FormatID.ToString()]) tmp._ChildFormatCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base FormatInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current FormatInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check FormatInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current FormatInfo - protected override object GetIdValue() - { - return MyFormatInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyFormatInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _FormatInfoUnique = 0; - private static int FormatInfoUnique - { get { return ++_FormatInfoUnique; } } - private int _MyFormatInfoUnique = FormatInfoUnique; - public int MyFormatInfoUnique // Absolutely Unique ID - Info - { get { return _MyFormatInfoUnique; } } + private static int FormatInfoUnique => ++_FormatInfoUnique; + private readonly int _MyFormatInfoUnique = FormatInfoUnique; + // Absolutely Unique ID - Info + public int MyFormatInfoUnique => _MyFormatInfoUnique; protected FormatInfo() {/* require use of factory methods */ AddToCache(this); @@ -376,15 +347,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~FormatInfo() { _CountFinalized++; @@ -417,11 +384,11 @@ namespace VEPROMS.CSLA.Library { if (_ParentID != tmp.ParentID) { - if (MyParent != null) MyParent.RefreshChildFormats(); // Update List for old value + MyParent?.RefreshChildFormats(); // Update List for old value _ParentID = tmp.ParentID; // Update the value } _MyParent = null; // Reset list so that the next line gets a new list - if (MyParent != null) MyParent.RefreshChildFormats(); // Update List for new value + MyParent?.RefreshChildFormats(); // Update List for new value _Name = tmp.Name; _Description = tmp.Description; _Data = tmp.Data; @@ -434,8 +401,6 @@ namespace VEPROMS.CSLA.Library } public static FormatInfo Get(int formatID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Format"); try { FormatInfo tmp = GetCachedByPrimaryKey(formatID); @@ -474,13 +439,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _FormatID; - public int FormatID - { get { return _FormatID; } } - public PKCriteria(int formatID) - { - _FormatID = formatID; - } + private readonly int _FormatID; + public int FormatID => _FormatID; + public PKCriteria(int formatID) => _FormatID = formatID; } public static string _Failed = null; public static string Failed @@ -564,7 +525,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - FormatInfoExtension _FormatInfoExtension = new FormatInfoExtension(); + readonly FormatInfoExtension _FormatInfoExtension = new FormatInfoExtension(); [Serializable()] partial class FormatInfoExtension : extensionBase { } [Serializable()] @@ -580,10 +541,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatInfo) + if (destType == typeof(string) && value is FormatInfo info) { // Return the ToString value - return ((FormatInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfoList.cs index 459f7407..1956ae3d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/FormatInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (FormatInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~FormatInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~FormatInfoList() { _CountFinalized++; } @@ -105,18 +98,6 @@ namespace VEPROMS.CSLA.Library _FormatInfoList = null; _SortedFormatInfoList = null; } - // CSLATODO: Add alternative gets - - //public static FormatInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on FormatInfoList.Get", ex); - // } - //} public static FormatInfoList GetChildren(int parentID) { try @@ -137,7 +118,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -151,7 +132,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new FormatInfo(dr)); + while (dr.Read()) Add(new FormatInfo(dr)); IsReadOnly = true; } } @@ -170,16 +151,13 @@ namespace VEPROMS.CSLA.Library System.Windows.Forms.MessageBox.Show(sbMsg.ToString(), "Update Stored Procedures", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); throw new DbCslaException("FormatInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ParentIDCriteria { - public ParentIDCriteria(int parentID) - { - _ParentID = parentID; - } - private int _ParentID; + public ParentIDCriteria(int parentID) => _ParentID = parentID; + private int _ParentID; public int ParentID { get { return _ParentID; } @@ -188,7 +166,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ParentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfoList.DataPortal_FetchParentID", GetHashCode()); try { @@ -203,7 +181,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new FormatInfo(dr)); + while (dr.Read()) Add(new FormatInfo(dr)); IsReadOnly = true; } } @@ -214,48 +192,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("FormatInfoList.DataPortal_FetchParentID", ex); throw new DbCslaException("FormatInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection FormatInfoListPropertyDescriptor pd = new FormatInfoListPropertyDescriptor(this, i); @@ -272,7 +239,6 @@ namespace VEPROMS.CSLA.Library /// public partial class FormatInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private FormatInfo Item { get { return (FormatInfo)_Item; } } public FormatInfoListPropertyDescriptor(FormatInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -281,10 +247,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is FormatInfoList) + if (destType == typeof(string) && value is FormatInfoList list) { // Return department and department role separated by comma. - return ((FormatInfoList)value).Items.Count.ToString() + " Formats"; + return $"{list.Items.Count} Formats"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Grid.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Grid.cs index 551a2541..15c6bb45 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Grid.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Grid.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshGrids.Add(this); } - private void ClearRefreshList() - { - _RefreshGrids = new List(); - } + private void ClearRefreshList() => _RefreshGrids = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Grid grid) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(grid)) _CacheList.Remove(grid); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,10 +87,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -192,40 +186,18 @@ namespace VEPROMS.CSLA.Library } } private byte[] _LastChanged = new byte[8];//timestamp - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base Grid.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Grid - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check Grid.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Grid - protected override object GetIdValue() - { - return MyGridUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyGridUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -253,8 +225,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -281,31 +253,11 @@ namespace VEPROMS.CSLA.Library _GridExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(Data, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(Data, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _GridExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -313,42 +265,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _GridExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _GridUnique = 0; - protected static int GridUnique - { get { return ++_GridUnique; } } - private int _MyGridUnique = GridUnique; - public int MyGridUnique // Absolutely Unique ID - Editable - { get { return _MyGridUnique; } } + protected static int GridUnique => ++_GridUnique; + private readonly int _MyGridUnique = GridUnique; + // Absolutely Unique ID - Editable + public int MyGridUnique => _MyGridUnique; protected Grid() {/* require use of factory methods */ AddToCache(this); @@ -357,15 +281,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Grid() { _CountFinalized++; @@ -390,8 +310,6 @@ namespace VEPROMS.CSLA.Library } public static Grid New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Grid"); try { return DataPortal.Create(); @@ -468,8 +386,6 @@ namespace VEPROMS.CSLA.Library } public static Grid Get(int contentID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Grid"); try { Grid tmp = GetCachedByPrimaryKey(contentID); @@ -495,14 +411,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Grid(dr); return null; } - internal Grid(SafeDataReader dr) - { - ReadData(dr); - } + internal Grid(SafeDataReader dr) => ReadData(dr); public static void Delete(int contentID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Grid"); try { DataPortal.Delete(new PKCriteria(contentID)); @@ -514,12 +425,6 @@ namespace VEPROMS.CSLA.Library } public override Grid Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Grid"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Grid"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Grid"); try { BuildRefreshList(); @@ -539,13 +444,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -614,7 +515,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Grid.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -639,33 +540,39 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addGrid"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addGrid"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.SQLInsert", GetHashCode()); @@ -677,7 +584,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Grid.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Content myContent, string data, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.Add", 0); @@ -695,8 +602,10 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -710,7 +619,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Grid.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -733,38 +642,44 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateGrid"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateGrid"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -777,18 +692,22 @@ namespace VEPROMS.CSLA.Library } internal void Update(Content content) { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Grid.Add(cn, content, _Data, _Config, _DTS, _UserID); - else - _LastChanged = Grid.Update(cn, content.ContentID, _Data, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Grid.Add(cn, content, _Data, _Config, _DTS, _UserID); + else + _LastChanged = Grid.Update(cn, content.ContentID, _Data, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int contentID, string data, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.Update", 0); @@ -807,8 +726,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -822,12 +743,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Grid.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ContentID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.DataPortal_Delete", GetHashCode()); @@ -852,7 +773,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Grid.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int contentID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.Remove", 0); @@ -893,16 +814,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ContentID; + private readonly int _ContentID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int contentID) - { - _ContentID = contentID; - } + public bool Exists => _exists; + public ExistsCommand(int contentID) => _ContentID = contentID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Grid.DataPortal_Execute", GetHashCode()); @@ -910,7 +825,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -932,7 +847,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - GridExtension _GridExtension = new GridExtension(); + readonly GridExtension _GridExtension = new GridExtension(); [Serializable()] partial class GridExtension : extensionBase { @@ -941,14 +856,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -977,57 +886,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Grid) + if (destType == typeof(string) && value is Grid mygrid) { // Return the ToString value - return ((Grid)value).ToString(); + return mygrid.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create GridExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Grid -// { -// partial class GridExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GridAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GridAudit.cs index 9ee0d7a6..c89e34f5 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GridAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GridAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -56,6 +54,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(GridAudit gridAudit) { @@ -65,6 +64,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(gridAudit)) _CacheList.Remove(gridAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +90,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -238,40 +232,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base GridAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current GridAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check GridAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current GridAudit - protected override object GetIdValue() - { - return MyGridAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyGridAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -299,8 +267,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -327,37 +295,11 @@ namespace VEPROMS.CSLA.Library _GridAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(Data, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowRead(ContentAuditID, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(Data, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(ContentAuditID, ""); _GridAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -365,42 +307,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _GridAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _GridAuditUnique = 0; - protected static int GridAuditUnique - { get { return ++_GridAuditUnique; } } - private int _MyGridAuditUnique = GridAuditUnique; - public int MyGridAuditUnique // Absolutely Unique ID - Editable - { get { return _MyGridAuditUnique; } } + protected static int GridAuditUnique => ++_GridAuditUnique; + private readonly int _MyGridAuditUnique = GridAuditUnique; + // Absolutely Unique ID - Editable + public int MyGridAuditUnique => _MyGridAuditUnique; protected GridAudit() {/* require use of factory methods */ AddToCache(this); @@ -409,15 +323,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~GridAudit() { _CountFinalized++; @@ -442,8 +352,6 @@ namespace VEPROMS.CSLA.Library } public static GridAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a GridAudit"); try { return DataPortal.Create(); @@ -520,8 +428,6 @@ namespace VEPROMS.CSLA.Library } public static GridAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a GridAudit"); try { GridAudit tmp = GetCachedByPrimaryKey(auditID); @@ -547,14 +453,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new GridAudit(dr); return null; } - internal GridAudit(SafeDataReader dr) - { - ReadData(dr); - } + internal GridAudit(SafeDataReader dr) => ReadData(dr); public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a GridAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -566,12 +467,6 @@ namespace VEPROMS.CSLA.Library } public override GridAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a GridAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a GridAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a GridAudit"); try { BuildRefreshList(); @@ -591,13 +486,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -667,7 +558,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("GridAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -692,35 +583,41 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addGridAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - cm.Parameters.AddWithValue("@ContentAuditID", _ContentAuditID); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addGridAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + cm.Parameters.AddWithValue("@ContentAuditID", _ContentAuditID); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.SQLInsert", GetHashCode()); @@ -732,7 +629,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("GridAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int contentID, string data, string config, DateTime dts, string userID, int deleteStatus, long contentAuditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.Add", 0); @@ -752,8 +649,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); cm.Parameters.AddWithValue("@ContentAuditID", contentAuditID); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -768,7 +667,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("GridAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -791,36 +690,40 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateGridAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - cm.Parameters.AddWithValue("@ContentAuditID", _ContentAuditID); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateGridAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + cm.Parameters.AddWithValue("@ContentAuditID", _ContentAuditID); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -833,18 +736,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - GridAudit.Add(cn, ref _AuditID, _ContentID, _Data, _Config, _DTS, _UserID, _DeleteStatus, _ContentAuditID); - else - GridAudit.Update(cn, ref _AuditID, _ContentID, _Data, _Config, _DTS, _UserID, _DeleteStatus, _ContentAuditID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + GridAudit.Add(cn, ref _AuditID, _ContentID, _Data, _Config, _DTS, _UserID, _DeleteStatus, _ContentAuditID); + else + GridAudit.Update(cn, ref _AuditID, _ContentID, _Data, _Config, _DTS, _UserID, _DeleteStatus, _ContentAuditID); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int contentID, string data, string config, DateTime dts, string userID, int deleteStatus, long contentAuditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.Update", 0); @@ -877,12 +784,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("GridAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.DataPortal_Delete", GetHashCode()); @@ -907,7 +814,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("GridAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.Remove", 0); @@ -948,16 +855,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private long _AuditID; + private readonly long _AuditID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(long auditID) - { - _AuditID = auditID; - } + public bool Exists => _exists; + public ExistsCommand(long auditID) => _AuditID = auditID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAudit.DataPortal_Execute", GetHashCode()); @@ -965,7 +866,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -987,7 +888,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - GridAuditExtension _GridAuditExtension = new GridAuditExtension(); + readonly GridAuditExtension _GridAuditExtension = new GridAuditExtension(); [Serializable()] partial class GridAuditExtension : extensionBase { @@ -996,10 +897,7 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual long DefaultContentAuditID - { - get { return 0; } - } + public virtual long DefaultContentAuditID => 0; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1028,53 +926,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GridAudit) + if (destType == typeof(string) && value is GridAudit audit) { // Return the ToString value - return ((GridAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create GridAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class GridAudit -// { -// partial class GridAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual long DefaultContentAuditID -// { -// get { return 0; } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfo.cs index 3bb48ca0..582ce041 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class GridAuditInfo : ReadOnlyBase, IDisposable { public event GridAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(GridAuditInfo gridAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(gridAuditInfo)) _CacheList.Remove(gridAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected GridAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -162,32 +146,19 @@ namespace VEPROMS.CSLA.Library return _ContentAuditID; } } - // CSLATODO: Replace base GridAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current GridAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check GridAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current GridAuditInfo - protected override object GetIdValue() - { - return MyGridAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyGridAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _GridAuditInfoUnique = 0; - private static int GridAuditInfoUnique - { get { return ++_GridAuditInfoUnique; } } - private int _MyGridAuditInfoUnique = GridAuditInfoUnique; - public int MyGridAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyGridAuditInfoUnique; } } + private static int GridAuditInfoUnique => ++_GridAuditInfoUnique; + private readonly int _MyGridAuditInfoUnique = GridAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyGridAuditInfoUnique => _MyGridAuditInfoUnique; protected GridAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -196,15 +167,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~GridAuditInfo() { _CountFinalized++; @@ -221,10 +188,7 @@ namespace VEPROMS.CSLA.Library if (listGridAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual GridAudit Get() - { - return _Editable = GridAudit.Get(_AuditID); - } + public virtual GridAudit Get() => _Editable = GridAudit.Get(_AuditID); public static void Refresh(GridAudit tmp) { string key = tmp.AuditID.ToString(); @@ -247,8 +211,6 @@ namespace VEPROMS.CSLA.Library } public static GridAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a GridAudit"); try { GridAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -287,13 +249,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -355,7 +313,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - GridAuditInfoExtension _GridAuditInfoExtension = new GridAuditInfoExtension(); + readonly GridAuditInfoExtension _GridAuditInfoExtension = new GridAuditInfoExtension(); [Serializable()] partial class GridAuditInfoExtension : extensionBase { } [Serializable()] @@ -371,10 +329,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GridAuditInfo) + if (destType == typeof(string) && value is GridAuditInfo info) { // Return the ToString value - return ((GridAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfoList.cs index 3ace579d..b754682d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GridAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (GridAuditInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~GridAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~GridAuditInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on GridAuditInfoList.Get", ex); } } - /// - /// Reset the list of all GridAuditInfo. - /// - public static void Reset() - { - _GridAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static GridAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on GridAuditInfoList.Get", ex); - // } - //} - private GridAuditInfoList() + /// + /// Reset the list of all GridAuditInfo. + /// + public static void Reset() => _GridAuditInfoList = null; + private GridAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GridAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new GridAuditInfo(dr)); + while (dr.Read()) Add(new GridAuditInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,38 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("GridAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("GridAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection GridAuditInfoListPropertyDescriptor pd = new GridAuditInfoListPropertyDescriptor(this, i); @@ -205,7 +173,6 @@ namespace VEPROMS.CSLA.Library /// public partial class GridAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private GridAuditInfo Item { get { return (GridAuditInfo)_Item; } } public GridAuditInfoListPropertyDescriptor(GridAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +181,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GridAuditInfoList) + if (destType == typeof(string) && value is GridAuditInfoList list) { // Return department and department role separated by comma. - return ((GridAuditInfoList)value).Items.Count.ToString() + " GridAudits"; + return $"{list.Items.Count} GridAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GridInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GridInfo.cs index 7791c5c7..4ffe68b9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GridInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GridInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Linq; @@ -30,14 +28,12 @@ namespace VEPROMS.CSLA.Library public partial class GridInfo : ReadOnlyBase, IDisposable { public event GridInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(GridInfo gridInfo) { @@ -47,6 +43,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(gridInfo)) _CacheList.Remove(gridInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,21 +89,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Grid _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -165,32 +149,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base GridInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current GridInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check GridInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current GridInfo - protected override object GetIdValue() - { - return MyGridInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyGridInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _GridInfoUnique = 0; - private static int GridInfoUnique - { get { return ++_GridInfoUnique; } } - private int _MyGridInfoUnique = GridInfoUnique; - public int MyGridInfoUnique // Absolutely Unique ID - Info - { get { return _MyGridInfoUnique; } } + private static int GridInfoUnique => ++_GridInfoUnique; + private readonly int _MyGridInfoUnique = GridInfoUnique; + // Absolutely Unique ID - Info + public int MyGridInfoUnique => _MyGridInfoUnique; protected GridInfo() {/* require use of factory methods */ AddToCache(this); @@ -199,15 +170,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~GridInfo() { _CountFinalized++; @@ -224,10 +191,7 @@ namespace VEPROMS.CSLA.Library if (listGridInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list } - public virtual Grid Get() - { - return _Editable = Grid.Get(_ContentID); - } + public virtual Grid Get() => _Editable = Grid.Get(_ContentID); public static void Refresh(Grid tmp) { string key = tmp.ContentID.ToString(); @@ -247,8 +211,6 @@ namespace VEPROMS.CSLA.Library } public static GridInfo Get(int contentID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Grid"); try { GridInfo tmp = GetCachedByPrimaryKey(contentID); @@ -287,13 +249,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } private void ReadData(SafeDataReader dr) { @@ -352,7 +310,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - GridInfoExtension _GridInfoExtension = new GridInfoExtension(); + readonly GridInfoExtension _GridInfoExtension = new GridInfoExtension(); [Serializable()] partial class GridInfoExtension : extensionBase { } [Serializable()] @@ -368,10 +326,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GridInfo) + if (destType == typeof(string) && value is GridInfo info) { // Return the ToString value - return ((GridInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Group.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Group.cs index 123c62ae..35f5e252 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Group.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Group.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -82,6 +80,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Group group) { @@ -91,7 +90,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(group)) _CacheList.Remove(group); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByGroupName = new Dictionary>(); private static void ConvertListToDictionary() { @@ -126,15 +127,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextGID = -1; - public static int NextGID - { - get { return _nextGID--; } - } + public static int NextGID => _nextGID--; private int _GID; [System.ComponentModel.DataObjectField(true, true)] public int GID @@ -270,10 +265,7 @@ namespace VEPROMS.CSLA.Library return _GroupAssignments; } } - public void Reset_GroupAssignments() - { - _GroupAssignmentCount = -1; - } + public void Reset_GroupAssignments() => _GroupAssignmentCount = -1; private int _GroupMembershipCount = 0; /// /// Count of GroupMemberships for this Group @@ -305,10 +297,7 @@ namespace VEPROMS.CSLA.Library return _GroupMemberships; } } - public void Reset_GroupMemberships() - { - _GroupMembershipCount = -1; - } + public void Reset_GroupMemberships() => _GroupMembershipCount = -1; public override bool IsDirty { get @@ -323,37 +312,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_GroupAssignments == null ? false : _GroupAssignments.IsDirtyList(list)) || (_GroupMemberships == null ? false : _GroupMemberships.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_GroupAssignments != null && _GroupAssignments.IsDirtyList(list)) || (_GroupMemberships != null && _GroupMemberships.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_GroupAssignments == null ? true : _GroupAssignments.IsValidList(list)) && (_GroupMemberships == null ? true : _GroupMemberships.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_GroupAssignments == null || _GroupAssignments.IsValidList(list)) && (_GroupMemberships == null || _GroupMemberships.IsValidList(list)); } - // CSLATODO: Replace base Group.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Group - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Group.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Group - protected override object GetIdValue() - { - return MyGroupUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyGroupUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -383,8 +357,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -411,33 +385,11 @@ namespace VEPROMS.CSLA.Library _GroupExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(GID, ""); - //AuthorizationRules.AllowRead(GroupName, ""); - //AuthorizationRules.AllowRead(GroupType, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(GroupName, ""); - //AuthorizationRules.AllowWrite(GroupType, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); _GroupExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -445,56 +397,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _GroupExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _GroupAssignmentCount; - usedByCount += _GroupMembershipCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _GroupUnique = 0; - protected static int GroupUnique - { get { return ++_GroupUnique; } } - private int _MyGroupUnique = GroupUnique; - public int MyGroupUnique // Absolutely Unique ID - Editable - { get { return _MyGroupUnique; } } + protected static int GroupUnique => ++_GroupUnique; + private readonly int _MyGroupUnique = GroupUnique; + // Absolutely Unique ID - Editable + public int MyGroupUnique => _MyGroupUnique; protected Group() {/* require use of factory methods */ AddToCache(this); @@ -503,15 +413,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Group() { _CountFinalized++; @@ -548,8 +454,6 @@ namespace VEPROMS.CSLA.Library } public static Group New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Group"); try { return DataPortal.Create(); @@ -617,8 +521,6 @@ namespace VEPROMS.CSLA.Library } public static Group Get(int gid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Group"); try { Group tmp = GetCachedByPrimaryKey(gid); @@ -641,8 +543,6 @@ namespace VEPROMS.CSLA.Library } public static Group GetByGroupName(string groupName) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Group"); try { Group tmp = GetCachedByGroupName(groupName); @@ -668,14 +568,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Group(dr); return null; } - internal Group(SafeDataReader dr) - { - ReadData(dr); - } + internal Group(SafeDataReader dr) => ReadData(dr); public static void Delete(int gid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Group"); try { DataPortal.Delete(new PKCriteria(gid)); @@ -687,12 +582,6 @@ namespace VEPROMS.CSLA.Library } public override Group Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Group"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Group"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Group"); try { BuildRefreshList(); @@ -712,24 +601,16 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _GID; - public int GID - { get { return _GID; } } - public PKCriteria(int gid) - { - _GID = gid; - } + private readonly int _GID; + public int GID => _GID; + public PKCriteria(int gid) => _GID = gid; } [Serializable()] private class GroupNameCriteria { - private string _GroupName; - public string GroupName - { get { return _GroupName; } } - public GroupNameCriteria(string groupName) - { - _GroupName = groupName; - } + private readonly string _GroupName; + public string GroupName => _GroupName; + public GroupNameCriteria(string groupName) => _GroupName = groupName; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -843,7 +724,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Group.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -868,41 +749,49 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addGroup"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@GroupName", _GroupName); - cm.Parameters.AddWithValue("@GroupType", _GroupType); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_GID = new SqlParameter("@newGID", SqlDbType.Int); - param_GID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_GID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _GID = (int)cm.Parameters["@newGID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addGroup"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@GroupName", _GroupName); + cm.Parameters.AddWithValue("@GroupType", _GroupType); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_GID = new SqlParameter("@newGID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_GID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _GID = (int)cm.Parameters["@newGID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_GroupAssignments != null) _GroupAssignments.Update(this); - if (_GroupMemberships != null) _GroupMemberships.Update(this); + _GroupAssignments?.Update(this); + _GroupMemberships?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -912,7 +801,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Group.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int gid, string groupName, int? groupType, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.Add", 0); @@ -930,11 +819,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_GID = new SqlParameter("@newGID", SqlDbType.Int); - param_GID.Direction = ParameterDirection.Output; + SqlParameter param_GID = new SqlParameter("@newGID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_GID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -949,7 +842,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Group.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -972,43 +865,49 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateGroup"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@GID", _GID); - cm.Parameters.AddWithValue("@GroupName", _GroupName); - cm.Parameters.AddWithValue("@GroupType", _GroupType); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateGroup"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@GID", _GID); + cm.Parameters.AddWithValue("@GroupName", _GroupName); + cm.Parameters.AddWithValue("@GroupType", _GroupType); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_GroupAssignments != null) _GroupAssignments.Update(this); - if (_GroupMemberships != null) _GroupMemberships.Update(this); + _GroupAssignments?.Update(this); + _GroupMemberships?.Update(this); } catch (Exception ex) { @@ -1019,20 +918,24 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Group.Add(cn, ref _GID, _GroupName, _GroupType, _Config, _DTS, _UsrID); - else - _LastChanged = Group.Update(cn, ref _GID, _GroupName, _GroupType, _Config, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Group.Add(cn, ref _GID, _GroupName, _GroupType, _Config, _DTS, _UsrID); + else + _LastChanged = Group.Update(cn, ref _GID, _GroupName, _GroupType, _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } - if (_GroupAssignments != null) _GroupAssignments.Update(this); - if (_GroupMemberships != null) _GroupMemberships.Update(this); + _GroupAssignments?.Update(this); + _GroupMemberships?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int gid, string groupName, int? groupType, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.Update", 0); @@ -1052,8 +955,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1067,12 +972,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Group.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_GID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.DataPortal_Delete", GetHashCode()); @@ -1097,7 +1002,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Group.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int gid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.Remove", 0); @@ -1138,16 +1043,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _GID; + private readonly int _GID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int gid) - { - _GID = gid; - } + public bool Exists => _exists; + public ExistsCommand(int gid) => _GID = gid; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.DataPortal_Execute", GetHashCode()); @@ -1155,7 +1054,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1177,7 +1076,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - GroupExtension _GroupExtension = new GroupExtension(); + readonly GroupExtension _GroupExtension = new GroupExtension(); [Serializable()] partial class GroupExtension : extensionBase { @@ -1186,14 +1085,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1222,57 +1115,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Group) + if (destType == typeof(string) && value is Group group) { // Return the ToString value - return ((Group)value).ToString(); + return group.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create GroupExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Group -// { -// partial class GroupExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignment.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignment.cs index 383daa99..197db379 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignment.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignment.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _AID; [System.ComponentModel.DataObjectField(true, true)] public int AID @@ -343,19 +337,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current GroupAssignment - protected override object GetIdValue() - { - return MyGroupAssignmentUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base GroupAssignment.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current GroupAssignment - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyGroupAssignmentUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -370,18 +352,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRole == null ? false : _MyRole.IsDirtyList(list)) || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRole != null && _MyRole.IsDirtyList(list)) || (_MyFolder != null && _MyFolder.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRole == null ? true : _MyRole.IsValidList(list)) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRole == null || _MyRole.IsValidList(list)) && (_MyFolder == null || _MyFolder.IsValidList(list)); } #endregion #region ValidationRules @@ -413,7 +392,7 @@ namespace VEPROMS.CSLA.Library { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -475,80 +454,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AID, ""); - //AuthorizationRules.AllowRead(RID, ""); - //AuthorizationRules.AllowWrite(RID, ""); - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowWrite(FolderID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _GroupAssignmentUnique = 0; - private static int GroupAssignmentUnique - { get { return ++_GroupAssignmentUnique; } } - private int _MyGroupAssignmentUnique = GroupAssignmentUnique; - public int MyGroupAssignmentUnique // Absolutely Unique ID - Editable FK - { get { return _MyGroupAssignmentUnique; } } - internal static GroupAssignment New(Role myRole, Folder myFolder) - { - return new GroupAssignment(myRole, myFolder); - } - internal static GroupAssignment Get(SafeDataReader dr) - { - return new GroupAssignment(dr); - } + private static int GroupAssignmentUnique => ++_GroupAssignmentUnique; + private readonly int _MyGroupAssignmentUnique = GroupAssignmentUnique; + // Absolutely Unique ID - Editable FK + public int MyGroupAssignmentUnique => _MyGroupAssignmentUnique; + internal static GroupAssignment New(Role myRole, Folder myFolder) => new GroupAssignment(myRole, myFolder); + internal static GroupAssignment Get(SafeDataReader dr) => new GroupAssignment(dr); public GroupAssignment() { MarkAsChild(); @@ -579,15 +500,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~GroupAssignment() { _CountFinalized++; @@ -639,32 +556,45 @@ namespace VEPROMS.CSLA.Library { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Assignment.Add(cn, ref _AID, myGroup, _MyRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Assignment.Add(cn, ref _AID, myGroup, _MyRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + } + MarkOld(); } internal void Update(Group myGroup) { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Assignment.Update(cn, ref _AID, myGroup.GID, _RID, _FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Assignment.Update(cn, ref _AID, myGroup.GID, _RID, _FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Group myGroup) { // if we're not dirty then don't update the database if (!this.IsDirty) return; // if we're new then don't update the database if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Assignment.Remove(cn, _AID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Assignment.Remove(cn, _AID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - GroupAssignmentExtension _GroupAssignmentExtension = new GroupAssignmentExtension(); + readonly GroupAssignmentExtension _GroupAssignmentExtension = new GroupAssignmentExtension(); [Serializable()] partial class GroupAssignmentExtension : extensionBase { @@ -673,18 +603,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -713,61 +634,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GroupAssignment) + if (destType == typeof(string) && value is GroupAssignment assignment) { // Return the ToString value - return ((GroupAssignment)value).ToString(); + return assignment.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create GroupAssignmentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class GroupAssignment -// { -// partial class GroupAssignmentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignments.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignments.cs index 4dfcb37c..8c7749f6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignments.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GroupAssignments.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public GroupAssignment this[Assignment myAssignment] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public GroupAssignment this[Assignment myAssignment] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public GroupAssignment GetItem(Assignment myAssignment) + public new System.Collections.Generic.IList Items => base.Items; + public GroupAssignment GetItem(Assignment myAssignment) { foreach (GroupAssignment assignment in this) if (assignment.AID == myAssignment.AID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public GroupAssignment Add(Role myRole, Folder myFolder) // One to Many { GroupAssignment assignment = GroupAssignment.New(myRole, myFolder); - this.Add(assignment); + Add(assignment); return assignment; } public void Remove(Assignment myAssignment) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (GroupAssignment child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (GroupAssignment child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static GroupAssignments New() - { - return new GroupAssignments(); - } - internal static GroupAssignments Get(SafeDataReader dr) - { - return new GroupAssignments(dr); - } - public static GroupAssignments GetByGID(int gid) + #endregion + #region Factory Methods + internal static GroupAssignments New() => new GroupAssignments(); + internal static GroupAssignments Get(SafeDataReader dr) => new GroupAssignments(dr); + public static GroupAssignments GetByGID(int gid) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on GroupAssignments.GetByGID", ex); } } - private GroupAssignments() - { - MarkAsChild(); - } - internal GroupAssignments(SafeDataReader dr) + private GroupAssignments() => MarkAsChild(); + internal GroupAssignments(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~GroupAssignments() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~GroupAssignments() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(GroupAssignment.Get(dr)); - this.RaiseListChangedEvents = true; + Add(GroupAssignment.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class GIDCriteria { - public GIDCriteria(int gid) - { - _GID = gid; - } - private int _GID; + public GIDCriteria(int gid) => _GID = gid; + private int _GID; public int GID { get { return _GID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(GIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GroupAssignments.DataPortal_FetchGID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new GroupAssignment(dr)); + while (dr.Read()) Add(new GroupAssignment(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("GroupAssignments.DataPortal_FetchGID", ex); throw new DbCslaException("GroupAssignments.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Group group) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection GroupAssignmentsPropertyDescriptor pd = new GroupAssignmentsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class GroupAssignmentsPropertyDescriptor : vlnListPropertyDescriptor { - private GroupAssignment Item { get { return (GroupAssignment)_Item; } } public GroupAssignmentsPropertyDescriptor(GroupAssignments collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GroupAssignments) + if (destType == typeof(string) && value is GroupAssignments assignments) { // Return department and department role separated by comma. - return ((GroupAssignments)value).Items.Count.ToString() + " Assignments"; + return $"{assignments.Items.Count} Assignments"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfo.cs index c10b6b4c..761e4c48 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class GroupInfo : ReadOnlyBase, IDisposable { public event GroupInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(GroupInfo groupInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(groupInfo)) _CacheList.Remove(groupInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -79,16 +76,6 @@ namespace VEPROMS.CSLA.Library get { return _ErrorMessage; } } protected Group _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _GID; [System.ComponentModel.DataObjectField(true, true)] public int GID @@ -216,32 +203,19 @@ namespace VEPROMS.CSLA.Library foreach (GroupInfo tmp in _CacheByPrimaryKey[_GID.ToString()]) tmp._GroupMembershipCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base GroupInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current GroupInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check GroupInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current GroupInfo - protected override object GetIdValue() - { - return MyGroupInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyGroupInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _GroupInfoUnique = 0; - private static int GroupInfoUnique - { get { return ++_GroupInfoUnique; } } - private int _MyGroupInfoUnique = GroupInfoUnique; - public int MyGroupInfoUnique // Absolutely Unique ID - Info - { get { return _MyGroupInfoUnique; } } + private static int GroupInfoUnique => ++_GroupInfoUnique; + private readonly int _MyGroupInfoUnique = GroupInfoUnique; + // Absolutely Unique ID - Info + public int MyGroupInfoUnique => _MyGroupInfoUnique; protected GroupInfo() {/* require use of factory methods */ AddToCache(this); @@ -250,15 +224,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~GroupInfo() { _CountFinalized++; @@ -275,10 +245,7 @@ namespace VEPROMS.CSLA.Library if (listGroupInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(GID.ToString()); // remove the list } - public virtual Group Get() - { - return _Editable = Group.Get(_GID); - } + public virtual Group Get() => _Editable = Group.Get(_GID); public static void Refresh(Group tmp) { string key = tmp.GID.ToString(); @@ -299,8 +266,6 @@ namespace VEPROMS.CSLA.Library } public static GroupInfo Get(int gid) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Group"); try { GroupInfo tmp = GetCachedByPrimaryKey(gid); @@ -339,13 +304,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _GID; - public int GID - { get { return _GID; } } - public PKCriteria(int gid) - { - _GID = gid; - } + private readonly int _GID; + public int GID => _GID; + public PKCriteria(int gid) => _GID = gid; } private void ReadData(SafeDataReader dr) { @@ -407,7 +368,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - GroupInfoExtension _GroupInfoExtension = new GroupInfoExtension(); + readonly GroupInfoExtension _GroupInfoExtension = new GroupInfoExtension(); [Serializable()] partial class GroupInfoExtension : extensionBase { } [Serializable()] @@ -423,10 +384,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GroupInfo) + if (destType == typeof(string) && value is GroupInfo info) { // Return the ToString value - return ((GroupInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfoList.cs index aa71ec4c..ccc67d04 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GroupInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (GroupInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~GroupInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~GroupInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on GroupInfoList.Get", ex); } } - /// - /// Reset the list of all GroupInfo. - /// - public static void Reset() - { - _GroupInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static GroupInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on GroupInfoList.Get", ex); - // } - //} - private GroupInfoList() + /// + /// Reset the list of all GroupInfo. + /// + public static void Reset() => _GroupInfoList = null; + private GroupInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class GroupInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private GroupInfo Item { get { return (GroupInfo)_Item; } } public GroupInfoListPropertyDescriptor(GroupInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GroupInfoList) + if (destType == typeof(string) && value is GroupInfoList list) { // Return department and department role separated by comma. - return ((GroupInfoList)value).Items.Count.ToString() + " Groups"; + return $"{list.Items.Count} Groups"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GroupMembership.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GroupMembership.cs index b080ad3d..41acefc2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GroupMembership.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GroupMembership.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _UGID; [System.ComponentModel.DataObjectField(true, true)] public int UGID @@ -323,19 +317,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current GroupMembership - protected override object GetIdValue() - { - return MyGroupMembershipUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base GroupMembership.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current GroupMembership - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyGroupMembershipUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -350,7 +332,7 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyUser == null ? false : _MyUser.IsDirtyList(list)); + return base.IsDirty || (_MyUser != null && _MyUser.IsDirtyList(list)); } public override bool IsValid { @@ -359,9 +341,9 @@ namespace VEPROMS.CSLA.Library public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyUser == null ? true : _MyUser.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyUser == null || _MyUser.IsValidList(list)); } #endregion #region ValidationRules @@ -391,8 +373,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -447,80 +429,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(UGID, ""); - //AuthorizationRules.AllowRead(UID, ""); - //AuthorizationRules.AllowWrite(UID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _GroupMembershipUnique = 0; - private static int GroupMembershipUnique - { get { return ++_GroupMembershipUnique; } } - private int _MyGroupMembershipUnique = GroupMembershipUnique; - public int MyGroupMembershipUnique // Absolutely Unique ID - Editable FK - { get { return _MyGroupMembershipUnique; } } - internal static GroupMembership New(User myUser) - { - return new GroupMembership(myUser); - } - internal static GroupMembership Get(SafeDataReader dr) - { - return new GroupMembership(dr); - } + private static int GroupMembershipUnique => ++_GroupMembershipUnique; + private readonly int _MyGroupMembershipUnique = GroupMembershipUnique; + // Absolutely Unique ID - Editable FK + public int MyGroupMembershipUnique => _MyGroupMembershipUnique; + internal static GroupMembership New(User myUser) => new GroupMembership(myUser); + internal static GroupMembership Get(SafeDataReader dr) => new GroupMembership(dr); public GroupMembership() { MarkAsChild(); @@ -550,15 +474,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~GroupMembership() { _CountFinalized++; @@ -608,33 +528,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Group myGroup) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Membership.Add(cn, ref _UGID, _MyUser, myGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Membership.Add(cn, ref _UGID, _MyUser, myGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + } + MarkOld(); } internal void Update(Group myGroup) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Membership.Update(cn, ref _UGID, _UID, myGroup.GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Membership.Update(cn, ref _UGID, _UID, myGroup.GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Group myGroup) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Membership.Remove(cn, _UGID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Membership.Remove(cn, _UGID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - GroupMembershipExtension _GroupMembershipExtension = new GroupMembershipExtension(); + readonly GroupMembershipExtension _GroupMembershipExtension = new GroupMembershipExtension(); [Serializable()] partial class GroupMembershipExtension : extensionBase { @@ -643,18 +576,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -683,61 +607,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GroupMembership) + if (destType == typeof(string) && value is GroupMembership membership) { // Return the ToString value - return ((GroupMembership)value).ToString(); + return membership.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create GroupMembershipExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class GroupMembership -// { -// partial class GroupMembershipExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/GroupMemberships.cs b/PROMS/VEPROMS.CSLA.Library/Generated/GroupMemberships.cs index 132e41ea..3ec97e6b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/GroupMemberships.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/GroupMemberships.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public GroupMembership this[Membership myMembership] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public GroupMembership this[Membership myMembership] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public GroupMembership GetItem(Membership myMembership) + public new System.Collections.Generic.IList Items => base.Items; + public GroupMembership GetItem(Membership myMembership) { foreach (GroupMembership membership in this) if (membership.UGID == myMembership.UGID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public GroupMembership Add(User myUser) // One to Many { GroupMembership membership = GroupMembership.New(myUser); - this.Add(membership); + Add(membership); return membership; } public void Remove(Membership myMembership) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (GroupMembership child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (GroupMembership child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static GroupMemberships New() - { - return new GroupMemberships(); - } - internal static GroupMemberships Get(SafeDataReader dr) - { - return new GroupMemberships(dr); - } - public static GroupMemberships GetByGID(int gid) + #endregion + #region Factory Methods + internal static GroupMemberships New() => new GroupMemberships(); + internal static GroupMemberships Get(SafeDataReader dr) => new GroupMemberships(dr); + public static GroupMemberships GetByGID(int gid) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on GroupMemberships.GetByGID", ex); } } - private GroupMemberships() - { - MarkAsChild(); - } - internal GroupMemberships(SafeDataReader dr) + private GroupMemberships() => MarkAsChild(); + internal GroupMemberships(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~GroupMemberships() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~GroupMemberships() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(GroupMembership.Get(dr)); - this.RaiseListChangedEvents = true; + Add(GroupMembership.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class GIDCriteria { - public GIDCriteria(int gid) - { - _GID = gid; - } - private int _GID; + public GIDCriteria(int gid) => _GID = gid; + private int _GID; public int GID { get { return _GID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(GIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] GroupMemberships.DataPortal_FetchGID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new GroupMembership(dr)); + while (dr.Read()) Add(new GroupMembership(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("GroupMemberships.DataPortal_FetchGID", ex); throw new DbCslaException("GroupMemberships.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Group group) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection GroupMembershipsPropertyDescriptor pd = new GroupMembershipsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class GroupMembershipsPropertyDescriptor : vlnListPropertyDescriptor { - private GroupMembership Item { get { return (GroupMembership)_Item; } } public GroupMembershipsPropertyDescriptor(GroupMemberships collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is GroupMemberships) + if (destType == typeof(string) && value is GroupMemberships memberships) { // Return department and department role separated by comma. - return ((GroupMemberships)value).Items.Count.ToString() + " Memberships"; + return $"{memberships.Items.Count} Memberships"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Image.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Image.cs index 65aca996..188c7100 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Image.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Image.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshImages.Add(this); } - private void ClearRefreshList() - { - _RefreshImages = new List(); - } + private void ClearRefreshList() => _RefreshImages = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,16 +51,18 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] protected static void AddToCache(Image image) { - // B2021-147 commented out to fix out of memory bug - //if (!_CacheList.Contains(image)) _CacheList.Add(image); // In AddToCache + } protected static void RemoveFromCache(Image image) { while (_CacheList.Contains(image)) _CacheList.Remove(image); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -91,10 +88,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -232,40 +226,18 @@ namespace VEPROMS.CSLA.Library } } private byte[] _LastChanged = new byte[8];//timestamp - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base Image.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Image - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check Image.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Image - protected override object GetIdValue() - { - return MyImageUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyImageUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -293,8 +265,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -321,35 +293,11 @@ namespace VEPROMS.CSLA.Library _ImageExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(ImageType, ""); - //AuthorizationRules.AllowRead(FileName, ""); - //AuthorizationRules.AllowRead(Data, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ImageType, ""); - //AuthorizationRules.AllowWrite(FileName, ""); - //AuthorizationRules.AllowWrite(Data, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _ImageExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -357,42 +305,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ImageExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ImageUnique = 0; - protected static int ImageUnique - { get { return ++_ImageUnique; } } - private int _MyImageUnique = ImageUnique; - public int MyImageUnique // Absolutely Unique ID - Editable - { get { return _MyImageUnique; } } + protected static int ImageUnique => ++_ImageUnique; + private readonly int _MyImageUnique = ImageUnique; + // Absolutely Unique ID - Editable + public int MyImageUnique => _MyImageUnique; protected Image() {/* require use of factory methods */ AddToCache(this); @@ -401,15 +321,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Image() { _CountFinalized++; @@ -434,8 +350,6 @@ namespace VEPROMS.CSLA.Library } public static Image New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Image"); try { return DataPortal.Create(); @@ -516,8 +430,6 @@ namespace VEPROMS.CSLA.Library } public static Image Get(int contentID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Image"); try { Image tmp = GetCachedByPrimaryKey(contentID); @@ -543,14 +455,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Image(dr); return null; } - internal Image(SafeDataReader dr) - { - ReadData(dr); - } + internal Image(SafeDataReader dr) => ReadData(dr); public static void Delete(int contentID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Image"); try { DataPortal.Delete(new PKCriteria(contentID)); @@ -562,12 +469,6 @@ namespace VEPROMS.CSLA.Library } public override Image Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Image"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Image"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Image"); try { BuildRefreshList(); @@ -587,13 +488,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -665,7 +562,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Image.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -690,35 +587,41 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addImage"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@ImageType", _ImageType); - cm.Parameters.AddWithValue("@FileName", _FileName); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addImage"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@ImageType", _ImageType); + cm.Parameters.AddWithValue("@FileName", _FileName); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.SQLInsert", GetHashCode()); @@ -730,7 +633,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Image.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Content myContent, int imageType, string fileName, byte[] data, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.Add", 0); @@ -750,8 +653,10 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -765,7 +670,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Image.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -788,40 +693,46 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateImage"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@ImageType", _ImageType); - cm.Parameters.AddWithValue("@FileName", _FileName); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateImage"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@ImageType", _ImageType); + cm.Parameters.AddWithValue("@FileName", _FileName); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -834,18 +745,22 @@ namespace VEPROMS.CSLA.Library } internal void Update(Content content) { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Image.Add(cn, content, _ImageType, _FileName, _Data, _Config, _DTS, _UserID); - else - _LastChanged = Image.Update(cn, content.ContentID, _ImageType, _FileName, _Data, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Image.Add(cn, content, _ImageType, _FileName, _Data, _Config, _DTS, _UserID); + else + _LastChanged = Image.Update(cn, content.ContentID, _ImageType, _FileName, _Data, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int contentID, int imageType, string fileName, byte[] data, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.Update", 0); @@ -866,8 +781,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -881,12 +798,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Image.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ContentID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.DataPortal_Delete", GetHashCode()); @@ -911,7 +828,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Image.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int contentID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.Remove", 0); @@ -952,16 +869,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ContentID; + private readonly int _ContentID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int contentID) - { - _ContentID = contentID; - } + public bool Exists => _exists; + public ExistsCommand(int contentID) => _ContentID = contentID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Image.DataPortal_Execute", GetHashCode()); @@ -969,7 +880,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -991,7 +902,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ImageExtension _ImageExtension = new ImageExtension(); + readonly ImageExtension _ImageExtension = new ImageExtension(); [Serializable()] partial class ImageExtension : extensionBase { @@ -1000,18 +911,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultImageType - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultImageType => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1040,61 +942,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Image) + if (destType == typeof(string) && value is Image myimage) { // Return the ToString value - return ((Image)value).ToString(); + return myimage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ImageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Image -// { -// partial class ImageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultImageType -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ImageAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ImageAudit.cs index e7b500b6..c66a265d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ImageAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ImageAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshImageAudits.Add(this); } - private void ClearRefreshList() - { - _RefreshImageAudits = new List(); - } + private void ClearRefreshList() => _RefreshImageAudits = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ImageAudit imageAudit) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(imageAudit)) _CacheList.Remove(imageAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -256,40 +247,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base ImageAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ImageAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check ImageAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ImageAudit - protected override object GetIdValue() - { - return MyImageAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyImageAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -317,8 +282,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -345,39 +310,11 @@ namespace VEPROMS.CSLA.Library _ImageAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(ImageType, ""); - //AuthorizationRules.AllowRead(FileName, ""); - //AuthorizationRules.AllowRead(Data, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(ImageType, ""); - //AuthorizationRules.AllowWrite(FileName, ""); - //AuthorizationRules.AllowWrite(Data, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); _ImageAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -385,42 +322,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ImageAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ImageAuditUnique = 0; - protected static int ImageAuditUnique - { get { return ++_ImageAuditUnique; } } - private int _MyImageAuditUnique = ImageAuditUnique; - public int MyImageAuditUnique // Absolutely Unique ID - Editable - { get { return _MyImageAuditUnique; } } + protected static int ImageAuditUnique => ++_ImageAuditUnique; + private readonly int _MyImageAuditUnique = ImageAuditUnique; + // Absolutely Unique ID - Editable + public int MyImageAuditUnique => _MyImageAuditUnique; protected ImageAudit() {/* require use of factory methods */ AddToCache(this); @@ -429,15 +338,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ImageAudit() { _CountFinalized++; @@ -462,8 +367,6 @@ namespace VEPROMS.CSLA.Library } public static ImageAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ImageAudit"); try { return DataPortal.Create(); @@ -516,8 +419,6 @@ namespace VEPROMS.CSLA.Library } public static ImageAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ImageAudit"); try { ImageAudit tmp = GetCachedByPrimaryKey(auditID); @@ -543,14 +444,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new ImageAudit(dr); return null; } - internal ImageAudit(SafeDataReader dr) - { - ReadData(dr); - } + internal ImageAudit(SafeDataReader dr) => ReadData(dr); public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ImageAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -562,12 +458,6 @@ namespace VEPROMS.CSLA.Library } public override ImageAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ImageAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ImageAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ImageAudit"); try { BuildRefreshList(); @@ -587,13 +477,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -664,7 +550,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ImageAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -689,36 +575,42 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addImageAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@ImageType", _ImageType); - cm.Parameters.AddWithValue("@FileName", _FileName); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addImageAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@ImageType", _ImageType); + cm.Parameters.AddWithValue("@FileName", _FileName); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.SQLInsert", GetHashCode()); @@ -730,7 +622,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ImageAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int contentID, int imageType, string fileName, byte[] data, string config, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.Add", 0); @@ -751,8 +643,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -767,7 +661,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ImageAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -790,37 +684,41 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateImageAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@ImageType", _ImageType); - cm.Parameters.AddWithValue("@FileName", _FileName); - cm.Parameters.AddWithValue("@Data", _Data); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateImageAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@ImageType", _ImageType); + cm.Parameters.AddWithValue("@FileName", _FileName); + cm.Parameters.AddWithValue("@Data", _Data); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -833,18 +731,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - ImageAudit.Add(cn, ref _AuditID, _ContentID, _ImageType, _FileName, _Data, _Config, _DTS, _UserID, _DeleteStatus); - else - ImageAudit.Update(cn, ref _AuditID, _ContentID, _ImageType, _FileName, _Data, _Config, _DTS, _UserID, _DeleteStatus); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + ImageAudit.Add(cn, ref _AuditID, _ContentID, _ImageType, _FileName, _Data, _Config, _DTS, _UserID, _DeleteStatus); + else + ImageAudit.Update(cn, ref _AuditID, _ContentID, _ImageType, _FileName, _Data, _Config, _DTS, _UserID, _DeleteStatus); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int contentID, int imageType, string fileName, byte[] data, string config, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.Update", 0); @@ -878,12 +780,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ImageAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.DataPortal_Delete", GetHashCode()); @@ -908,7 +810,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ImageAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ImageAudit.Remove", 0); @@ -934,7 +836,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ImageAuditExtension _ImageAuditExtension = new ImageAuditExtension(); + readonly ImageAuditExtension _ImageAuditExtension = new ImageAuditExtension(); [Serializable()] partial class ImageAuditExtension : extensionBase { @@ -971,49 +873,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ImageAudit) + if (destType == typeof(string) && value is ImageAudit audit) { // Return the ToString value - return ((ImageAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ImageAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ImageAudit -// { -// partial class ImageAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfo.cs index 99e26e9f..b4b96350 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ImageAuditInfo : ReadOnlyBase, IDisposable { public event ImageAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ImageAuditInfo imageAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(imageAuditInfo)) _CacheList.Remove(imageAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ImageAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -171,32 +155,19 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base ImageAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ImageAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ImageAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ImageAuditInfo - protected override object GetIdValue() - { - return MyImageAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyImageAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ImageAuditInfoUnique = 0; - private static int ImageAuditInfoUnique - { get { return ++_ImageAuditInfoUnique; } } - private int _MyImageAuditInfoUnique = ImageAuditInfoUnique; - public int MyImageAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyImageAuditInfoUnique; } } + private static int ImageAuditInfoUnique => ++_ImageAuditInfoUnique; + private readonly int _MyImageAuditInfoUnique = ImageAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyImageAuditInfoUnique => _MyImageAuditInfoUnique; protected ImageAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -205,15 +176,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ImageAuditInfo() { _CountFinalized++; @@ -230,10 +197,7 @@ namespace VEPROMS.CSLA.Library if (listImageAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual ImageAudit Get() - { - return _Editable = ImageAudit.Get(_AuditID); - } + public virtual ImageAudit Get() => _Editable = ImageAudit.Get(_AuditID); public static void Refresh(ImageAudit tmp) { string key = tmp.AuditID.ToString(); @@ -257,8 +221,6 @@ namespace VEPROMS.CSLA.Library } public static ImageAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ImageAudit"); try { ImageAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -297,13 +259,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -366,7 +324,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ImageAuditInfoExtension _ImageAuditInfoExtension = new ImageAuditInfoExtension(); + readonly ImageAuditInfoExtension _ImageAuditInfoExtension = new ImageAuditInfoExtension(); [Serializable()] partial class ImageAuditInfoExtension : extensionBase { } [Serializable()] @@ -382,10 +340,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ImageAuditInfo) + if (destType == typeof(string) && value is ImageAuditInfo info) { // Return the ToString value - return ((ImageAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfoList.cs index 24145e14..84283328 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ImageAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ImageAuditInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ImageAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ImageAuditInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ImageAuditInfoList.Get", ex); } } - /// - /// Reset the list of all ImageAuditInfo. - /// - public static void Reset() - { - _ImageAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ImageAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ImageAuditInfoList.Get", ex); - // } - //} - private ImageAuditInfoList() + /// + /// Reset the list of all ImageAuditInfo. + /// + public static void Reset() => _ImageAuditInfoList = null; + private ImageAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ImageAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ImageAuditInfo Item { get { return (ImageAuditInfo)_Item; } } public ImageAuditInfoListPropertyDescriptor(ImageAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ImageAuditInfoList) + if (destType == typeof(string) && value is ImageAuditInfoList list) { // Return department and department role separated by comma. - return ((ImageAuditInfoList)value).Items.Count.ToString() + " ImageAudits"; + return $"{list.Items.Count} ImageAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ImageInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ImageInfo.cs index 36a2a7d4..5489bf52 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ImageInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ImageInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ImageInfo : ReadOnlyBase, IDisposable { public event ImageInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ImageInfo imageInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(imageInfo)) _CacheList.Remove(imageInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -70,21 +67,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Image _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -164,32 +148,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base ImageInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ImageInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ImageInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ImageInfo - protected override object GetIdValue() - { - return MyImageInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyImageInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ImageInfoUnique = 0; - private static int ImageInfoUnique - { get { return ++_ImageInfoUnique; } } - private int _MyImageInfoUnique = ImageInfoUnique; - public int MyImageInfoUnique // Absolutely Unique ID - Info - { get { return _MyImageInfoUnique; } } + private static int ImageInfoUnique => ++_ImageInfoUnique; + private readonly int _MyImageInfoUnique = ImageInfoUnique; + // Absolutely Unique ID - Info + public int MyImageInfoUnique => _MyImageInfoUnique; protected ImageInfo() {/* require use of factory methods */ AddToCache(this); @@ -198,15 +169,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ImageInfo() { _CountFinalized++; @@ -223,10 +190,7 @@ namespace VEPROMS.CSLA.Library if (listImageInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list } - public virtual Image Get() - { - return _Editable = Image.Get(_ContentID); - } + public virtual Image Get() => _Editable = Image.Get(_ContentID); public static void Refresh(Image tmp) { string key = tmp.ContentID.ToString(); @@ -244,20 +208,10 @@ namespace VEPROMS.CSLA.Library _DTS = tmp.DTS; _UserID = tmp.UserID; _ImageInfoExtension.Refresh(this); - //RHM Removed 20090724 - Duplicates function of code above. - // - Dispose caused error when a new step was added. - // - Resequence of transitions did not work properly. - // if(_MyContent != null) - // { - // _MyContent.Dispose();// Dispose related value - // _MyContent = null;// Reset related value - // } OnChange();// raise an event } public static ImageInfo Get(int contentID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Image"); try { ImageInfo tmp = GetCachedByPrimaryKey(contentID); @@ -296,13 +250,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } private void ReadData(SafeDataReader dr) { @@ -363,7 +313,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ImageInfoExtension _ImageInfoExtension = new ImageInfoExtension(); + readonly ImageInfoExtension _ImageInfoExtension = new ImageInfoExtension(); [Serializable()] partial class ImageInfoExtension : extensionBase { } [Serializable()] @@ -379,10 +329,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ImageInfo) + if (destType == typeof(string) && value is ImageInfo info) { // Return the ToString value - return ((ImageInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Item.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Item.cs index 2ea29707..adb29028 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Item.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Item.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -133,6 +131,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Item item) { @@ -142,6 +141,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(item)) _CacheList.Remove(item); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -167,15 +167,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextItemID = -1; - public static int NextItemID - { - get { return _nextItemID--; } - } + public static int NextItemID => _nextItemID--; private int _ItemID; [System.ComponentModel.DataObjectField(true, true)] public int ItemID @@ -315,10 +309,7 @@ namespace VEPROMS.CSLA.Library return _ItemAnnotations; } } - public void Reset_ItemAnnotations() - { - _ItemAnnotationCount = -1; - } + public void Reset_ItemAnnotations() => _ItemAnnotationCount = -1; private int _ItemDocVersionCount = 0; /// /// Count of ItemDocVersions for this Item @@ -350,10 +341,7 @@ namespace VEPROMS.CSLA.Library return _ItemDocVersions; } } - public void Reset_ItemDocVersions() - { - _ItemDocVersionCount = -1; - } + public void Reset_ItemDocVersions() => _ItemDocVersionCount = -1; private int _NextItemCount = 0; /// /// Count of NextItems for this Item @@ -385,10 +373,7 @@ namespace VEPROMS.CSLA.Library return _NextItems; } } - public void Reset_NextItems() - { - _NextItemCount = -1; - } + public void Reset_NextItems() => _NextItemCount = -1; private int _ItemPartCount = 0; /// /// Count of ItemParts for this Item @@ -420,10 +405,7 @@ namespace VEPROMS.CSLA.Library return _ItemParts; } } - public void Reset_ItemParts() - { - _ItemPartCount = -1; - } + public void Reset_ItemParts() => _ItemPartCount = -1; private int _ItemTransition_RangeIDCount = 0; /// /// Count of ItemTransitions for this Item @@ -455,10 +437,7 @@ namespace VEPROMS.CSLA.Library return _ItemTransitions_RangeID; } } - public void Reset_ItemTransitions_RangeID() - { - _ItemTransition_RangeIDCount = -1; - } + public void Reset_ItemTransitions_RangeID() => _ItemTransition_RangeIDCount = -1; private int _ItemTransition_ToIDCount = 0; /// /// Count of ItemTransitions for this Item @@ -490,10 +469,7 @@ namespace VEPROMS.CSLA.Library return _ItemTransitions_ToID; } } - public void Reset_ItemTransitions_ToID() - { - _ItemTransition_ToIDCount = -1; - } + public void Reset_ItemTransitions_ToID() => _ItemTransition_ToIDCount = -1; public override bool IsDirty { get @@ -508,37 +484,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_ItemAnnotations == null ? false : _ItemAnnotations.IsDirtyList(list)) || (_ItemDocVersions == null ? false : _ItemDocVersions.IsDirtyList(list)) || (_NextItems == null ? false : _NextItems.IsDirtyList(list)) || (_ItemParts == null ? false : _ItemParts.IsDirtyList(list)) || (_ItemTransitions_RangeID == null ? false : _ItemTransitions_RangeID.IsDirtyList(list)) || (_ItemTransitions_ToID == null ? false : _ItemTransitions_ToID.IsDirtyList(list)) || (_MyContent == null ? false : _MyContent.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_ItemAnnotations != null && _ItemAnnotations.IsDirtyList(list)) || (_ItemDocVersions != null && _ItemDocVersions.IsDirtyList(list)) || (_NextItems != null && _NextItems.IsDirtyList(list)) || (_ItemParts != null && _ItemParts.IsDirtyList(list)) || (_ItemTransitions_RangeID != null && _ItemTransitions_RangeID.IsDirtyList(list)) || (_ItemTransitions_ToID != null && _ItemTransitions_ToID.IsDirtyList(list)) || (_MyContent != null && _MyContent.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_ItemAnnotations == null ? true : _ItemAnnotations.IsValidList(list)) && (_ItemDocVersions == null ? true : _ItemDocVersions.IsValidList(list)) && (_NextItems == null ? true : _NextItems.IsValidList(list)) && (_ItemParts == null ? true : _ItemParts.IsValidList(list)) && (_ItemTransitions_RangeID == null ? true : _ItemTransitions_RangeID.IsValidList(list)) && (_ItemTransitions_ToID == null ? true : _ItemTransitions_ToID.IsValidList(list)) && (_MyContent == null ? true : _MyContent.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_ItemAnnotations == null || _ItemAnnotations.IsValidList(list)) && (_ItemDocVersions == null || _ItemDocVersions.IsValidList(list)) && (_NextItems == null || _NextItems.IsValidList(list)) && (_ItemParts == null || _ItemParts.IsValidList(list)) && (_ItemTransitions_RangeID == null || _ItemTransitions_RangeID.IsValidList(list)) && (_ItemTransitions_ToID == null || _ItemTransitions_ToID.IsValidList(list)) && (_MyContent == null || _MyContent.IsValidList(list)); } - // CSLATODO: Replace base Item.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Item - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Item.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Item - protected override object GetIdValue() - { - return MyItemUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyItemUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -573,8 +534,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -603,31 +564,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(PreviousID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(PreviousID, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _ItemExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -635,60 +576,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ItemExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _ItemAnnotationCount; - usedByCount += _ItemDocVersionCount; - usedByCount += _ItemPartCount; - usedByCount += _ItemTransition_RangeIDCount; - usedByCount += _ItemTransition_ToIDCount; - usedByCount += _NextItemCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemUnique = 0; - protected static int ItemUnique - { get { return ++_ItemUnique; } } - private int _MyItemUnique = ItemUnique; - public int MyItemUnique // Absolutely Unique ID - Editable - { get { return _MyItemUnique; } } + protected static int ItemUnique => ++_ItemUnique; + private readonly int _MyItemUnique = ItemUnique; + // Absolutely Unique ID - Editable + public int MyItemUnique => _MyItemUnique; protected Item() {/* require use of factory methods */ AddToCache(this); @@ -697,15 +592,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Item() { _CountFinalized++; @@ -732,16 +623,6 @@ namespace VEPROMS.CSLA.Library _ItemTransitions_RangeID = null; if (_ItemTransitions_ToID != null) _ItemTransitions_ToID = null; - //if (_MyPrevious != null) - // _MyPrevious = null; - //if (_NextItems != null) - // _NextItems = null; - //if (_ItemAnnotations != null) - // _ItemAnnotations.Dispose(); - //if (_ItemDocVersions != null) - // _ItemDocVersions = null; - //if (_ItemParts != null) - // _ItemParts = null; } private void RemoveFromDictionaries() { @@ -756,8 +637,6 @@ namespace VEPROMS.CSLA.Library } public static Item New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Item"); try { return DataPortal.Create(); @@ -823,8 +702,6 @@ namespace VEPROMS.CSLA.Library } public static Item Get(int itemID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Item"); try { Item tmp = GetCachedByPrimaryKey(itemID); @@ -850,15 +727,14 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Item(dr, previous); return null; } - internal Item(SafeDataReader dr) - { - ReadData(dr); - } + internal Item(SafeDataReader dr) => ReadData(dr); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] private Item(SafeDataReader dr, Item previous) { ReadData(dr); MarkAsChild(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal Item(SafeDataReader dr, int parentID) { ReadData(dr); @@ -866,8 +742,6 @@ namespace VEPROMS.CSLA.Library } public static void Delete(int itemID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Item"); try { DataPortal.Delete(new PKCriteria(itemID)); @@ -879,12 +753,6 @@ namespace VEPROMS.CSLA.Library } public override Item Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Item"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Item"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Item"); try { BuildRefreshList(); @@ -904,13 +772,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public PKCriteria(int itemID) - { - _ItemID = itemID; - } + private readonly int _ItemID; + public int ItemID => _ItemID; + public PKCriteria(int itemID) => _ItemID = itemID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -1000,7 +864,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Item.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -1025,45 +889,53 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyContent != null) _MyContent.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyContent?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addItem"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@PreviousID", PreviousID); - cm.Parameters.AddWithValue("@ContentID", ContentID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int); - param_ItemID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ItemID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _ItemID = (int)cm.Parameters["@newItemID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addItem"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@PreviousID", PreviousID); + cm.Parameters.AddWithValue("@ContentID", ContentID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ItemID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _ItemID = (int)cm.Parameters["@newItemID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_ItemAnnotations != null) _ItemAnnotations.Update(this); - if (_ItemDocVersions != null) _ItemDocVersions.Update(this); - if (_NextItems != null) _NextItems.Update(this); - if (_ItemParts != null) _ItemParts.Update(this); - if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID.Update(this); - if (_ItemTransitions_ToID != null) _ItemTransitions_ToID.Update(this); + _ItemAnnotations?.Update(this); + _ItemDocVersions?.Update(this); + _NextItems?.Update(this); + _ItemParts?.Update(this); + _ItemTransitions_RangeID?.Update(this); + _ItemTransitions_ToID?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -1073,7 +945,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Item.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int itemID, Item myPrevious, Content myContent, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Add", 0); @@ -1090,11 +962,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int); - param_ItemID.Direction = ParameterDirection.Output; + SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_ItemID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1178,7 +1054,7 @@ namespace VEPROMS.CSLA.Library return dt; } - catch (Exception ex) + catch (Exception) { //B2025-004 //if it fails loading previously open tabs, simply treat it as if no tabs were open @@ -1189,7 +1065,7 @@ namespace VEPROMS.CSLA.Library } } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1212,47 +1088,53 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.SQLUpdate", GetHashCode()); try { - if (_MyContent != null) _MyContent.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyContent?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateItem"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@PreviousID", PreviousID); - cm.Parameters.AddWithValue("@ContentID", ContentID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateItem"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@PreviousID", PreviousID); + cm.Parameters.AddWithValue("@ContentID", ContentID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_ItemAnnotations != null) _ItemAnnotations.Update(this); - if (_ItemDocVersions != null) _ItemDocVersions.Update(this); - if (_NextItems != null) _NextItems.Update(this); - if (_ItemParts != null) _ItemParts.Update(this); - if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID.Update(this); - if (_ItemTransitions_ToID != null) _ItemTransitions_ToID.Update(this); + _ItemAnnotations?.Update(this); + _ItemDocVersions?.Update(this); + _NextItems?.Update(this); + _ItemParts?.Update(this); + _ItemTransitions_RangeID?.Update(this); + _ItemTransitions_ToID?.Update(this); } catch (Exception ex) { @@ -1263,34 +1145,43 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Item.Add(cn, ref _ItemID, _MyPrevious, _MyContent, _DTS, _UserID); - else - _LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, _ContentID, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Item.Add(cn, ref _ItemID, _MyPrevious, _MyContent, _DTS, _UserID); + else + _LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, _ContentID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_ItemAnnotations != null) _ItemAnnotations.Update(this); - if (_ItemDocVersions != null) _ItemDocVersions.Update(this); - if (_NextItems != null) _NextItems.Update(this); - if (_ItemParts != null) _ItemParts.Update(this); - if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID.Update(this); - if (_ItemTransitions_ToID != null) _ItemTransitions_ToID.Update(this); + _ItemAnnotations?.Update(this); + _ItemDocVersions?.Update(this); + _NextItems?.Update(this); + _ItemParts?.Update(this); + _ItemTransitions_RangeID?.Update(this); + _ItemTransitions_ToID?.Update(this); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item item) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Item.Remove(cn, _ItemID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Item.Remove(cn, _ItemID); + } + MarkNew(); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int itemID, int? previousID, int contentID, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Update", 0); @@ -1309,8 +1200,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1324,12 +1217,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Item.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ItemID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); @@ -1354,7 +1247,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Item.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int itemID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Remove", 0); @@ -1395,16 +1288,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ItemID; + private readonly int _ItemID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int itemID) - { - _ItemID = itemID; - } + public bool Exists => _exists; + public ExistsCommand(int itemID) => _ItemID = itemID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Execute", GetHashCode()); @@ -1412,7 +1299,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1434,7 +1321,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ItemExtension _ItemExtension = new ItemExtension(); + readonly ItemExtension _ItemExtension = new ItemExtension(); [Serializable()] partial class ItemExtension : extensionBase { @@ -1443,14 +1330,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1479,57 +1360,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Item) + if (destType == typeof(string) && value is Item myitem) { // Return the ToString value - return ((Item)value).ToString(); + return myitem.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Item -// { -// partial class ItemExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotation.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotation.cs index 1f4f60ff..24c8267f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotation.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotation.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _AnnotationID; [System.ComponentModel.DataObjectField(true, true)] public int AnnotationID @@ -224,19 +218,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemAnnotation - protected override object GetIdValue() - { - return MyItemAnnotationUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ItemAnnotation.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemAnnotation - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyItemAnnotationUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -251,18 +233,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyAnnotationType == null ? false : _MyAnnotationType.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyAnnotationType != null && _MyAnnotationType.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyAnnotationType == null ? true : _MyAnnotationType.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyAnnotationType == null || _MyAnnotationType.IsValidList(list)); } #endregion #region ValidationRules @@ -292,8 +271,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -324,80 +303,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AnnotationID, ""); - //AuthorizationRules.AllowRead(TypeID, ""); - //AuthorizationRules.AllowWrite(TypeID, ""); - //AuthorizationRules.AllowRead(RtfText, ""); - //AuthorizationRules.AllowWrite(RtfText, ""); - //AuthorizationRules.AllowRead(SearchText, ""); - //AuthorizationRules.AllowWrite(SearchText, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemAnnotationUnique = 0; - private static int ItemAnnotationUnique - { get { return ++_ItemAnnotationUnique; } } - private int _MyItemAnnotationUnique = ItemAnnotationUnique; - public int MyItemAnnotationUnique // Absolutely Unique ID - Editable FK - { get { return _MyItemAnnotationUnique; } } - internal static ItemAnnotation New(AnnotationType myAnnotationType) - { - return new ItemAnnotation(myAnnotationType); - } - internal static ItemAnnotation Get(SafeDataReader dr) - { - return new ItemAnnotation(dr); - } + private static int ItemAnnotationUnique => ++_ItemAnnotationUnique; + private readonly int _MyItemAnnotationUnique = ItemAnnotationUnique; + // Absolutely Unique ID - Editable FK + public int MyItemAnnotationUnique => _MyItemAnnotationUnique; + internal static ItemAnnotation New(AnnotationType myAnnotationType) => new ItemAnnotation(myAnnotationType); + internal static ItemAnnotation Get(SafeDataReader dr) => new ItemAnnotation(dr); public ItemAnnotation() { MarkAsChild(); @@ -425,15 +346,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemAnnotation() { _CountFinalized++; @@ -474,33 +391,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Item myItem) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Annotation.Add(cn, ref _AnnotationID, myItem, _MyAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Annotation.Add(cn, ref _AnnotationID, myItem, _MyAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Item myItem) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Annotation.Update(cn, ref _AnnotationID, myItem.ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Annotation.Update(cn, ref _AnnotationID, myItem.ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item myItem) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Annotation.Remove(cn, _AnnotationID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Annotation.Remove(cn, _AnnotationID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ItemAnnotationExtension _ItemAnnotationExtension = new ItemAnnotationExtension(); + readonly ItemAnnotationExtension _ItemAnnotationExtension = new ItemAnnotationExtension(); [Serializable()] partial class ItemAnnotationExtension : extensionBase { @@ -509,14 +439,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -545,57 +469,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemAnnotation) + if (destType == typeof(string) && value is ItemAnnotation annotation) { // Return the ToString value - return ((ItemAnnotation)value).ToString(); + return annotation.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemAnnotationExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ItemAnnotation -// { -// partial class ItemAnnotationExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotations.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotations.cs index 7dc96795..8157186f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotations.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAnnotations.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ItemAnnotation this[Annotation myAnnotation] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ItemAnnotation this[Annotation myAnnotation] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ItemAnnotation GetItem(Annotation myAnnotation) + public new System.Collections.Generic.IList Items => base.Items; + public ItemAnnotation GetItem(Annotation myAnnotation) { foreach (ItemAnnotation annotation in this) if (annotation.AnnotationID == myAnnotation.AnnotationID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ItemAnnotation Add(AnnotationType myAnnotationType) // One to Many { ItemAnnotation annotation = ItemAnnotation.New(myAnnotationType); - this.Add(annotation); + Add(annotation); return annotation; } public void Remove(Annotation myAnnotation) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ItemAnnotation child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ItemAnnotation child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ItemAnnotations New() - { - return new ItemAnnotations(); - } - internal static ItemAnnotations Get(SafeDataReader dr) - { - return new ItemAnnotations(dr); - } - public static ItemAnnotations GetByItemID(int itemID) + #endregion + #region Factory Methods + internal static ItemAnnotations New() => new ItemAnnotations(); + internal static ItemAnnotations Get(SafeDataReader dr) => new ItemAnnotations(dr); + public static ItemAnnotations GetByItemID(int itemID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ItemAnnotations.GetByItemID", ex); } } - private ItemAnnotations() - { - MarkAsChild(); - } - internal ItemAnnotations(SafeDataReader dr) + private ItemAnnotations() => MarkAsChild(); + internal ItemAnnotations(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ItemAnnotations() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ItemAnnotations() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ItemAnnotation.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ItemAnnotation.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAnnotations.DataPortal_FetchItemID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ItemAnnotation(dr)); + while (dr.Read()) Add(new ItemAnnotation(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAnnotations.DataPortal_FetchItemID", ex); throw new DbCslaException("ItemAnnotations.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Item item) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemAnnotationsPropertyDescriptor pd = new ItemAnnotationsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemAnnotationsPropertyDescriptor : vlnListPropertyDescriptor { - private ItemAnnotation Item { get { return (ItemAnnotation)_Item; } } public ItemAnnotationsPropertyDescriptor(ItemAnnotations collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemAnnotations) + if (destType == typeof(string) && value is ItemAnnotations annotations) { // Return department and department role separated by comma. - return ((ItemAnnotations)value).Items.Count.ToString() + " Annotations"; + return $"{annotations.Items.Count} Annotations"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAudit.cs index f3ee51e3..ddd79eab 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshItemAudits.Add(this); } - private void ClearRefreshList() - { - _RefreshItemAudits = new List(); - } + private void ClearRefreshList() => _RefreshItemAudits = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ItemAudit itemAudit) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(itemAudit)) _CacheList.Remove(itemAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -218,40 +209,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base ItemAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check ItemAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemAudit - protected override object GetIdValue() - { - return MyItemAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyItemAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -279,8 +244,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -299,35 +264,11 @@ namespace VEPROMS.CSLA.Library _ItemAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(PreviousID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(PreviousID, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); _ItemAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -335,42 +276,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ItemAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemAuditUnique = 0; - protected static int ItemAuditUnique - { get { return ++_ItemAuditUnique; } } - private int _MyItemAuditUnique = ItemAuditUnique; - public int MyItemAuditUnique // Absolutely Unique ID - Editable - { get { return _MyItemAuditUnique; } } + protected static int ItemAuditUnique => ++_ItemAuditUnique; + private readonly int _MyItemAuditUnique = ItemAuditUnique; + // Absolutely Unique ID - Editable + public int MyItemAuditUnique => _MyItemAuditUnique; protected ItemAudit() {/* require use of factory methods */ AddToCache(this); @@ -379,15 +292,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemAudit() { _CountFinalized++; @@ -412,8 +321,6 @@ namespace VEPROMS.CSLA.Library } public static ItemAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ItemAudit"); try { return DataPortal.Create(); @@ -462,8 +369,6 @@ namespace VEPROMS.CSLA.Library } public static ItemAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ItemAudit"); try { ItemAudit tmp = GetCachedByPrimaryKey(auditID); @@ -489,14 +394,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new ItemAudit(dr); return null; } - internal ItemAudit(SafeDataReader dr) - { - ReadData(dr); - } + internal ItemAudit(SafeDataReader dr) => ReadData(dr); public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ItemAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -508,12 +408,6 @@ namespace VEPROMS.CSLA.Library } public override ItemAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ItemAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ItemAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ItemAudit"); try { BuildRefreshList(); @@ -533,13 +427,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -608,7 +498,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ItemAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -633,34 +523,40 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addItemAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@PreviousID", _PreviousID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addItemAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@PreviousID", _PreviousID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.SQLInsert", GetHashCode()); @@ -672,7 +568,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ItemAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int itemID, int? previousID, int contentID, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.Add", 0); @@ -691,8 +587,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -707,7 +605,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ItemAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -730,35 +628,39 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateItemAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@PreviousID", _PreviousID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateItemAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@PreviousID", _PreviousID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -771,18 +673,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - ItemAudit.Add(cn, ref _AuditID, _ItemID, _PreviousID, _ContentID, _DTS, _UserID, _DeleteStatus); - else - ItemAudit.Update(cn, ref _AuditID, _ItemID, _PreviousID, _ContentID, _DTS, _UserID, _DeleteStatus); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + ItemAudit.Add(cn, ref _AuditID, _ItemID, _PreviousID, _ContentID, _DTS, _UserID, _DeleteStatus); + else + ItemAudit.Update(cn, ref _AuditID, _ItemID, _PreviousID, _ContentID, _DTS, _UserID, _DeleteStatus); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int itemID, int? previousID, int contentID, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.Update", 0); @@ -814,12 +720,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ItemAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.DataPortal_Delete", GetHashCode()); @@ -844,7 +750,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ItemAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAudit.Remove", 0); @@ -870,7 +776,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ItemAuditExtension _ItemAuditExtension = new ItemAuditExtension(); + readonly ItemAuditExtension _ItemAuditExtension = new ItemAuditExtension(); [Serializable()] partial class ItemAuditExtension : extensionBase { @@ -907,49 +813,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemAudit) + if (destType == typeof(string) && value is ItemAudit audit) { // Return the ToString value - return ((ItemAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ItemAudit -// { -// partial class ItemAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfo.cs index 06e15c5d..13da170d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ItemAuditInfo : ReadOnlyBase, IDisposable { public event ItemAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ItemAuditInfo itemAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(itemAuditInfo)) _CacheList.Remove(itemAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ItemAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -153,32 +137,19 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base ItemAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ItemAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemAuditInfo - protected override object GetIdValue() - { - return MyItemAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyItemAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ItemAuditInfoUnique = 0; - private static int ItemAuditInfoUnique - { get { return ++_ItemAuditInfoUnique; } } - private int _MyItemAuditInfoUnique = ItemAuditInfoUnique; - public int MyItemAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyItemAuditInfoUnique; } } + private static int ItemAuditInfoUnique => ++_ItemAuditInfoUnique; + private readonly int _MyItemAuditInfoUnique = ItemAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyItemAuditInfoUnique => _MyItemAuditInfoUnique; protected ItemAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -187,15 +158,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemAuditInfo() { _CountFinalized++; @@ -212,10 +179,7 @@ namespace VEPROMS.CSLA.Library if (listItemAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual ItemAudit Get() - { - return _Editable = ItemAudit.Get(_AuditID); - } + public virtual ItemAudit Get() => _Editable = ItemAudit.Get(_AuditID); public static void Refresh(ItemAudit tmp) { string key = tmp.AuditID.ToString(); @@ -237,8 +201,6 @@ namespace VEPROMS.CSLA.Library } public static ItemAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ItemAudit"); try { ItemAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -277,13 +239,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -344,7 +302,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ItemAuditInfoExtension _ItemAuditInfoExtension = new ItemAuditInfoExtension(); + readonly ItemAuditInfoExtension _ItemAuditInfoExtension = new ItemAuditInfoExtension(); [Serializable()] partial class ItemAuditInfoExtension : extensionBase { } [Serializable()] @@ -360,10 +318,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemAuditInfo) + if (destType == typeof(string) && value is ItemAuditInfo info) { // Return the ToString value - return ((ItemAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfoList.cs index 8df4b727..c1b83173 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ItemAuditInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~ItemAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ItemAuditInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ItemAuditInfoList.Get", ex); } } - /// - /// Reset the list of all ItemAuditInfo. - /// - public static void Reset() - { - _ItemAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ItemAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ItemAuditInfoList.Get", ex); - // } - //} - private ItemAuditInfoList() + /// + /// Reset the list of all ItemAuditInfo. + /// + public static void Reset() => _ItemAuditInfoList = null; + private ItemAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ItemAuditInfo(dr)); + while (dr.Read()) Add(new ItemAuditInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ItemAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemAuditInfoListPropertyDescriptor pd = new ItemAuditInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ItemAuditInfo Item { get { return (ItemAuditInfo)_Item; } } public ItemAuditInfoListPropertyDescriptor(ItemAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemAuditInfoList) + if (destType == typeof(string) && value is ItemAuditInfoList list) { // Return department and department role separated by comma. - return ((ItemAuditInfoList)value).Items.Count.ToString() + " ItemAudits"; + return $"{list.Items.Count} ItemAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersion.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersion.cs index 50d8abd8..671e54ee 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersion.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersion.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -329,19 +323,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemDocVersion - protected override object GetIdValue() - { - return MyItemDocVersionUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ItemDocVersion.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemDocVersion - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyItemDocVersionUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -356,18 +338,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyFolder != null && _MyFolder.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyFolder == null || _MyFolder.IsValidList(list)); } #endregion #region ValidationRules @@ -399,7 +378,7 @@ namespace VEPROMS.CSLA.Library { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -432,84 +411,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowWrite(FolderID, ""); - //AuthorizationRules.AllowRead(VersionType, ""); - //AuthorizationRules.AllowWrite(VersionType, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowRead(FormatID, ""); - //AuthorizationRules.AllowWrite(FormatID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemDocVersionUnique = 0; - private static int ItemDocVersionUnique - { get { return ++_ItemDocVersionUnique; } } - private int _MyItemDocVersionUnique = ItemDocVersionUnique; - public int MyItemDocVersionUnique // Absolutely Unique ID - Editable FK - { get { return _MyItemDocVersionUnique; } } - internal static ItemDocVersion New(Folder myFolder, string name) - { - return new ItemDocVersion(myFolder, name); - } - internal static ItemDocVersion Get(SafeDataReader dr) - { - return new ItemDocVersion(dr); - } + private static int ItemDocVersionUnique => ++_ItemDocVersionUnique; + private readonly int _MyItemDocVersionUnique = ItemDocVersionUnique; + // Absolutely Unique ID - Editable FK + public int MyItemDocVersionUnique => _MyItemDocVersionUnique; + internal static ItemDocVersion New(Folder myFolder, string name) => new ItemDocVersion(myFolder, name); + internal static ItemDocVersion Get(SafeDataReader dr) => new ItemDocVersion(dr); public ItemDocVersion() { MarkAsChild(); @@ -540,15 +457,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemDocVersion() { _CountFinalized++; @@ -598,32 +511,45 @@ namespace VEPROMS.CSLA.Library { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, myItem, _MyFormat, _Config, _DTS, _UserID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, myItem, _MyFormat, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Item myItem) { // if we're not dirty then don't update the database if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, myItem != null ? (int?)myItem.ItemID : (int?)null, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, myItem != null ? (int?)myItem.ItemID : (int?)null, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item myItem) { // if we're not dirty then don't update the database if (!this.IsDirty) return; // if we're new then don't update the database if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - DocVersion.Remove(cn, _VersionID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + DocVersion.Remove(cn, _VersionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ItemDocVersionExtension _ItemDocVersionExtension = new ItemDocVersionExtension(); + readonly ItemDocVersionExtension _ItemDocVersionExtension = new ItemDocVersionExtension(); [Serializable()] partial class ItemDocVersionExtension : extensionBase { @@ -632,18 +558,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultVersionType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultVersionType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -672,61 +589,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemDocVersion) + if (destType == typeof(string) && value is ItemDocVersion version) { // Return the ToString value - return ((ItemDocVersion)value).ToString(); + return version.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemDocVersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ItemDocVersion -// { -// partial class ItemDocVersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultVersionType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersions.cs index 986203ed..14e3455b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemDocVersions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ItemDocVersion this[DocVersion myDocVersion] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ItemDocVersion this[DocVersion myDocVersion] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ItemDocVersion GetItem(DocVersion myDocVersion) + public new System.Collections.Generic.IList Items => base.Items; + public ItemDocVersion GetItem(DocVersion myDocVersion) { foreach (ItemDocVersion docVersion in this) if (docVersion.VersionID == myDocVersion.VersionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ItemDocVersion Add(Folder myFolder, string name) // One to Many { ItemDocVersion docVersion = ItemDocVersion.New(myFolder, name); - this.Add(docVersion); + Add(docVersion); return docVersion; } public void Remove(DocVersion myDocVersion) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ItemDocVersion child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ItemDocVersion child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ItemDocVersions New() - { - return new ItemDocVersions(); - } - internal static ItemDocVersions Get(SafeDataReader dr) - { - return new ItemDocVersions(dr); - } - public static ItemDocVersions GetByItemID(int itemID) + #endregion + #region Factory Methods + internal static ItemDocVersions New() => new ItemDocVersions(); + internal static ItemDocVersions Get(SafeDataReader dr) => new ItemDocVersions(dr); + public static ItemDocVersions GetByItemID(int itemID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ItemDocVersions.GetByItemID", ex); } } - private ItemDocVersions() - { - MarkAsChild(); - } - internal ItemDocVersions(SafeDataReader dr) + private ItemDocVersions() => MarkAsChild(); + internal ItemDocVersions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ItemDocVersions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ItemDocVersions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ItemDocVersion.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ItemDocVersion.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemDocVersions.DataPortal_FetchItemID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ItemDocVersion(dr)); + while (dr.Read()) Add(new ItemDocVersion(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemDocVersions.DataPortal_FetchItemID", ex); throw new DbCslaException("ItemDocVersions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Item item) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemDocVersionsPropertyDescriptor pd = new ItemDocVersionsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemDocVersionsPropertyDescriptor : vlnListPropertyDescriptor { - private ItemDocVersion Item { get { return (ItemDocVersion)_Item; } } public ItemDocVersionsPropertyDescriptor(ItemDocVersions collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemDocVersions) + if (destType == typeof(string) && value is ItemDocVersions versions) { // Return department and department role separated by comma. - return ((ItemDocVersions)value).Items.Count.ToString() + " DocVersions"; + return $"{versions.Items.Count} DocVersions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfo.cs index ba31fad0..4122d20b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfo.cs @@ -13,11 +13,8 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; -using Volian.Base.Library; namespace VEPROMS.CSLA.Library { public delegate void ItemInfoEvent(object sender); @@ -29,27 +26,17 @@ namespace VEPROMS.CSLA.Library public partial class ItemInfo : ReadOnlyBase, IDisposable { public event ItemInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ItemInfo itemInfo) { if (!_CacheList.Contains(itemInfo)) - _CacheList.Add(itemInfo); // In AddToCache - //try - //{ - // _CacheList.Add(itemInfo); // In AddToCache - //} - //catch (Exception ex) - //{ - // _MyLog.ErrorFormat("ItemInfo {0}.{1} already exists in the cache", itemInfo.ItemID, itemInfo.MyItemInfoUnique); - //} + _CacheList.Add(itemInfo); } protected static void RemoveFromCache(ItemInfo itemInfo) { @@ -84,10 +71,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Item _Editable; private IVEHasBrokenRules HasBrokenRules { @@ -259,10 +243,7 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class PreviousIDCriteria { - public PreviousIDCriteria(int? previousID) - { - _PreviousID = previousID; - } + public PreviousIDCriteria(int? previousID) => _PreviousID = previousID; private int? _PreviousID; public int? PreviousID { @@ -469,24 +450,12 @@ namespace VEPROMS.CSLA.Library foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()]) tmp._ItemTransition_ToIDCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base ItemInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ItemInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemInfo - protected override object GetIdValue() - { - return MyItemInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyItemInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ItemInfoUnique = 0; @@ -500,9 +469,9 @@ namespace VEPROMS.CSLA.Library return ui; } } - private int _MyItemInfoUnique = ItemInfoUnique; - public int MyItemInfoUnique // Absolutely Unique ID - Info - { get { return _MyItemInfoUnique; } } + private readonly int _MyItemInfoUnique = ItemInfoUnique; + // Absolutely Unique ID - Info + public int MyItemInfoUnique => _MyItemInfoUnique; protected ItemInfo() {/* require use of factory methods */ //AddToCache(this); @@ -511,15 +480,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemInfo() { _CountFinalized++; @@ -540,21 +505,8 @@ namespace VEPROMS.CSLA.Library _MyContent = null; if (_MyPrevious != null) _MyPrevious = null; - //if (_ActiveFormat != null) - // _ActiveFormat = null; - //if (_ActiveParent != null) - // _ActiveParent = null; - //if (_ActiveSection != null) - // _ActiveSection = null; - //if (_MyDocVersion != null) - // _MyDocVersion = null; - //if (_ParentNoteOrCaution != null) - // _ParentNoteOrCaution = null; - } - public virtual Item Get() - { - return _Editable = Item.Get(_ItemID); } + public virtual Item Get() => _Editable = Item.Get(_ItemID); public static void Refresh(Item tmp) { string key = tmp.ItemID.ToString(); @@ -567,18 +519,17 @@ namespace VEPROMS.CSLA.Library { if (_PreviousID != tmp.PreviousID) { - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value + MyPrevious?.RefreshNextItems(); // Update List for old value _PreviousID = tmp.PreviousID; // Update the value } _MyPrevious = null; // Reset list so that the next line gets a new list - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value - //if (_ContentID != tmp.ContentID) - //{ - if (MyContent != null) MyContent.RefreshContentItems(); // Update List for old value + MyPrevious?.RefreshNextItems(); // Update List for new value + + MyContent?.RefreshContentItems(); // Update List for old value _ContentID = tmp.ContentID; // Update the value - //} + _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentItems(); // Update List for new value + MyContent?.RefreshContentItems(); // Update List for new value _DTS = tmp.DTS; _UserID = tmp.UserID; _ItemInfoExtension.Refresh(this); @@ -596,11 +547,11 @@ namespace VEPROMS.CSLA.Library { if (_PreviousID != tmp.PreviousID) { - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value + MyPrevious?.RefreshNextItems(); // Update List for old value _PreviousID = tmp.PreviousID; // Update the value } _MyPrevious = null; // Reset list so that the next line gets a new list - if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value + MyPrevious?.RefreshNextItems(); // Update List for new value _DTS = tmp.DTS; _UserID = tmp.UserID; _ItemInfoExtension.Refresh(this); @@ -675,13 +626,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ItemID; - public int ItemID - { get { return _ItemID; } } - public PKCriteria(int itemID) - { - _ItemID = itemID; - } + private readonly int _ItemID; + public int ItemID => _ItemID; + public PKCriteria(int itemID) => _ItemID = itemID; } protected void ReadData(SafeDataReader dr) { @@ -746,7 +693,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ItemInfoExtension _ItemInfoExtension = new ItemInfoExtension(); + readonly ItemInfoExtension _ItemInfoExtension = new ItemInfoExtension(); [Serializable()] partial class ItemInfoExtension : extensionBase { } [Serializable()] @@ -762,10 +709,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemInfo) + if (destType == typeof(string) && value is ItemInfo info) { // Return the ToString value - return ((ItemInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfoList.cs index 410bdce1..18909b15 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -30,8 +28,7 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - internal new IList Items - { get { return base.Items; } } + internal new IList Items => base.Items; public void AddEvents() { foreach (ItemInfo tmp in this) @@ -48,14 +45,13 @@ namespace VEPROMS.CSLA.Library } void tmp_Deleted(object sender) { - ItemInfo ii = sender as ItemInfo; - if (ii != null) + if (sender is ItemInfo ii) { RefreshingList = true; IsReadOnly = false; Remove(ii); IsReadOnly = true; - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, 0)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, 0)); RefreshingList = false; } } @@ -75,7 +71,7 @@ namespace VEPROMS.CSLA.Library if (SourceOfList != "Search" && (sender as ItemInfo).MyPrevious != null && i > 0 && base[i - 1].ItemID != (sender as ItemInfo).MyPrevious.ItemID) Items.Insert(i, (sender as ItemInfo).MyPrevious); IsReadOnly = true; - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); RefreshingList = false; break; } @@ -87,27 +83,15 @@ namespace VEPROMS.CSLA.Library get { return _SourceOfList; } set { _SourceOfList = value; } } - //private void ShowList(string txt) - //{ - // Console.WriteLine("\r\n{0} - {1} - {2}: i, base[i].Ordinal, base[i].ItemID, base[i].DisplayText", txt, Count, SourceOfList); - // for (int i = 0; i < Count; i++) - // { - // Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}", i, base[i].Ordinal, base[i].ItemID, base[i].DisplayText, base[i].MyItemInfoUnique, base[i].Disposed); - // } - //} 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 static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemInfoList() { _CountFinalized++; @@ -149,22 +133,7 @@ namespace VEPROMS.CSLA.Library /// /// Reset the list of all ItemInfo. /// - public static void Reset() - { - _ItemInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ItemInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ItemInfoList.Get", ex); - // } - //} + public static void Reset() => _ItemInfoList = null; public static ItemInfoList GetNext(int? previousID) { try @@ -199,7 +168,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -213,7 +182,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ItemInfo(dr)); + while (dr.Read()) Add(new ItemInfo(dr)); IsReadOnly = true; } } @@ -224,15 +193,12 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ItemInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class PreviousIDCriteria { - public PreviousIDCriteria(int? previousID) - { - _PreviousID = previousID; - } + public PreviousIDCriteria(int? previousID) => _PreviousID = previousID; private int? _PreviousID; public int? PreviousID { @@ -242,7 +208,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(PreviousIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfoList.DataPortal_FetchPreviousID", GetHashCode()); try { @@ -257,7 +223,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ItemInfo(dr)); + while (dr.Read()) Add(new ItemInfo(dr)); IsReadOnly = true; } } @@ -268,15 +234,12 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemInfoList.DataPortal_FetchPreviousID", ex); throw new DbCslaException("ItemInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } + public ContentIDCriteria(int contentID) => _ContentID = contentID; private int _ContentID; public int ContentID { @@ -286,7 +249,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfoList.DataPortal_FetchContentID", GetHashCode()); try { @@ -301,7 +264,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ItemInfo(dr)); + while (dr.Read()) Add(new ItemInfo(dr)); IsReadOnly = true; } } @@ -312,38 +275,27 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemInfoList.DataPortal_FetchContentID", ex); throw new DbCslaException("ItemInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #endregion #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; /// /// Called to get the properties of this type. Returns properties with certain /// attributes. this restriction is not implemented here. /// /// /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); /// /// Called to get the properties of this type. /// @@ -353,7 +305,7 @@ namespace VEPROMS.CSLA.Library // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemInfoListPropertyDescriptor pd = new ItemInfoListPropertyDescriptor(this, i); @@ -370,7 +322,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ItemInfo Item { get { return (ItemInfo)_Item; } } public ItemInfoListPropertyDescriptor(ItemInfoList collection, int index) : base(collection, index) {; } } #endregion @@ -379,10 +330,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemInfoList) + if (destType == typeof(string) && value is ItemInfoList list) { // Return department and department role separated by comma. - return ((ItemInfoList)value).Items.Count.ToString() + " Items"; + return $"{list.Items.Count} Items"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemPart.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemPart.cs index b8c4549e..f1efc382 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemPart.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemPart.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -180,35 +174,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemPart - protected override object GetIdValue() - { - return MyItemPartUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ItemPart.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemPart - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyItemPartUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -236,8 +208,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -249,73 +221,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(FromType, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemPartUnique = 0; - private static int ItemPartUnique - { get { return ++_ItemPartUnique; } } - private int _MyItemPartUnique = ItemPartUnique; - public int MyItemPartUnique // Absolutely Unique ID - Editable FK - { get { return _MyItemPartUnique; } } - internal static ItemPart New(Content myContent, int fromType) - { - return new ItemPart(myContent, fromType); - } - internal static ItemPart Get(SafeDataReader dr) - { - return new ItemPart(dr); - } + private static int ItemPartUnique => ++_ItemPartUnique; + private readonly int _MyItemPartUnique = ItemPartUnique; + // Absolutely Unique ID - Editable FK + public int MyItemPartUnique => _MyItemPartUnique; + internal static ItemPart New(Content myContent, int fromType) => new ItemPart(myContent, fromType); + internal static ItemPart Get(SafeDataReader dr) => new ItemPart(dr); public ItemPart() { MarkAsChild(); @@ -343,15 +264,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemPart() { _CountFinalized++; @@ -392,33 +309,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Item myItem) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Part.Add(cn, _MyContent, _FromType, myItem, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Part.Add(cn, _MyContent, _FromType, myItem, _DTS, _UserID); + } + MarkOld(); } internal void Update(Item myItem) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Part.Update(cn, _ContentID, _FromType, myItem.ItemID, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Part.Update(cn, _ContentID, _FromType, myItem.ItemID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item myItem) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Part.Remove(cn, _ContentID, _FromType); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Part.Remove(cn, _ContentID, _FromType); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ItemPartExtension _ItemPartExtension = new ItemPartExtension(); + readonly ItemPartExtension _ItemPartExtension = new ItemPartExtension(); [Serializable()] partial class ItemPartExtension : extensionBase { @@ -427,14 +357,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -463,57 +387,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemPart) + if (destType == typeof(string) && value is ItemPart part) { // Return the ToString value - return ((ItemPart)value).ToString(); + return part.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemPartExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ItemPart -// { -// partial class ItemPartExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemParts.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemParts.cs index dcee9ee1..0b7cec7c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemParts.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemParts.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ItemPart this[Content myContent, int fromType] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ItemPart this[Content myContent, int fromType] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ItemPart GetItem(Content myContent, int fromType) + public new System.Collections.Generic.IList Items => base.Items; + public ItemPart GetItem(Content myContent, int fromType) { foreach (ItemPart part in this) if (part.ContentID == myContent.ContentID && part.FromType == fromType) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ItemPart Add(Content myContent, int fromType) // One to Many { ItemPart part = ItemPart.New(myContent, fromType); - this.Add(part); + Add(part); return part; } public void Remove(Content myContent, int fromType) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ItemPart child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ItemPart child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ItemParts New() - { - return new ItemParts(); - } - internal static ItemParts Get(SafeDataReader dr) - { - return new ItemParts(dr); - } - public static ItemParts GetByItemID(int itemID) + #endregion + #region Factory Methods + internal static ItemParts New() => new ItemParts(); + internal static ItemParts Get(SafeDataReader dr) => new ItemParts(dr); + public static ItemParts GetByItemID(int itemID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ItemParts.GetByItemID", ex); } } - private ItemParts() - { - MarkAsChild(); - } - internal ItemParts(SafeDataReader dr) + private ItemParts() => MarkAsChild(); + internal ItemParts(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ItemParts() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ItemParts() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ItemPart.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ItemPart.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemParts.DataPortal_FetchItemID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ItemPart(dr)); + while (dr.Read()) Add(new ItemPart(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemParts.DataPortal_FetchItemID", ex); throw new DbCslaException("ItemParts.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Item item) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemPartsPropertyDescriptor pd = new ItemPartsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemPartsPropertyDescriptor : vlnListPropertyDescriptor { - private ItemPart Item { get { return (ItemPart)_Item; } } public ItemPartsPropertyDescriptor(ItemParts collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemParts) + if (destType == typeof(string) && value is ItemParts parts) { // Return department and department role separated by comma. - return ((ItemParts)value).Items.Count.ToString() + " Parts"; + return $"{parts.Items.Count} Parts"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_RangeID.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_RangeID.cs index f40f2721..0130bfef 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_RangeID.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_RangeID.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -295,15 +289,6 @@ namespace VEPROMS.CSLA.Library { return MyItemTransition_RangeIDUnique; // Absolutely Unique ID } - // CSLATODO: Replace base ItemTransition_RangeID.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemTransition_RangeID - //public override string ToString() - //{ - // return base.ToString(); - //} public override bool IsDirty { get @@ -318,18 +303,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)); } #endregion #region ValidationRules @@ -359,8 +341,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -385,82 +367,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(TransitionID, ""); - //AuthorizationRules.AllowRead(FromID, ""); - //AuthorizationRules.AllowWrite(FromID, ""); - //AuthorizationRules.AllowRead(ToID, ""); - //AuthorizationRules.AllowWrite(ToID, ""); - //AuthorizationRules.AllowRead(IsRange, ""); - //AuthorizationRules.AllowWrite(IsRange, ""); - //AuthorizationRules.AllowRead(TranType, ""); - //AuthorizationRules.AllowWrite(TranType, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemTransition_RangeIDUnique = 0; - private static int ItemTransition_RangeIDUnique - { get { return ++_ItemTransition_RangeIDUnique; } } - private int _MyItemTransition_RangeIDUnique = ItemTransition_RangeIDUnique; - public int MyItemTransition_RangeIDUnique // Absolutely Unique ID - Editable FK - { get { return _MyItemTransition_RangeIDUnique; } } - internal static ItemTransition_RangeID New(Content myContent, Item myItemToID) - { - return new ItemTransition_RangeID(myContent, myItemToID); - } - internal static ItemTransition_RangeID Get(SafeDataReader dr) - { - return new ItemTransition_RangeID(dr); - } + private static int ItemTransition_RangeIDUnique => ++_ItemTransition_RangeIDUnique; + private readonly int _MyItemTransition_RangeIDUnique = ItemTransition_RangeIDUnique; + // Absolutely Unique ID - Editable FK + public int MyItemTransition_RangeIDUnique => _MyItemTransition_RangeIDUnique; + internal static ItemTransition_RangeID New(Content myContent, Item myItemToID) => new ItemTransition_RangeID(myContent, myItemToID); + internal static ItemTransition_RangeID Get(SafeDataReader dr) => new ItemTransition_RangeID(dr); public ItemTransition_RangeID() { MarkAsChild(); @@ -493,15 +415,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemTransition_RangeID() { _CountFinalized++; @@ -546,33 +464,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Item myItemRangeID) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, _MyItemToID, myItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, _MyItemToID, myItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Item myItemRangeID) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, _ToID, myItemRangeID.ItemID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, _ToID, myItemRangeID.ItemID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item myItemRangeID) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Transition.Remove(cn, _TransitionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Transition.Remove(cn, _TransitionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ItemTransition_RangeIDExtension _ItemTransition_RangeIDExtension = new ItemTransition_RangeIDExtension(); + readonly ItemTransition_RangeIDExtension _ItemTransition_RangeIDExtension = new ItemTransition_RangeIDExtension(); [Serializable()] partial class ItemTransition_RangeIDExtension : extensionBase { @@ -581,22 +512,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultIsRange - { - get { return 0; } - } - public virtual int DefaultTranType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultIsRange => 0; + public virtual int DefaultTranType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -625,65 +544,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemTransition_RangeID) + if (destType == typeof(string) && value is ItemTransition_RangeID iD) { // Return the ToString value - return ((ItemTransition_RangeID)value).ToString(); + return iD.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemTransition_RangeIDExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ItemTransition_RangeID -// { -// partial class ItemTransition_RangeIDExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultIsRange -// { -// get { return 0; } -// } -// public virtual int DefaultTranType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_ToID.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_ToID.cs index 7e3b9a27..86a5e48f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_ToID.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransition_ToID.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -288,19 +282,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ItemTransition_ToID - protected override object GetIdValue() - { - return MyItemTransition_ToIDUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ItemTransition_ToID.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ItemTransition_ToID - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyItemTransition_ToIDUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -315,18 +297,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)); } #endregion #region ValidationRules @@ -356,8 +335,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -382,82 +361,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(TransitionID, ""); - //AuthorizationRules.AllowRead(FromID, ""); - //AuthorizationRules.AllowWrite(FromID, ""); - //AuthorizationRules.AllowRead(RangeID, ""); - //AuthorizationRules.AllowWrite(RangeID, ""); - //AuthorizationRules.AllowRead(IsRange, ""); - //AuthorizationRules.AllowWrite(IsRange, ""); - //AuthorizationRules.AllowRead(TranType, ""); - //AuthorizationRules.AllowWrite(TranType, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ItemTransition_ToIDUnique = 0; - private static int ItemTransition_ToIDUnique - { get { return ++_ItemTransition_ToIDUnique; } } - private int _MyItemTransition_ToIDUnique = ItemTransition_ToIDUnique; - public int MyItemTransition_ToIDUnique // Absolutely Unique ID - Editable FK - { get { return _MyItemTransition_ToIDUnique; } } - internal static ItemTransition_ToID New(Content myContent, Item myItemRangeID) - { - return new ItemTransition_ToID(myContent, myItemRangeID); - } - internal static ItemTransition_ToID Get(SafeDataReader dr) - { - return new ItemTransition_ToID(dr); - } + private static int ItemTransition_ToIDUnique => ++_ItemTransition_ToIDUnique; + private readonly int _MyItemTransition_ToIDUnique = ItemTransition_ToIDUnique; + // Absolutely Unique ID - Editable FK + public int MyItemTransition_ToIDUnique => _MyItemTransition_ToIDUnique; + internal static ItemTransition_ToID New(Content myContent, Item myItemRangeID) => new ItemTransition_ToID(myContent, myItemRangeID); + internal static ItemTransition_ToID Get(SafeDataReader dr) => new ItemTransition_ToID(dr); public ItemTransition_ToID() { MarkAsChild(); @@ -490,15 +409,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ItemTransition_ToID() { _CountFinalized++; @@ -543,33 +458,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Item myItemToID) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, myItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, myItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(Item myItemToID) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, myItemToID.ItemID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, myItemToID.ItemID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item myItemToID) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Transition.Remove(cn, _TransitionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Transition.Remove(cn, _TransitionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ItemTransition_ToIDExtension _ItemTransition_ToIDExtension = new ItemTransition_ToIDExtension(); + readonly ItemTransition_ToIDExtension _ItemTransition_ToIDExtension = new ItemTransition_ToIDExtension(); [Serializable()] partial class ItemTransition_ToIDExtension : extensionBase { @@ -578,22 +506,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultIsRange - { - get { return 0; } - } - public virtual int DefaultTranType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultIsRange => 0; + public virtual int DefaultTranType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -622,65 +538,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemTransition_ToID) + if (destType == typeof(string) && value is ItemTransition_ToID iD) { // Return the ToString value - return ((ItemTransition_ToID)value).ToString(); + return iD.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ItemTransition_ToIDExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ItemTransition_ToID -// { -// partial class ItemTransition_ToIDExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultIsRange -// { -// get { return 0; } -// } -// public virtual int DefaultTranType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_RangeID.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_RangeID.cs index 1f2b1085..c6626754 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_RangeID.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_RangeID.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ItemTransition_RangeID this[Transition myTransition] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ItemTransition_RangeID this[Transition myTransition] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ItemTransition_RangeID GetItem(Transition myTransition) + public new System.Collections.Generic.IList Items => base.Items; + public ItemTransition_RangeID GetItem(Transition myTransition) { foreach (ItemTransition_RangeID transition in this) if (transition.TransitionID == myTransition.TransitionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public ItemTransition_RangeID Add(Content myContent, Item myItemToID) // One to Many { ItemTransition_RangeID transition = ItemTransition_RangeID.New(myContent, myItemToID); - this.Add(transition); + Add(transition); return transition; } public void Remove(Transition myTransition) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ItemTransition_RangeID child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ItemTransition_RangeID child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,7 +126,7 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } #endregion @@ -174,16 +163,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ItemTransitions_RangeID() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ItemTransitions_RangeID() { _CountFinalized++; } @@ -198,19 +183,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ItemTransition_RangeID.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ItemTransition_RangeID.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RangeIDCriteria { - public RangeIDCriteria(int rangeID) - { - _RangeID = rangeID; - } - private int _RangeID; + public RangeIDCriteria(int rangeID) => _RangeID = rangeID; + private int _RangeID; public int RangeID { get { return _RangeID; } @@ -219,7 +201,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RangeIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemTransitions_RangeID.DataPortal_FetchRangeID", GetHashCode()); try { @@ -233,7 +215,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ItemTransition_RangeID(dr)); + while (dr.Read()) Add(new ItemTransition_RangeID(dr)); } } } @@ -243,11 +225,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemTransitions_RangeID.DataPortal_FetchRangeID", ex); throw new DbCslaException("ItemTransitions_RangeID.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Item item) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +248,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemTransitions_RangeIDPropertyDescriptor pd = new ItemTransitions_RangeIDPropertyDescriptor(this, i); @@ -325,7 +296,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemTransitions_RangeIDPropertyDescriptor : vlnListPropertyDescriptor { - private ItemTransition_RangeID Item { get { return (ItemTransition_RangeID)_Item; } } public ItemTransitions_RangeIDPropertyDescriptor(ItemTransitions_RangeID collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +304,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemTransitions_RangeID) + if (destType == typeof(string) && value is ItemTransitions_RangeID iD) { // Return department and department role separated by comma. - return ((ItemTransitions_RangeID)value).Items.Count.ToString() + " Transitions_RangeID"; + return $"{iD.Items.Count} Transitions_RangeID"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_ToID.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_ToID.cs index a67a3841..12da73f2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_ToID.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ItemTransitions_ToID.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ItemTransition_ToID this[Transition myTransition] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ItemTransition_ToID this[Transition myTransition] { get { @@ -61,7 +56,7 @@ namespace VEPROMS.CSLA.Library public ItemTransition_ToID Add(Content myContent, Item myItemRangeID) // One to Many { ItemTransition_ToID transition = ItemTransition_ToID.New(myContent, myItemRangeID); - this.Add(transition); + Add(transition); return transition; } public void Remove(Transition myTransition) @@ -103,23 +98,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ItemTransition_ToID child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ItemTransition_ToID child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +129,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ItemTransitions_ToID New() - { - return new ItemTransitions_ToID(); - } - internal static ItemTransitions_ToID Get(SafeDataReader dr) - { - return new ItemTransitions_ToID(dr); - } - public static ItemTransitions_ToID GetByToID(int toID) + #endregion + #region Factory Methods + internal static ItemTransitions_ToID New() => new ItemTransitions_ToID(); + internal static ItemTransitions_ToID Get(SafeDataReader dr) => new ItemTransitions_ToID(dr); + public static ItemTransitions_ToID GetByToID(int toID) { try { @@ -161,11 +147,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ItemTransitions_ToID.GetByToID", ex); } } - private ItemTransitions_ToID() - { - MarkAsChild(); - } - internal ItemTransitions_ToID(SafeDataReader dr) + private ItemTransitions_ToID() => MarkAsChild(); + internal ItemTransitions_ToID(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +157,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ItemTransitions_ToID() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ItemTransitions_ToID() { _CountFinalized++; } @@ -198,19 +177,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ItemTransition_ToID.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ItemTransition_ToID.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ToIDCriteria { - public ToIDCriteria(int toID) - { - _ToID = toID; - } - private int _ToID; + public ToIDCriteria(int toID) => _ToID = toID; + private int _ToID; public int ToID { get { return _ToID; } @@ -219,7 +195,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ToIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemTransitions_ToID.DataPortal_FetchToID", GetHashCode()); try { @@ -233,7 +209,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ItemTransition_ToID(dr)); + while (dr.Read()) Add(new ItemTransition_ToID(dr)); } } } @@ -243,11 +219,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemTransitions_ToID.DataPortal_FetchToID", ex); throw new DbCslaException("ItemTransitions_ToID.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Item item) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +242,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ItemTransitions_ToIDPropertyDescriptor pd = new ItemTransitions_ToIDPropertyDescriptor(this, i); @@ -325,7 +290,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ItemTransitions_ToIDPropertyDescriptor : vlnListPropertyDescriptor { - private ItemTransition_ToID Item { get { return (ItemTransition_ToID)_Item; } } public ItemTransitions_ToIDPropertyDescriptor(ItemTransitions_ToID collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +298,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ItemTransitions_ToID) + if (destType == typeof(string) && value is ItemTransitions_ToID iD) { // Return department and department role separated by comma. - return ((ItemTransitions_ToID)value).Items.Count.ToString() + " Transitions_ToID"; + return $"{iD.Items.Count} Transitions_ToID"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Membership.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Membership.cs index c24a7fca..d3284c41 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Membership.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Membership.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshMemberships.Add(this); } - private void ClearRefreshList() - { - _RefreshMemberships = new List(); - } + private void ClearRefreshList() => _RefreshMemberships = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Membership membership) { @@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(membership)) _CacheList.Remove(membership); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,15 +89,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextUGID = -1; - public static int NextUGID - { - get { return _nextUGID--; } - } + public static int NextUGID => _nextUGID--; private int _UGID; [System.ComponentModel.DataObjectField(true, true)] public int UGID @@ -298,7 +289,7 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyGroup == null ? false : _MyGroup.IsDirtyList(list)) || (_MyUser == null ? false : _MyUser.IsDirtyList(list)); + return base.IsDirty || (_MyGroup != null && _MyGroup.IsDirtyList(list)) || (_MyUser != null && _MyUser.IsDirtyList(list)); } public override bool IsValid { @@ -307,28 +298,16 @@ namespace VEPROMS.CSLA.Library public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyGroup == null ? true : _MyGroup.IsValidList(list)) && (_MyUser == null ? true : _MyUser.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyGroup == null || _MyGroup.IsValidList(list)) && (_MyUser == null || _MyUser.IsValidList(list)); } - // CSLATODO: Replace base Membership.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Membership - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Membership.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Membership - protected override object GetIdValue() - { - return MyMembershipUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyMembershipUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -358,8 +337,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -431,37 +410,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(UGID, ""); - //AuthorizationRules.AllowRead(UID, ""); - //AuthorizationRules.AllowRead(GID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UID, ""); - //AuthorizationRules.AllowWrite(GID, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); _MembershipExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -469,42 +422,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _MembershipExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _MembershipUnique = 0; - protected static int MembershipUnique - { get { return ++_MembershipUnique; } } - private int _MyMembershipUnique = MembershipUnique; - public int MyMembershipUnique // Absolutely Unique ID - Editable - { get { return _MyMembershipUnique; } } + protected static int MembershipUnique => ++_MembershipUnique; + private readonly int _MyMembershipUnique = MembershipUnique; + // Absolutely Unique ID - Editable + public int MyMembershipUnique => _MyMembershipUnique; protected Membership() {/* require use of factory methods */ AddToCache(this); @@ -513,15 +438,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Membership() { _CountFinalized++; @@ -546,8 +467,6 @@ namespace VEPROMS.CSLA.Library } public static Membership New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Membership"); try { return DataPortal.Create(); @@ -619,8 +538,6 @@ namespace VEPROMS.CSLA.Library } public static Membership Get(int ugid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Membership"); try { Membership tmp = GetCachedByPrimaryKey(ugid); @@ -646,14 +563,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Membership(dr); return null; } - internal Membership(SafeDataReader dr) - { - ReadData(dr); - } + internal Membership(SafeDataReader dr) => ReadData(dr); public static void Delete(int ugid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Membership"); try { DataPortal.Delete(new PKCriteria(ugid)); @@ -665,12 +577,6 @@ namespace VEPROMS.CSLA.Library } public override Membership Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Membership"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Membership"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Membership"); try { BuildRefreshList(); @@ -690,13 +596,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _UGID; - public int UGID - { get { return _UGID; } } - public PKCriteria(int ugid) - { - _UGID = ugid; - } + private readonly int _UGID; + public int UGID => _UGID; + public PKCriteria(int ugid) => _UGID = ugid; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -769,7 +671,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Membership.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -794,41 +696,49 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyGroup != null) _MyGroup.Update(); - if (_MyUser != null) _MyUser.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyGroup?.Update(); + _MyUser?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addMembership"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@UID", UID); - cm.Parameters.AddWithValue("@GID", GID); - cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); - cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_UGID = new SqlParameter("@newUGID", SqlDbType.Int); - param_UGID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_UGID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _UGID = (int)cm.Parameters["@newUGID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addMembership"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@UID", UID); + cm.Parameters.AddWithValue("@GID", GID); + cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); + cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_UGID = new SqlParameter("@newUGID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_UGID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _UGID = (int)cm.Parameters["@newUGID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.SQLInsert", GetHashCode()); @@ -840,7 +750,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Membership.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int ugid, User myUser, Group myGroup, SmartDate startDate, SmartDate endDate, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.Add", 0); @@ -860,11 +770,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_UGID = new SqlParameter("@newUGID", SqlDbType.Int); - param_UGID.Direction = ParameterDirection.Output; + SqlParameter param_UGID = new SqlParameter("@newUGID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_UGID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -879,7 +793,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Membership.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -902,43 +816,49 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.SQLUpdate", GetHashCode()); try { - if (_MyGroup != null) _MyGroup.Update(); - if (_MyUser != null) _MyUser.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyGroup?.Update(); + _MyUser?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateMembership"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@UGID", _UGID); - cm.Parameters.AddWithValue("@UID", UID); - cm.Parameters.AddWithValue("@GID", GID); - cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); - cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateMembership"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@UGID", _UGID); + cm.Parameters.AddWithValue("@UID", UID); + cm.Parameters.AddWithValue("@GID", GID); + cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); + cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -951,18 +871,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Membership.Add(cn, ref _UGID, _MyUser, _MyGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); - else - _LastChanged = Membership.Update(cn, ref _UGID, _UID, _GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Membership.Add(cn, ref _UGID, _MyUser, _MyGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + else + _LastChanged = Membership.Update(cn, ref _UGID, _UID, _GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int ugid, int uid, int gid, SmartDate startDate, SmartDate endDate, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.Update", 0); @@ -984,8 +908,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -999,12 +925,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Membership.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_UGID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.DataPortal_Delete", GetHashCode()); @@ -1029,7 +955,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Membership.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int ugid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.Remove", 0); @@ -1070,16 +996,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _UGID; + private readonly int _UGID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int ugid) - { - _UGID = ugid; - } + public bool Exists => _exists; + public ExistsCommand(int ugid) => _UGID = ugid; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Membership.DataPortal_Execute", GetHashCode()); @@ -1087,7 +1007,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1109,7 +1029,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - MembershipExtension _MembershipExtension = new MembershipExtension(); + readonly MembershipExtension _MembershipExtension = new MembershipExtension(); [Serializable()] partial class MembershipExtension : extensionBase { @@ -1118,18 +1038,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1158,61 +1069,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Membership) + if (destType == typeof(string) && value is Membership membership) { // Return the ToString value - return ((Membership)value).ToString(); + return membership.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create MembershipExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Membership -// { -// partial class MembershipExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfo.cs index c70b7b85..da5a9e0b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class MembershipInfo : ReadOnlyBase, IDisposable { public event MembershipInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(MembershipInfo membershipInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(membershipInfo)) _CacheList.Remove(membershipInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Membership _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _UGID; [System.ComponentModel.DataObjectField(true, true)] public int UGID @@ -202,32 +186,19 @@ namespace VEPROMS.CSLA.Library return _UsrID; } } - // CSLATODO: Replace base MembershipInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current MembershipInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check MembershipInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current MembershipInfo - protected override object GetIdValue() - { - return MyMembershipInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyMembershipInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _MembershipInfoUnique = 0; - private static int MembershipInfoUnique - { get { return ++_MembershipInfoUnique; } } - private int _MyMembershipInfoUnique = MembershipInfoUnique; - public int MyMembershipInfoUnique // Absolutely Unique ID - Info - { get { return _MyMembershipInfoUnique; } } + private static int MembershipInfoUnique => ++_MembershipInfoUnique; + private readonly int _MyMembershipInfoUnique = MembershipInfoUnique; + // Absolutely Unique ID - Info + public int MyMembershipInfoUnique => _MyMembershipInfoUnique; protected MembershipInfo() {/* require use of factory methods */ AddToCache(this); @@ -236,15 +207,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~MembershipInfo() { _CountFinalized++; @@ -261,10 +228,7 @@ namespace VEPROMS.CSLA.Library if (listMembershipInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(UGID.ToString()); // remove the list } - public virtual Membership Get() - { - return _Editable = Membership.Get(_UGID); - } + public virtual Membership Get() => _Editable = Membership.Get(_UGID); public static void Refresh(Membership tmp) { string key = tmp.UGID.ToString(); @@ -277,18 +241,18 @@ namespace VEPROMS.CSLA.Library { if (_UID != tmp.UID) { - if (MyUser != null) MyUser.RefreshUserMemberships(); // Update List for old value + MyUser?.RefreshUserMemberships(); // Update List for old value _UID = tmp.UID; // Update the value } _MyUser = null; // Reset list so that the next line gets a new list - if (MyUser != null) MyUser.RefreshUserMemberships(); // Update List for new value + MyUser?.RefreshUserMemberships(); // Update List for new value if (_GID != tmp.GID) { - if (MyGroup != null) MyGroup.RefreshGroupMemberships(); // Update List for old value + MyGroup?.RefreshGroupMemberships(); // Update List for old value _GID = tmp.GID; // Update the value } _MyGroup = null; // Reset list so that the next line gets a new list - if (MyGroup != null) MyGroup.RefreshGroupMemberships(); // Update List for new value + MyGroup?.RefreshGroupMemberships(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _Config = tmp.Config; @@ -309,11 +273,11 @@ namespace VEPROMS.CSLA.Library { if (_UID != tmp.UID) { - if (MyUser != null) MyUser.RefreshUserMemberships(); // Update List for old value + MyUser?.RefreshUserMemberships(); // Update List for old value _UID = tmp.UID; // Update the value } _MyUser = null; // Reset list so that the next line gets a new list - if (MyUser != null) MyUser.RefreshUserMemberships(); // Update List for new value + MyUser?.RefreshUserMemberships(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _Config = tmp.Config; @@ -334,11 +298,11 @@ namespace VEPROMS.CSLA.Library { if (_GID != tmp.GID) { - if (MyGroup != null) MyGroup.RefreshGroupMemberships(); // Update List for old value + MyGroup?.RefreshGroupMemberships(); // Update List for old value _GID = tmp.GID; // Update the value } _MyGroup = null; // Reset list so that the next line gets a new list - if (MyGroup != null) MyGroup.RefreshGroupMemberships(); // Update List for new value + MyGroup?.RefreshGroupMemberships(); // Update List for new value _StartDate = tmp.StartDate; _EndDate = tmp.EndDate; _Config = tmp.Config; @@ -349,8 +313,6 @@ namespace VEPROMS.CSLA.Library } public static MembershipInfo Get(int ugid) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Membership"); try { MembershipInfo tmp = GetCachedByPrimaryKey(ugid); @@ -389,13 +351,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _UGID; - public int UGID - { get { return _UGID; } } - public PKCriteria(int ugid) - { - _UGID = ugid; - } + private readonly int _UGID; + public int UGID => _UGID; + public PKCriteria(int ugid) => _UGID = ugid; } private void ReadData(SafeDataReader dr) { @@ -457,7 +415,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - MembershipInfoExtension _MembershipInfoExtension = new MembershipInfoExtension(); + readonly MembershipInfoExtension _MembershipInfoExtension = new MembershipInfoExtension(); [Serializable()] partial class MembershipInfoExtension : extensionBase { } [Serializable()] @@ -473,10 +431,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is MembershipInfo) + if (destType == typeof(string) && value is MembershipInfo info) { // Return the ToString value - return ((MembershipInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfoList.cs index 780f9c09..db24acd9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/MembershipInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (MembershipInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~MembershipInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~MembershipInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on MembershipInfoList.Get", ex); } } - /// - /// Reset the list of all MembershipInfo. - /// - public static void Reset() - { - _MembershipInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static MembershipInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on MembershipInfoList.Get", ex); - // } - //} - public static MembershipInfoList GetByGID(int gid) + /// + /// Reset the list of all MembershipInfo. + /// + public static void Reset() => _MembershipInfoList = null; + public static MembershipInfoList GetByGID(int gid) { try { @@ -150,7 +128,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] MembershipInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -164,7 +142,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new MembershipInfo(dr)); + while (dr.Read()) Add(new MembershipInfo(dr)); IsReadOnly = true; } } @@ -175,16 +153,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("MembershipInfoList.DataPortal_Fetch", ex); throw new DbCslaException("MembershipInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class GIDCriteria { - public GIDCriteria(int gid) - { - _GID = gid; - } - private int _GID; + public GIDCriteria(int gid) => _GID = gid; + private int _GID; public int GID { get { return _GID; } @@ -193,7 +168,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(GIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] MembershipInfoList.DataPortal_FetchGID", GetHashCode()); try { @@ -208,7 +183,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new MembershipInfo(dr)); + while (dr.Read()) Add(new MembershipInfo(dr)); IsReadOnly = true; } } @@ -219,16 +194,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("MembershipInfoList.DataPortal_FetchGID", ex); throw new DbCslaException("MembershipInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class UIDCriteria { - public UIDCriteria(int uid) - { - _UID = uid; - } - private int _UID; + public UIDCriteria(int uid) => _UID = uid; + private int _UID; public int UID { get { return _UID; } @@ -237,7 +209,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(UIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] MembershipInfoList.DataPortal_FetchUID", GetHashCode()); try { @@ -252,7 +224,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new MembershipInfo(dr)); + while (dr.Read()) Add(new MembershipInfo(dr)); IsReadOnly = true; } } @@ -263,48 +235,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("MembershipInfoList.DataPortal_FetchUID", ex); throw new DbCslaException("MembershipInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection MembershipInfoListPropertyDescriptor pd = new MembershipInfoListPropertyDescriptor(this, i); @@ -321,7 +282,6 @@ namespace VEPROMS.CSLA.Library /// public partial class MembershipInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private MembershipInfo Item { get { return (MembershipInfo)_Item; } } public MembershipInfoListPropertyDescriptor(MembershipInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +290,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is MembershipInfoList) + if (destType == typeof(string) && value is MembershipInfoList list) { // Return department and department role separated by comma. - return ((MembershipInfoList)value).Items.Count.ToString() + " Memberships"; + return $"{list.Items.Count} Memberships"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/NextItems.cs b/PROMS/VEPROMS.CSLA.Library/Generated/NextItems.cs index d4ace9ea..8efaa34d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/NextItems.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/NextItems.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public new Item this[int itemID] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public new Item this[int itemID] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public Item GetItem(int itemID) + public new System.Collections.Generic.IList Items => base.Items; + public Item GetItem(int itemID) { foreach (Item item in this) if (item.ItemID == itemID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public Item Add(Content myContent) // One to Many { Item item = Item.New(myContent); - this.Add(item); + Add(item); return item; } public void Remove(int itemID) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (Item child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (Item child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static NextItems New() - { - return new NextItems(); - } - internal static NextItems Get(SafeDataReader dr, Item parent) - { - return new NextItems(dr, parent); - } - public static NextItems GetByPreviousID(int previousID) + #endregion + #region Factory Methods + internal static NextItems New() => new NextItems(); + internal static NextItems Get(SafeDataReader dr, Item parent) => new NextItems(dr, parent); + public static NextItems GetByPreviousID(int previousID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on NextItems.GetByPreviousID", ex); } } - private NextItems() - { - MarkAsChild(); - } - internal NextItems(SafeDataReader dr, Item parent) + private NextItems() => MarkAsChild(); + internal NextItems(SafeDataReader dr, Item parent) { MarkAsChild(); Fetch(dr, parent); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~NextItems() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~NextItems() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr, Item parent) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(Item.Get(dr, parent)); - this.RaiseListChangedEvents = true; + Add(Item.Get(dr, parent)); + RaiseListChangedEvents = true; } [Serializable()] private class PreviousIDCriteria { - public PreviousIDCriteria(int previousID) - { - _PreviousID = previousID; - } - private int _PreviousID; + public PreviousIDCriteria(int previousID) => _PreviousID = previousID; + private int _PreviousID; public int PreviousID { get { return _PreviousID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(PreviousIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] NextItems.DataPortal_FetchPreviousID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new Item(dr, criteria.PreviousID)); + while (dr.Read()) Add(new Item(dr, criteria.PreviousID)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("NextItems.DataPortal_FetchPreviousID", ex); throw new DbCslaException("NextItems.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Item item) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection NextItemsPropertyDescriptor pd = new NextItemsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class NextItemsPropertyDescriptor : vlnListPropertyDescriptor { - private Item Item { get { return (Item)_Item; } } public NextItemsPropertyDescriptor(NextItems collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is NextItems) + if (destType == typeof(string) && value is NextItems items) { // Return department and department role separated by comma. - return ((NextItems)value).Items.Count.ToString() + " Items"; + return $"{items.Items.Count} Items"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Owner.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Owner.cs index 180f3cb3..6a1bcedc 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Owner.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Owner.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshOwners.Add(this); } - private void ClearRefreshList() - { - _RefreshOwners = new List(); - } + private void ClearRefreshList() => _RefreshOwners = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Owner owner) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(owner)) _CacheList.Remove(owner); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextOwnerID = -1; - public static int NextOwnerID - { - get { return _nextOwnerID--; } - } + public static int NextOwnerID => _nextOwnerID--; private int _OwnerID; [System.ComponentModel.DataObjectField(true, true)] public int OwnerID @@ -182,40 +173,14 @@ namespace VEPROMS.CSLA.Library } } private byte[] _LastChanged = new byte[8];//timestamp - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base Owner.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Owner - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check Owner.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Owner - protected override object GetIdValue() - { - return MyOwnerUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyOwnerUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -243,8 +208,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -258,31 +223,11 @@ namespace VEPROMS.CSLA.Library _OwnerExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(OwnerID, ""); - //AuthorizationRules.AllowRead(SessionID, ""); - //AuthorizationRules.AllowRead(OwnerType, ""); - //AuthorizationRules.AllowRead(OwnerItemID, ""); - //AuthorizationRules.AllowRead(DTSStart, ""); - //AuthorizationRules.AllowWrite(SessionID, ""); - //AuthorizationRules.AllowWrite(OwnerType, ""); - //AuthorizationRules.AllowWrite(OwnerItemID, ""); - //AuthorizationRules.AllowWrite(DTSStart, ""); _OwnerExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -290,42 +235,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _OwnerExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _OwnerUnique = 0; - protected static int OwnerUnique - { get { return ++_OwnerUnique; } } - private int _MyOwnerUnique = OwnerUnique; - public int MyOwnerUnique // Absolutely Unique ID - Editable - { get { return _MyOwnerUnique; } } + protected static int OwnerUnique => ++_OwnerUnique; + private readonly int _MyOwnerUnique = OwnerUnique; + // Absolutely Unique ID - Editable + public int MyOwnerUnique => _MyOwnerUnique; protected Owner() {/* require use of factory methods */ AddToCache(this); @@ -334,15 +251,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Owner() { _CountFinalized++; @@ -367,8 +280,6 @@ namespace VEPROMS.CSLA.Library } public static Owner New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Owner"); try { return DataPortal.Create(); @@ -405,8 +316,6 @@ namespace VEPROMS.CSLA.Library } public static Owner Get(int ownerID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Owner"); try { Owner tmp = GetCachedByPrimaryKey(ownerID); @@ -432,14 +341,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Owner(dr); return null; } - internal Owner(SafeDataReader dr) - { - ReadData(dr); - } + internal Owner(SafeDataReader dr) => ReadData(dr); public static void Delete(int ownerID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Owner"); try { DataPortal.Delete(new PKCriteria(ownerID)); @@ -451,12 +355,6 @@ namespace VEPROMS.CSLA.Library } public override Owner Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Owner"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Owner"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Owner"); try { BuildRefreshList(); @@ -476,13 +374,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _OwnerID; - public int OwnerID - { get { return _OwnerID; } } - public PKCriteria(int ownerID) - { - _OwnerID = ownerID; - } + private readonly int _OwnerID; + public int OwnerID => _OwnerID; + public PKCriteria(int ownerID) => _OwnerID = ownerID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -553,7 +447,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Owner.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -578,36 +472,44 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addOwner"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@SessionID", _SessionID); - cm.Parameters.AddWithValue("@OwnerType", _OwnerType); - cm.Parameters.AddWithValue("@OwnerItemID", _OwnerItemID); - if (_DTSStart.Year >= 1753 && _DTSStart.Year <= 9999) cm.Parameters.AddWithValue("@DTSStart", _DTSStart); - // Output Calculated Columns - SqlParameter param_OwnerID = new SqlParameter("@newOwnerID", SqlDbType.Int); - param_OwnerID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_OwnerID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _OwnerID = (int)cm.Parameters["@newOwnerID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addOwner"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@SessionID", _SessionID); + cm.Parameters.AddWithValue("@OwnerType", _OwnerType); + cm.Parameters.AddWithValue("@OwnerItemID", _OwnerItemID); + if (_DTSStart.Year >= 1753 && _DTSStart.Year <= 9999) cm.Parameters.AddWithValue("@DTSStart", _DTSStart); + // Output Calculated Columns + SqlParameter param_OwnerID = new SqlParameter("@newOwnerID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_OwnerID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _OwnerID = (int)cm.Parameters["@newOwnerID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.SQLInsert", GetHashCode()); @@ -619,7 +521,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Owner.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int ownerID, int sessionID, byte ownerType, int ownerItemID, DateTime dTSStart) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.Add", 0); @@ -636,11 +538,15 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@OwnerItemID", ownerItemID); if (dTSStart.Year >= 1753 && dTSStart.Year <= 9999) cm.Parameters.AddWithValue("@DTSStart", dTSStart); // Output Calculated Columns - SqlParameter param_OwnerID = new SqlParameter("@newOwnerID", SqlDbType.Int); - param_OwnerID.Direction = ParameterDirection.Output; + SqlParameter param_OwnerID = new SqlParameter("@newOwnerID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_OwnerID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -655,7 +561,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Owner.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -678,38 +584,44 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateOwner"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@OwnerID", _OwnerID); - cm.Parameters.AddWithValue("@SessionID", _SessionID); - cm.Parameters.AddWithValue("@OwnerType", _OwnerType); - cm.Parameters.AddWithValue("@OwnerItemID", _OwnerItemID); - if (_DTSStart.Year >= 1753 && _DTSStart.Year <= 9999) cm.Parameters.AddWithValue("@DTSStart", _DTSStart); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateOwner"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@OwnerID", _OwnerID); + cm.Parameters.AddWithValue("@SessionID", _SessionID); + cm.Parameters.AddWithValue("@OwnerType", _OwnerType); + cm.Parameters.AddWithValue("@OwnerItemID", _OwnerItemID); + if (_DTSStart.Year >= 1753 && _DTSStart.Year <= 9999) cm.Parameters.AddWithValue("@DTSStart", _DTSStart); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -722,18 +634,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Owner.Add(cn, ref _OwnerID, _SessionID, _OwnerType, _OwnerItemID, _DTSStart); - else - _LastChanged = Owner.Update(cn, ref _OwnerID, _SessionID, _OwnerType, _OwnerItemID, _DTSStart, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Owner.Add(cn, ref _OwnerID, _SessionID, _OwnerType, _OwnerItemID, _DTSStart); + else + _LastChanged = Owner.Update(cn, ref _OwnerID, _SessionID, _OwnerType, _OwnerItemID, _DTSStart, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int ownerID, int sessionID, byte ownerType, int ownerItemID, DateTime dTSStart, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.Update", 0); @@ -752,8 +668,10 @@ namespace VEPROMS.CSLA.Library if (dTSStart.Year >= 1753 && dTSStart.Year <= 9999) cm.Parameters.AddWithValue("@DTSStart", dTSStart); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -767,12 +685,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Owner.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_OwnerID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.DataPortal_Delete", GetHashCode()); @@ -797,7 +715,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Owner.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int ownerID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.Remove", 0); @@ -838,16 +756,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _OwnerID; + private readonly int _OwnerID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int ownerID) - { - _OwnerID = ownerID; - } + public bool Exists => _exists; + public ExistsCommand(int ownerID) => _OwnerID = ownerID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Owner.DataPortal_Execute", GetHashCode()); @@ -855,7 +767,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -877,7 +789,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - OwnerExtension _OwnerExtension = new OwnerExtension(); + readonly OwnerExtension _OwnerExtension = new OwnerExtension(); [Serializable()] partial class OwnerExtension : extensionBase { @@ -886,22 +798,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultSessionID - { - get { return 0; } - } - public virtual byte DefaultOwnerType - { - get { return 0; } - } - public virtual int DefaultOwnerItemID - { - get { return 0; } - } - public virtual DateTime DefaultDTSStart - { - get { return DateTime.Now; } - } + public virtual int DefaultSessionID => 0; + public virtual byte DefaultOwnerType => 0; + public virtual int DefaultOwnerItemID => 0; + public virtual DateTime DefaultDTSStart => DateTime.Now; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -930,65 +830,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Owner) + if (destType == typeof(string) && value is Owner owner) { // Return the ToString value - return ((Owner)value).ToString(); + return owner.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create OwnerExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Owner -// { -// partial class OwnerExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultSessionID -// { -// get { return 0; } -// } -// public virtual byte DefaultOwnerType -// { -// get { return 0; } -// } -// public virtual int DefaultOwnerItemID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTSStart -// { -// get { return DateTime.Now; } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfo.cs index c4955fc3..05c8c00d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class OwnerInfo : ReadOnlyBase, IDisposable { public event OwnerInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(OwnerInfo ownerInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(ownerInfo)) _CacheList.Remove(ownerInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Owner _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _OwnerID; [System.ComponentModel.DataObjectField(true, true)] public int OwnerID @@ -135,32 +119,19 @@ namespace VEPROMS.CSLA.Library return _DTSStart; } } - // CSLATODO: Replace base OwnerInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current OwnerInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check OwnerInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current OwnerInfo - protected override object GetIdValue() - { - return MyOwnerInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyOwnerInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _OwnerInfoUnique = 0; - private static int OwnerInfoUnique - { get { return ++_OwnerInfoUnique; } } - private int _MyOwnerInfoUnique = OwnerInfoUnique; - public int MyOwnerInfoUnique // Absolutely Unique ID - Info - { get { return _MyOwnerInfoUnique; } } + private static int OwnerInfoUnique => ++_OwnerInfoUnique; + private readonly int _MyOwnerInfoUnique = OwnerInfoUnique; + // Absolutely Unique ID - Info + public int MyOwnerInfoUnique => _MyOwnerInfoUnique; protected OwnerInfo() {/* require use of factory methods */ AddToCache(this); @@ -169,15 +140,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~OwnerInfo() { _CountFinalized++; @@ -194,10 +161,7 @@ namespace VEPROMS.CSLA.Library if (listOwnerInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(OwnerID.ToString()); // remove the list } - public virtual Owner Get() - { - return _Editable = Owner.Get(_OwnerID); - } + public virtual Owner Get() => _Editable = Owner.Get(_OwnerID); public static void Refresh(Owner tmp) { string key = tmp.OwnerID.ToString(); @@ -217,8 +181,6 @@ namespace VEPROMS.CSLA.Library } public static OwnerInfo Get(int ownerID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Owner"); try { OwnerInfo tmp = GetCachedByPrimaryKey(ownerID); @@ -257,13 +219,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _OwnerID; - public int OwnerID - { get { return _OwnerID; } } - public PKCriteria(int ownerID) - { - _OwnerID = ownerID; - } + private readonly int _OwnerID; + public int OwnerID => _OwnerID; + public PKCriteria(int ownerID) => _OwnerID = ownerID; } private void ReadData(SafeDataReader dr) { @@ -322,7 +280,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - OwnerInfoExtension _OwnerInfoExtension = new OwnerInfoExtension(); + readonly OwnerInfoExtension _OwnerInfoExtension = new OwnerInfoExtension(); [Serializable()] partial class OwnerInfoExtension : extensionBase { } [Serializable()] @@ -338,10 +296,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is OwnerInfo) + if (destType == typeof(string) && value is OwnerInfo info) { // Return the ToString value - return ((OwnerInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfoList.cs index 3b6d0168..7d71e684 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/OwnerInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -51,16 +49,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~OwnerInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~OwnerInfoList() { _CountFinalized++; } @@ -97,26 +91,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on OwnerInfoList.Get", ex); } } - /// - /// Reset the list of all OwnerInfo. - /// - public static void Reset() - { - _OwnerInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static OwnerInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on OwnerInfoList.Get", ex); - // } - //} - private OwnerInfoList() + /// + /// Reset the list of all OwnerInfo. + /// + public static void Reset() => _OwnerInfoList = null; + private OwnerInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,41 +128,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -205,7 +173,6 @@ namespace VEPROMS.CSLA.Library /// public partial class OwnerInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private OwnerInfo Item { get { return (OwnerInfo)_Item; } } public OwnerInfoListPropertyDescriptor(OwnerInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +181,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is OwnerInfoList) + if (destType == typeof(string) && value is OwnerInfoList list) { // Return department and department role separated by comma. - return ((OwnerInfoList)value).Items.Count.ToString() + " Owners"; + return $"{list.Items.Count} Owners"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Part.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Part.cs index a058a679..81ed5f7c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Part.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Part.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshParts.Add(this); } - private void ClearRefreshList() - { - _RefreshParts = new List(); - } + private void ClearRefreshList() => _RefreshParts = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Part part) { @@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(part)) _CacheList.Remove(part); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,10 +89,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -210,37 +204,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)) || (_MyItem == null ? false : _MyItem.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)) || (_MyItem != null && _MyItem.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)) && (_MyItem == null ? true : _MyItem.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)) && (_MyItem == null || _MyItem.IsValidList(list)); } - // CSLATODO: Replace base Part.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Part - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Part.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Part - protected override object GetIdValue() - { - return MyPartUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPartUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -269,8 +248,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -299,30 +278,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(FromType, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _PartExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -330,42 +290,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _PartExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _PartUnique = 0; - protected static int PartUnique - { get { return ++_PartUnique; } } - private int _MyPartUnique = PartUnique; - public int MyPartUnique // Absolutely Unique ID - Editable - { get { return _MyPartUnique; } } + protected static int PartUnique => ++_PartUnique; + private readonly int _MyPartUnique = PartUnique; + // Absolutely Unique ID - Editable + public int MyPartUnique => _MyPartUnique; protected Part() {/* require use of factory methods */ AddToCache(this); @@ -374,15 +306,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Part() { _CountFinalized++; @@ -407,8 +335,6 @@ namespace VEPROMS.CSLA.Library } public static Part New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Part"); try { return DataPortal.Create(); @@ -470,8 +396,6 @@ namespace VEPROMS.CSLA.Library } public static Part Get(int contentID, int fromType) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Part"); try { Part tmp = GetCachedByPrimaryKey(contentID, fromType); @@ -497,14 +421,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Part(dr); return null; } - internal Part(SafeDataReader dr) - { - ReadData(dr); - } + internal Part(SafeDataReader dr) => ReadData(dr); public static void Delete(int contentID, int fromType) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Part"); try { DataPortal.Delete(new PKCriteria(contentID, fromType)); @@ -516,12 +435,6 @@ namespace VEPROMS.CSLA.Library } public override Part Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Part"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Part"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Part"); try { BuildRefreshList(); @@ -541,12 +454,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - private int _FromType; - public int FromType - { get { return _FromType; } } + private readonly int _ContentID; + public int ContentID => _ContentID; + private readonly int _FromType; + public int FromType => _FromType; public PKCriteria(int contentID, int fromType) { _ContentID = contentID; @@ -621,7 +532,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Part.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -646,35 +557,41 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyContent != null) _MyContent.Update(); - if (_MyItem != null) _MyItem.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyContent?.Update(); + _MyItem?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addPart"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@FromType", _FromType); - cm.Parameters.AddWithValue("@ItemID", ItemID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addPart"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@FromType", _FromType); + cm.Parameters.AddWithValue("@ItemID", ItemID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.SQLInsert", GetHashCode()); @@ -686,7 +603,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Part.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Content myContent, int fromType, Item myItem, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.Add", 0); @@ -704,8 +621,10 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -719,7 +638,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Part.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -742,40 +661,46 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.SQLUpdate", GetHashCode()); try { - if (_MyContent != null) _MyContent.Update(); - if (_MyItem != null) _MyItem.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyContent?.Update(); + _MyItem?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updatePart"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@FromType", _FromType); - cm.Parameters.AddWithValue("@ItemID", ItemID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updatePart"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@FromType", _FromType); + cm.Parameters.AddWithValue("@ItemID", ItemID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -788,18 +713,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Part.Add(cn, _MyContent, _FromType, _MyItem, _DTS, _UserID); - else - _LastChanged = Part.Update(cn, _ContentID, _FromType, _ItemID, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Part.Add(cn, _MyContent, _FromType, _MyItem, _DTS, _UserID); + else + _LastChanged = Part.Update(cn, _ContentID, _FromType, _ItemID, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int contentID, int fromType, int itemID, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.Update", 0); @@ -818,8 +747,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -833,12 +764,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Part.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ContentID, _FromType)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.DataPortal_Delete", GetHashCode()); @@ -864,7 +795,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Part.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int contentID, int fromType) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Part.Remove", 0); @@ -906,13 +837,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ContentID; - private int _FromType; + private readonly int _ContentID; + private readonly int _FromType; private bool _exists; - public bool Exists - { - get { return _exists; } - } + public bool Exists => _exists; public ExistsCommand(int contentID, int fromType) { _ContentID = contentID; @@ -925,7 +853,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -948,7 +876,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - PartExtension _PartExtension = new PartExtension(); + readonly PartExtension _PartExtension = new PartExtension(); [Serializable()] partial class PartExtension : extensionBase { @@ -957,14 +885,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -993,57 +915,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Part) + if (destType == typeof(string) && value is Part part) { // Return the ToString value - return ((Part)value).ToString(); + return part.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create PartExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Part -// { -// partial class PartExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PartAudit.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PartAudit.cs index 6e4fdcc9..979e8ce3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PartAudit.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PartAudit.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -56,6 +54,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(PartAudit partAudit) { @@ -65,6 +64,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(partAudit)) _CacheList.Remove(partAudit); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +90,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextAuditID = -1; - public static int NextAuditID - { - get { return _nextAuditID--; } - } + public static int NextAuditID => _nextAuditID--; private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -218,40 +212,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base PartAudit.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current PartAudit - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check PartAudit.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current PartAudit - protected override object GetIdValue() - { - return MyPartAuditUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPartAuditUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -279,8 +247,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -299,35 +267,11 @@ namespace VEPROMS.CSLA.Library _PartAuditExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AuditID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(FromType, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DeleteStatus, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(FromType, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DeleteStatus, ""); _PartAuditExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -335,42 +279,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _PartAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _PartAuditUnique = 0; - protected static int PartAuditUnique - { get { return ++_PartAuditUnique; } } - private int _MyPartAuditUnique = PartAuditUnique; - public int MyPartAuditUnique // Absolutely Unique ID - Editable - { get { return _MyPartAuditUnique; } } + protected static int PartAuditUnique => ++_PartAuditUnique; + private readonly int _MyPartAuditUnique = PartAuditUnique; + // Absolutely Unique ID - Editable + public int MyPartAuditUnique => _MyPartAuditUnique; protected PartAudit() {/* require use of factory methods */ AddToCache(this); @@ -379,15 +295,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~PartAudit() { _CountFinalized++; @@ -412,8 +324,6 @@ namespace VEPROMS.CSLA.Library } public static PartAudit New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a PartAudit"); try { return DataPortal.Create(); @@ -452,8 +362,6 @@ namespace VEPROMS.CSLA.Library } public static PartAudit Get(long auditID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a PartAudit"); try { PartAudit tmp = GetCachedByPrimaryKey(auditID); @@ -479,14 +387,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new PartAudit(dr); return null; } - internal PartAudit(SafeDataReader dr) - { - ReadData(dr); - } + internal PartAudit(SafeDataReader dr) => ReadData(dr); public static void Delete(long auditID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a PartAudit"); try { DataPortal.Delete(new PKCriteria(auditID)); @@ -498,12 +401,6 @@ namespace VEPROMS.CSLA.Library } public override PartAudit Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a PartAudit"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a PartAudit"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a PartAudit"); try { BuildRefreshList(); @@ -523,13 +420,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -598,7 +491,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("PartAudit.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -623,34 +516,40 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addPartAudit"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@FromType", _FromType); - cm.Parameters.AddWithValue("@ItemID", _ItemID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_AuditID); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _AuditID = (long)cm.Parameters["@newAuditID"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addPartAudit"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@FromType", _FromType); + cm.Parameters.AddWithValue("@ItemID", _ItemID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_AuditID); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _AuditID = (long)cm.Parameters["@newAuditID"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.SQLInsert", GetHashCode()); @@ -662,7 +561,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("PartAudit.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Add(SqlConnection cn, ref long auditID, int contentID, int fromType, int itemID, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.Add", 0); @@ -681,8 +580,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); // Output Calculated Columns - SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); - param_AuditID.Direction = ParameterDirection.Output; + SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_AuditID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -697,7 +598,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("PartAudit.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -720,35 +621,39 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updatePartAudit"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@AuditID", _AuditID); - cm.Parameters.AddWithValue("@ContentID", _ContentID); - cm.Parameters.AddWithValue("@FromType", _FromType); - cm.Parameters.AddWithValue("@ItemID", _ItemID); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); - // Output Calculated Columns - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updatePartAudit"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@AuditID", _AuditID); + cm.Parameters.AddWithValue("@ContentID", _ContentID); + cm.Parameters.AddWithValue("@FromType", _FromType); + cm.Parameters.AddWithValue("@ItemID", _ItemID); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); + // Output Calculated Columns + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + } } } + MarkOld(); // use the open connection to update child objects } @@ -761,18 +666,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - PartAudit.Add(cn, ref _AuditID, _ContentID, _FromType, _ItemID, _DTS, _UserID, _DeleteStatus); - else - PartAudit.Update(cn, ref _AuditID, _ContentID, _FromType, _ItemID, _DTS, _UserID, _DeleteStatus); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + PartAudit.Add(cn, ref _AuditID, _ContentID, _FromType, _ItemID, _DTS, _UserID, _DeleteStatus); + else + PartAudit.Update(cn, ref _AuditID, _ContentID, _FromType, _ItemID, _DTS, _UserID, _DeleteStatus); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Update(SqlConnection cn, ref long auditID, int contentID, int fromType, int itemID, DateTime dts, string userID, int deleteStatus) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.Update", 0); @@ -804,12 +713,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("PartAudit.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_AuditID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.DataPortal_Delete", GetHashCode()); @@ -834,7 +743,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("PartAudit.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, long auditID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAudit.Remove", 0); @@ -860,7 +769,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - PartAuditExtension _PartAuditExtension = new PartAuditExtension(); + readonly PartAuditExtension _PartAuditExtension = new PartAuditExtension(); [Serializable()] partial class PartAuditExtension : extensionBase { @@ -897,49 +806,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PartAudit) + if (destType == typeof(string) && value is PartAudit audit) { // Return the ToString value - return ((PartAudit)value).ToString(); + return audit.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create PartAuditExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class PartAudit -// { -// partial class PartAuditExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfo.cs index f57dd7bc..56c98085 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class PartAuditInfo : ReadOnlyBase, IDisposable { public event PartAuditInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(PartAuditInfo partAuditInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(partAuditInfo)) _CacheList.Remove(partAuditInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected PartAudit _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private long _AuditID; [System.ComponentModel.DataObjectField(true, true)] public long AuditID @@ -153,32 +137,19 @@ namespace VEPROMS.CSLA.Library return _DeleteStatus; } } - // CSLATODO: Replace base PartAuditInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current PartAuditInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check PartAuditInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current PartAuditInfo - protected override object GetIdValue() - { - return MyPartAuditInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPartAuditInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _PartAuditInfoUnique = 0; - private static int PartAuditInfoUnique - { get { return ++_PartAuditInfoUnique; } } - private int _MyPartAuditInfoUnique = PartAuditInfoUnique; - public int MyPartAuditInfoUnique // Absolutely Unique ID - Info - { get { return _MyPartAuditInfoUnique; } } + private static int PartAuditInfoUnique => ++_PartAuditInfoUnique; + private readonly int _MyPartAuditInfoUnique = PartAuditInfoUnique; + // Absolutely Unique ID - Info + public int MyPartAuditInfoUnique => _MyPartAuditInfoUnique; protected PartAuditInfo() {/* require use of factory methods */ AddToCache(this); @@ -187,15 +158,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~PartAuditInfo() { _CountFinalized++; @@ -212,10 +179,7 @@ namespace VEPROMS.CSLA.Library if (listPartAuditInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list } - public virtual PartAudit Get() - { - return _Editable = PartAudit.Get(_AuditID); - } + public virtual PartAudit Get() => _Editable = PartAudit.Get(_AuditID); public static void Refresh(PartAudit tmp) { string key = tmp.AuditID.ToString(); @@ -237,8 +201,6 @@ namespace VEPROMS.CSLA.Library } public static PartAuditInfo Get(long auditID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a PartAudit"); try { PartAuditInfo tmp = GetCachedByPrimaryKey(auditID); @@ -277,13 +239,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private long _AuditID; - public long AuditID - { get { return _AuditID; } } - public PKCriteria(long auditID) - { - _AuditID = auditID; - } + private readonly long _AuditID; + public long AuditID => _AuditID; + public PKCriteria(long auditID) => _AuditID = auditID; } private void ReadData(SafeDataReader dr) { @@ -344,7 +302,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - PartAuditInfoExtension _PartAuditInfoExtension = new PartAuditInfoExtension(); + readonly PartAuditInfoExtension _PartAuditInfoExtension = new PartAuditInfoExtension(); [Serializable()] partial class PartAuditInfoExtension : extensionBase { } [Serializable()] @@ -360,10 +318,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PartAuditInfo) + if (destType == typeof(string) && value is PartAuditInfo info) { // Return the ToString value - return ((PartAuditInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfoList.cs index 52a5ca25..a70e3b8e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PartAuditInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (PartAuditInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~PartAuditInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~PartAuditInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on PartAuditInfoList.Get", ex); } } - /// - /// Reset the list of all PartAuditInfo. - /// - public static void Reset() - { - _PartAuditInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static PartAuditInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on PartAuditInfoList.Get", ex); - // } - //} - private PartAuditInfoList() + /// + /// Reset the list of all PartAuditInfo. + /// + public static void Reset() => _PartAuditInfoList = null; + private PartAuditInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartAuditInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartAuditInfo(dr)); + while (dr.Read()) Add(new PartAuditInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartAuditInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PartAuditInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection PartAuditInfoListPropertyDescriptor pd = new PartAuditInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class PartAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private PartAuditInfo Item { get { return (PartAuditInfo)_Item; } } public PartAuditInfoListPropertyDescriptor(PartAuditInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PartAuditInfoList) + if (destType == typeof(string) && value is PartAuditInfoList list) { // Return department and department role separated by comma. - return ((PartAuditInfoList)value).Items.Count.ToString() + " PartAudits"; + return $"{list.Items.Count} PartAudits"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PartInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PartInfo.cs index 1586b596..e43d42c2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PartInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PartInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class PartInfo : ReadOnlyBase, IDisposable { public event PartInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(PartInfo partInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(partInfo)) _CacheList.Remove(partInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -81,21 +78,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Part _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -166,32 +150,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base PartInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current PartInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check PartInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current PartInfo - protected override object GetIdValue() - { - return MyPartInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPartInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _PartInfoUnique = 0; - private static int PartInfoUnique - { get { return ++_PartInfoUnique; } } - private int _MyPartInfoUnique = PartInfoUnique; - public int MyPartInfoUnique // Absolutely Unique ID - Info - { get { return _MyPartInfoUnique; } } + private static int PartInfoUnique => ++_PartInfoUnique; + private readonly int _MyPartInfoUnique = PartInfoUnique; + // Absolutely Unique ID - Info + public int MyPartInfoUnique => _MyPartInfoUnique; protected PartInfo() {/* require use of factory methods */ AddToCache(this); @@ -200,15 +171,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~PartInfo() { _CountFinalized++; @@ -227,10 +194,7 @@ namespace VEPROMS.CSLA.Library if (listPartInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ContentID.ToString() + "_" + FromType.ToString()); // remove the list } - public virtual Part Get() - { - return _Editable = Part.Get(_ContentID, _FromType); - } + public virtual Part Get() => _Editable = Part.Get(_ContentID, _FromType); public static void Refresh(Part tmp) { string key = tmp.ContentID.ToString() + "_" + tmp.FromType.ToString(); @@ -243,11 +207,11 @@ namespace VEPROMS.CSLA.Library { if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemParts(); // Update List for old value + MyItem?.RefreshItemParts(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemParts(); // Update List for new value + MyItem?.RefreshItemParts(); // Update List for new value _DTS = tmp.DTS; _UserID = tmp.UserID; _PartInfoExtension.Refresh(this); @@ -265,11 +229,11 @@ namespace VEPROMS.CSLA.Library { if (_ItemID != tmp.ItemID) { - if (MyItem != null) MyItem.RefreshItemParts(); // Update List for old value + MyItem?.RefreshItemParts(); // Update List for old value _ItemID = tmp.ItemID; // Update the value } _MyItem = null; // Reset list so that the next line gets a new list - if (MyItem != null) MyItem.RefreshItemParts(); // Update List for new value + MyItem?.RefreshItemParts(); // Update List for new value _DTS = tmp.DTS; _UserID = tmp.UserID; _PartInfoExtension.Refresh(this); @@ -292,8 +256,6 @@ namespace VEPROMS.CSLA.Library } public static PartInfo Get(int contentID, int fromType) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Part"); try { PartInfo tmp = GetCachedByPrimaryKey(contentID, fromType); @@ -332,12 +294,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - private int _FromType; - public int FromType - { get { return _FromType; } } + private readonly int _ContentID; + public int ContentID => _ContentID; + private readonly int _FromType; + public int FromType => _FromType; public PKCriteria(int contentID, int fromType) { _ContentID = contentID; @@ -402,7 +362,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - PartInfoExtension _PartInfoExtension = new PartInfoExtension(); + readonly PartInfoExtension _PartInfoExtension = new PartInfoExtension(); [Serializable()] partial class PartInfoExtension : extensionBase { } [Serializable()] @@ -418,10 +378,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PartInfo) + if (destType == typeof(string) && value is PartInfo info) { // Return the ToString value - return ((PartInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PartInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PartInfoList.cs index b9f44c2a..dcbd968c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PartInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PartInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -30,8 +28,7 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - internal new IList Items - { get { return base.Items; } } + internal new IList Items => base.Items; public void AddEvents() { foreach (PartInfo tmp in this) @@ -44,22 +41,18 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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 static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~PartInfoList() { _CountFinalized++; @@ -100,22 +93,7 @@ namespace VEPROMS.CSLA.Library /// /// Reset the list of all PartInfo. /// - public static void Reset() - { - _PartInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static PartInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on PartInfoList.Get", ex); - // } - //} + public static void Reset() => _PartInfoList = null; public static PartInfoList GetByContentID(int contentID) { try @@ -150,7 +128,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -164,7 +142,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartInfo(dr)); + while (dr.Read()) Add(new PartInfo(dr)); IsReadOnly = true; } } @@ -175,15 +153,12 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PartInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } + public ContentIDCriteria(int contentID) => _ContentID = contentID; private int _ContentID; public int ContentID { @@ -193,7 +168,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartInfoList.DataPortal_FetchContentID", GetHashCode()); try { @@ -208,7 +183,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartInfo(dr)); + while (dr.Read()) Add(new PartInfo(dr)); IsReadOnly = true; } } @@ -219,15 +194,12 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartInfoList.DataPortal_FetchContentID", ex); throw new DbCslaException("PartInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } + public ItemIDCriteria(int itemID) => _ItemID = itemID; private int _ItemID; public int ItemID { @@ -237,7 +209,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PartInfoList.DataPortal_FetchItemID", GetHashCode()); try { @@ -252,7 +224,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PartInfo(dr)); + while (dr.Read()) Add(new PartInfo(dr)); IsReadOnly = true; } } @@ -263,38 +235,27 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PartInfoList.DataPortal_FetchItemID", ex); throw new DbCslaException("PartInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } #endregion #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; /// /// Called to get the properties of this type. Returns properties with certain /// attributes. this restriction is not implemented here. /// /// /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); /// /// Called to get the properties of this type. /// @@ -304,7 +265,7 @@ namespace VEPROMS.CSLA.Library // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection PartInfoListPropertyDescriptor pd = new PartInfoListPropertyDescriptor(this, i); @@ -321,7 +282,6 @@ namespace VEPROMS.CSLA.Library /// public partial class PartInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private PartInfo Item { get { return (PartInfo)_Item; } } public PartInfoListPropertyDescriptor(PartInfoList collection, int index) : base(collection, index) {; } } #endregion @@ -330,10 +290,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PartInfoList) + if (destType == typeof(string) && value is PartInfoList list) { // Return department and department role separated by comma. - return ((PartInfoList)value).Items.Count.ToString() + " Parts"; + return $"{list.Items.Count} Parts"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Pdf.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Pdf.cs index 9bd0d5d8..58d8fd40 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Pdf.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Pdf.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshPdfs.Add(this); } - private void ClearRefreshList() - { - _RefreshPdfs = new List(); - } + private void ClearRefreshList() => _RefreshPdfs = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -57,6 +52,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Pdf pdf) { @@ -66,13 +62,14 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(pdf)) _CacheList.Remove(pdf); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Pdf(s) from temporary _CacheList to _CacheByPrimaryKey { Pdf tmp = _CacheList[0]; // Get the first Pdf - string pKey = tmp.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString(); + string pKey = $"{tmp.DocID}_{tmp.DebugStatus}_{tmp.TopRow}_{tmp.PageLength}_{tmp.LeftMargin}_{tmp.PageWidth}"; if (!_CacheByPrimaryKey.ContainsKey(pKey)) { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey @@ -84,17 +81,14 @@ namespace VEPROMS.CSLA.Library protected static Pdf GetCachedByPrimaryKey(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { ConvertListToDictionary(); - string key = docID.ToString() + "_" + debugStatus.ToString() + "_" + topRow.ToString() + "_" + pageLength.ToString() + "_" + leftMargin.ToString() + "_" + pageWidth.ToString(); + string key = $"{docID}_{debugStatus}_{topRow}_{pageLength}_{leftMargin}_{pageWidth}"; if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _DocID; [System.ComponentModel.DataObjectField(true, true)] public int DocID @@ -261,37 +255,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyDocument != null && _MyDocument.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocument == null || _MyDocument.IsValidList(list)); } - // CSLATODO: Replace base Pdf.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Pdf - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Pdf.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Pdf - protected override object GetIdValue() - { - return MyPdfUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPdfUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -319,8 +298,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -339,36 +318,11 @@ namespace VEPROMS.CSLA.Library _PdfExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowRead(DebugStatus, ""); - //AuthorizationRules.AllowRead(TopRow, ""); - //AuthorizationRules.AllowRead(PageLength, ""); - //AuthorizationRules.AllowRead(LeftMargin, ""); - //AuthorizationRules.AllowRead(PageWidth, ""); - //AuthorizationRules.AllowRead(PageCount, ""); - //AuthorizationRules.AllowRead(DocPdf, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(PageCount, ""); - //AuthorizationRules.AllowWrite(DocPdf, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _PdfExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -376,42 +330,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _PdfExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _PdfUnique = 0; - protected static int PdfUnique - { get { return ++_PdfUnique; } } - private int _MyPdfUnique = PdfUnique; - public int MyPdfUnique // Absolutely Unique ID - Editable - { get { return _MyPdfUnique; } } + protected static int PdfUnique => ++_PdfUnique; + private readonly int _MyPdfUnique = PdfUnique; + // Absolutely Unique ID - Editable + public int MyPdfUnique => _MyPdfUnique; protected Pdf() {/* require use of factory methods */ AddToCache(this); @@ -420,15 +346,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Pdf() { _CountFinalized++; @@ -453,8 +375,6 @@ namespace VEPROMS.CSLA.Library } public static Pdf New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Pdf"); try { return DataPortal.Create(); @@ -541,8 +461,6 @@ namespace VEPROMS.CSLA.Library } public static Pdf Get(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Pdf"); try { Pdf tmp = GetCachedByPrimaryKey(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth); @@ -568,14 +486,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Pdf(dr); return null; } - internal Pdf(SafeDataReader dr) - { - ReadData(dr); - } + internal Pdf(SafeDataReader dr) => ReadData(dr); public static void Delete(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Pdf"); try { DataPortal.Delete(new PKCriteria(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth)); @@ -587,12 +500,6 @@ namespace VEPROMS.CSLA.Library } public override Pdf Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Pdf"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Pdf"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Pdf"); try { BuildRefreshList(); @@ -619,24 +526,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - private int _DebugStatus; - public int DebugStatus - { get { return _DebugStatus; } } - private int _TopRow; - public int TopRow - { get { return _TopRow; } } - private int _PageLength; - public int PageLength - { get { return _PageLength; } } - private int _LeftMargin; - public int LeftMargin - { get { return _LeftMargin; } } - private int _PageWidth; - public int PageWidth - { get { return _PageWidth; } } + private readonly int _DocID; + public int DocID => _DocID; + private readonly int _DebugStatus; + public int DebugStatus => _DebugStatus; + private readonly int _TopRow; + public int TopRow => _TopRow; + private readonly int _PageLength; + public int PageLength => _PageLength; + private readonly int _LeftMargin; + public int LeftMargin => _LeftMargin; + private readonly int _PageWidth; + public int PageWidth => _PageWidth; public PKCriteria(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { _DocID = docID; @@ -724,7 +625,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Pdf.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -749,39 +650,45 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyDocument != null) _MyDocument.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyDocument?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addPdf"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@DocID", DocID); - cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); - cm.Parameters.AddWithValue("@TopRow", _TopRow); - cm.Parameters.AddWithValue("@PageLength", _PageLength); - cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); - cm.Parameters.AddWithValue("@PageWidth", _PageWidth); - cm.Parameters.AddWithValue("@PageCount", _PageCount); - cm.Parameters.AddWithValue("@DocPdf", _DocPdf); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addPdf"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@DocID", DocID); + cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); + cm.Parameters.AddWithValue("@TopRow", _TopRow); + cm.Parameters.AddWithValue("@PageLength", _PageLength); + cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); + cm.Parameters.AddWithValue("@PageWidth", _PageWidth); + cm.Parameters.AddWithValue("@PageCount", _PageCount); + cm.Parameters.AddWithValue("@DocPdf", _DocPdf); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.SQLInsert", GetHashCode()); @@ -793,7 +700,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Pdf.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.Add", 0); @@ -816,8 +723,10 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -831,7 +740,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Pdf.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -854,44 +763,50 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.SQLUpdate", GetHashCode()); try { - if (_MyDocument != null) _MyDocument.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyDocument?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updatePdf"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@DocID", DocID); - cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); - cm.Parameters.AddWithValue("@TopRow", _TopRow); - cm.Parameters.AddWithValue("@PageLength", _PageLength); - cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); - cm.Parameters.AddWithValue("@PageWidth", _PageWidth); - cm.Parameters.AddWithValue("@PageCount", _PageCount); - cm.Parameters.AddWithValue("@DocPdf", _DocPdf); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updatePdf"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@DocID", DocID); + cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); + cm.Parameters.AddWithValue("@TopRow", _TopRow); + cm.Parameters.AddWithValue("@PageLength", _PageLength); + cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); + cm.Parameters.AddWithValue("@PageWidth", _PageWidth); + cm.Parameters.AddWithValue("@PageCount", _PageCount); + cm.Parameters.AddWithValue("@DocPdf", _DocPdf); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -904,18 +819,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Pdf.Add(cn, _MyDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID); - else - _LastChanged = Pdf.Update(cn, _DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Pdf.Add(cn, _MyDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID); + else + _LastChanged = Pdf.Update(cn, _DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.Update", 0); @@ -939,8 +858,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -954,12 +875,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Pdf.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Delete", GetHashCode()); @@ -989,7 +910,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Pdf.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.Remove", 0); @@ -1035,17 +956,14 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _DocID; - private int _DebugStatus; - private int _TopRow; - private int _PageLength; - private int _LeftMargin; - private int _PageWidth; + private readonly int _DocID; + private readonly int _DebugStatus; + private readonly int _TopRow; + private readonly int _PageLength; + private readonly int _LeftMargin; + private readonly int _PageWidth; private bool _exists; - public bool Exists - { - get { return _exists; } - } + public bool Exists => _exists; public ExistsCommand(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { _DocID = docID; @@ -1062,7 +980,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1089,7 +1007,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - PdfExtension _PdfExtension = new PdfExtension(); + readonly PdfExtension _PdfExtension = new PdfExtension(); [Serializable()] partial class PdfExtension : extensionBase { @@ -1098,14 +1016,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1134,57 +1046,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Pdf) + if (destType == typeof(string) && value is Pdf mypdf) { // Return the ToString value - return ((Pdf)value).ToString(); + return mypdf.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create PdfExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Pdf -// { -// partial class PdfExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs index 67fb92d5..c528c993 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class PdfInfo : ReadOnlyBase, IDisposable { public event PdfInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(PdfInfo pdfInfo) { @@ -45,13 +41,14 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(pdfInfo)) _CacheList.Remove(pdfInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move PdfInfo(s) from temporary _CacheList to _CacheByPrimaryKey { PdfInfo tmp = _CacheList[0]; // Get the first PdfInfo - string pKey = tmp.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString(); + string pKey = $"{tmp.DocID}_{tmp.DebugStatus}_{tmp.TopRow}_{tmp.PageLength}_{tmp.LeftMargin}_{tmp.PageWidth}"; if (!_CacheByPrimaryKey.ContainsKey(pKey)) { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey @@ -67,7 +64,7 @@ namespace VEPROMS.CSLA.Library protected static PdfInfo GetCachedByPrimaryKey(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { ConvertListToDictionary(); - string key = docID.ToString() + "_" + debugStatus.ToString() + "_" + topRow.ToString() + "_" + pageLength.ToString() + "_" + leftMargin.ToString() + "_" + pageWidth.ToString(); + string key = $"{docID}_{debugStatus}_{topRow}_{pageLength}_{leftMargin}_{pageWidth}"; if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0]; return null; } @@ -77,7 +74,7 @@ namespace VEPROMS.CSLA.Library protected static void RemoveFromCachedByPrimaryKey(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { ConvertListToDictionary(); - string key = docID.ToString() + "_" + debugStatus.ToString() + "_" + topRow.ToString() + "_" + pageLength.ToString() + "_" + leftMargin.ToString() + "_" + pageWidth.ToString(); + string key = $"{docID}_{debugStatus}_{topRow}_{pageLength}_{leftMargin}_{pageWidth}"; if (_CacheByPrimaryKey.ContainsKey(key)) { _CacheByPrimaryKey.Remove(key); @@ -87,21 +84,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Pdf _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _DocID; [System.ComponentModel.DataObjectField(true, true)] public int DocID @@ -216,32 +200,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base PdfInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current PdfInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check PdfInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current PdfInfo - protected override object GetIdValue() - { - return MyPdfInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPdfInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _PdfInfoUnique = 0; - private static int PdfInfoUnique - { get { return ++_PdfInfoUnique; } } - private int _MyPdfInfoUnique = PdfInfoUnique; - public int MyPdfInfoUnique // Absolutely Unique ID - Info - { get { return _MyPdfInfoUnique; } } + private static int PdfInfoUnique => ++_PdfInfoUnique; + private readonly int _MyPdfInfoUnique = PdfInfoUnique; + // Absolutely Unique ID - Info + public int MyPdfInfoUnique => _MyPdfInfoUnique; protected PdfInfo() {/* require use of factory methods */ AddToCache(this); @@ -250,15 +221,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~PdfInfo() { _CountFinalized++; @@ -269,19 +236,16 @@ namespace VEPROMS.CSLA.Library _CountDisposed++; _Disposed = true; RemoveFromCache(this); - if (!_CacheByPrimaryKey.ContainsKey(DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString())) return; - List listPdfInfo = _CacheByPrimaryKey[DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString()]; // Get the list of items + if (!_CacheByPrimaryKey.ContainsKey($"{DocID}_{DebugStatus}_{TopRow}_{PageLength}_{LeftMargin}_{PageWidth}")) return; + List listPdfInfo = _CacheByPrimaryKey[$"{DocID}_{DebugStatus}_{TopRow}_{PageLength}_{LeftMargin}_{PageWidth}"]; // Get the list of items while (listPdfInfo.Contains(this)) listPdfInfo.Remove(this); // Remove the item from the list if (listPdfInfo.Count == 0) // If there are no items left in the list - _CacheByPrimaryKey.Remove(DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString()); // remove the list - } - public virtual Pdf Get() - { - return _Editable = Pdf.Get(_DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth); + _CacheByPrimaryKey.Remove($"{DocID}_{DebugStatus}_{TopRow}_{PageLength}_{LeftMargin}_{PageWidth}"); // remove the list } + public virtual Pdf Get() => _Editable = Pdf.Get(_DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth); public static void Refresh(Pdf tmp) { - string key = tmp.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString(); + string key = $"{tmp.DocID}_{tmp.DebugStatus}_{tmp.TopRow}_{tmp.PageLength}_{tmp.LeftMargin}_{tmp.PageWidth}"; ConvertListToDictionary(); if (_CacheByPrimaryKey.ContainsKey(key)) foreach (PdfInfo tmpInfo in _CacheByPrimaryKey[key]) @@ -298,7 +262,7 @@ namespace VEPROMS.CSLA.Library } public static void Refresh(Document myDocument, DocumentPdf tmp) { - string key = myDocument.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString(); + string key = $"{myDocument.DocID}_{tmp.DebugStatus}_{tmp.TopRow}_{tmp.PageLength}_{tmp.LeftMargin}_{tmp.PageWidth}"; ConvertListToDictionary(); if (_CacheByPrimaryKey.ContainsKey(key)) foreach (PdfInfo tmpInfo in _CacheByPrimaryKey[key]) @@ -315,8 +279,6 @@ namespace VEPROMS.CSLA.Library } public static PdfInfo Get(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Pdf"); try { PdfInfo tmp = GetCachedByPrimaryKey(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth); @@ -355,24 +317,18 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - private int _DebugStatus; - public int DebugStatus - { get { return _DebugStatus; } } - private int _TopRow; - public int TopRow - { get { return _TopRow; } } - private int _PageLength; - public int PageLength - { get { return _PageLength; } } - private int _LeftMargin; - public int LeftMargin - { get { return _LeftMargin; } } - private int _PageWidth; - public int PageWidth - { get { return _PageWidth; } } + private readonly int _DocID; + public int DocID => _DocID; + private readonly int _DebugStatus; + public int DebugStatus => _DebugStatus; + private readonly int _TopRow; + public int TopRow => _TopRow; + private readonly int _PageLength; + public int PageLength => _PageLength; + private readonly int _LeftMargin; + public int LeftMargin => _LeftMargin; + private readonly int _PageWidth; + public int PageWidth => _PageWidth; public PKCriteria(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { _DocID = docID; @@ -450,7 +406,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - PdfInfoExtension _PdfInfoExtension = new PdfInfoExtension(); + readonly PdfInfoExtension _PdfInfoExtension = new PdfInfoExtension(); [Serializable()] partial class PdfInfoExtension : extensionBase { } [Serializable()] @@ -466,10 +422,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PdfInfo) + if (destType == typeof(string) && value is PdfInfo info) { // Return the ToString value - return ((PdfInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfoList.cs index c99b453f..17f23fd6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PdfInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (PdfInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~PdfInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~PdfInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on PdfInfoList.Get", ex); } } - /// - /// Reset the list of all PdfInfo. - /// - public static void Reset() - { - _PdfInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static PdfInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on PdfInfoList.Get", ex); - // } - //} - public static PdfInfoList GetByDocID(int docID) + /// + /// Reset the list of all PdfInfo. + /// + public static void Reset() => _PdfInfoList = null; + public static PdfInfoList GetByDocID(int docID) { try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PdfInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -150,7 +128,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PdfInfo(dr)); + while (dr.Read()) Add(new PdfInfo(dr)); IsReadOnly = true; } } @@ -161,16 +139,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PdfInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PdfInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class DocIDCriteria { - public DocIDCriteria(int docID) - { - _DocID = docID; - } - private int _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + private int _DocID; public int DocID { get { return _DocID; } @@ -179,7 +154,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(DocIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PdfInfoList.DataPortal_FetchDocID", GetHashCode()); try { @@ -194,7 +169,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PdfInfo(dr)); + while (dr.Read()) Add(new PdfInfo(dr)); IsReadOnly = true; } } @@ -205,48 +180,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PdfInfoList.DataPortal_FetchDocID", ex); throw new DbCslaException("PdfInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection PdfInfoListPropertyDescriptor pd = new PdfInfoListPropertyDescriptor(this, i); @@ -263,7 +227,6 @@ namespace VEPROMS.CSLA.Library /// public partial class PdfInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private PdfInfo Item { get { return (PdfInfo)_Item; } } public PdfInfoListPropertyDescriptor(PdfInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -272,10 +235,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PdfInfoList) + if (destType == typeof(string) && value is PdfInfoList list) { // Return department and department role separated by comma. - return ((PdfInfoList)value).Items.Count.ToString() + " Pdfs"; + return $"{list.Items.Count} Pdfs"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Permission.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Permission.cs index 29c0ef05..06a14176 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Permission.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Permission.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshPermissions.Add(this); } - private void ClearRefreshList() - { - _RefreshPermissions = new List(); - } + private void ClearRefreshList() => _RefreshPermissions = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -57,6 +52,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Permission permission) { @@ -66,6 +62,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(permission)) _CacheList.Remove(permission); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -91,15 +88,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextPID = -1; - public static int NextPID - { - get { return _nextPID--; } - } + public static int NextPID => _nextPID--; private int _PID; [System.ComponentModel.DataObjectField(true, true)] public int PID @@ -351,37 +342,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRole == null ? false : _MyRole.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRole != null && _MyRole.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRole == null ? true : _MyRole.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRole == null || _MyRole.IsValidList(list)); } - // CSLATODO: Replace base Permission.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Permission - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Permission.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Permission - protected override object GetIdValue() - { - return MyPermissionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPermissionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -410,8 +386,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -473,43 +449,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(PID, ""); - //AuthorizationRules.AllowRead(RID, ""); - //AuthorizationRules.AllowRead(PermLevel, ""); - //AuthorizationRules.AllowRead(VersionType, ""); - //AuthorizationRules.AllowRead(PermValue, ""); - //AuthorizationRules.AllowRead(PermAD, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(RID, ""); - //AuthorizationRules.AllowWrite(PermLevel, ""); - //AuthorizationRules.AllowWrite(VersionType, ""); - //AuthorizationRules.AllowWrite(PermValue, ""); - //AuthorizationRules.AllowWrite(PermAD, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); _PermissionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -517,42 +461,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _PermissionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _PermissionUnique = 0; - protected static int PermissionUnique - { get { return ++_PermissionUnique; } } - private int _MyPermissionUnique = PermissionUnique; - public int MyPermissionUnique // Absolutely Unique ID - Editable - { get { return _MyPermissionUnique; } } + protected static int PermissionUnique => ++_PermissionUnique; + private readonly int _MyPermissionUnique = PermissionUnique; + // Absolutely Unique ID - Editable + public int MyPermissionUnique => _MyPermissionUnique; protected Permission() {/* require use of factory methods */ AddToCache(this); @@ -561,15 +477,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Permission() { _CountFinalized++; @@ -594,8 +506,6 @@ namespace VEPROMS.CSLA.Library } public static Permission New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Permission"); try { return DataPortal.Create(); @@ -640,7 +550,7 @@ namespace VEPROMS.CSLA.Library tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { - tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; + tmp._ErrorMessage += $"\r\n\tFailure: {br.RuleName}"; } } return tmp; @@ -667,15 +577,13 @@ namespace VEPROMS.CSLA.Library tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { - tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; + tmp._ErrorMessage += $"\r\n\tFailure: {br.RuleName}"; } } return tmp; } public static Permission Get(int pid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Permission"); try { Permission tmp = GetCachedByPrimaryKey(pid); @@ -701,14 +609,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Permission(dr); return null; } - internal Permission(SafeDataReader dr) - { - ReadData(dr); - } + internal Permission(SafeDataReader dr) => ReadData(dr); public static void Delete(int pid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Permission"); try { DataPortal.Delete(new PKCriteria(pid)); @@ -720,12 +623,6 @@ namespace VEPROMS.CSLA.Library } public override Permission Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Permission"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Permission"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Permission"); try { BuildRefreshList(); @@ -745,13 +642,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _PID; - public int PID - { get { return _PID; } } - public PKCriteria(int pid) - { - _PID = pid; - } + private readonly int _PID; + public int PID => _PID; + public PKCriteria(int pid) => _PID = pid; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -828,7 +721,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Permission.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -853,43 +746,51 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyRole != null) _MyRole.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyRole?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addPermission"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@RID", RID); - cm.Parameters.AddWithValue("@PermLevel", _PermLevel); - cm.Parameters.AddWithValue("@VersionType", _VersionType); - cm.Parameters.AddWithValue("@PermValue", _PermValue); - cm.Parameters.AddWithValue("@PermAD", _PermAD); - cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); - cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_PID = new SqlParameter("@newPID", SqlDbType.Int); - param_PID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_PID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _PID = (int)cm.Parameters["@newPID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addPermission"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@RID", RID); + cm.Parameters.AddWithValue("@PermLevel", _PermLevel); + cm.Parameters.AddWithValue("@VersionType", _VersionType); + cm.Parameters.AddWithValue("@PermValue", _PermValue); + cm.Parameters.AddWithValue("@PermAD", _PermAD); + cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); + cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_PID = new SqlParameter("@newPID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_PID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _PID = (int)cm.Parameters["@newPID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.SQLInsert", GetHashCode()); @@ -901,7 +802,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Permission.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int pid, Role myRole, int permLevel, int versionType, int permValue, int permAD, SmartDate startDate, SmartDate endDate, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.Add", 0); @@ -924,11 +825,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_PID = new SqlParameter("@newPID", SqlDbType.Int); - param_PID.Direction = ParameterDirection.Output; + SqlParameter param_PID = new SqlParameter("@newPID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_PID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -943,7 +848,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Permission.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -966,45 +871,51 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.SQLUpdate", GetHashCode()); try { - if (_MyRole != null) _MyRole.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyRole?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updatePermission"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@PID", _PID); - cm.Parameters.AddWithValue("@RID", RID); - cm.Parameters.AddWithValue("@PermLevel", _PermLevel); - cm.Parameters.AddWithValue("@VersionType", _VersionType); - cm.Parameters.AddWithValue("@PermValue", _PermValue); - cm.Parameters.AddWithValue("@PermAD", _PermAD); - cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); - cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updatePermission"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@PID", _PID); + cm.Parameters.AddWithValue("@RID", RID); + cm.Parameters.AddWithValue("@PermLevel", _PermLevel); + cm.Parameters.AddWithValue("@VersionType", _VersionType); + cm.Parameters.AddWithValue("@PermValue", _PermValue); + cm.Parameters.AddWithValue("@PermAD", _PermAD); + cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); + cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -1017,18 +928,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Permission.Add(cn, ref _PID, _MyRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); - else - _LastChanged = Permission.Update(cn, ref _PID, _RID, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Permission.Add(cn, ref _PID, _MyRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + else + _LastChanged = Permission.Update(cn, ref _PID, _RID, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int pid, int rid, int permLevel, int versionType, int permValue, int permAD, SmartDate startDate, SmartDate endDate, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.Update", 0); @@ -1053,8 +968,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1068,12 +985,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Permission.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_PID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.DataPortal_Delete", GetHashCode()); @@ -1098,7 +1015,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Permission.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int pid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.Remove", 0); @@ -1139,16 +1056,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _PID; + private readonly int _PID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int pid) - { - _PID = pid; - } + public bool Exists => _exists; + public ExistsCommand(int pid) => _PID = pid; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.DataPortal_Execute", GetHashCode()); @@ -1156,7 +1067,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1178,7 +1089,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - PermissionExtension _PermissionExtension = new PermissionExtension(); + readonly PermissionExtension _PermissionExtension = new PermissionExtension(); [Serializable()] partial class PermissionExtension : extensionBase { @@ -1187,22 +1098,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultPermAD - { - get { return 0; } - } - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultPermAD => 0; + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1231,65 +1130,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Permission) + if (destType == typeof(string) && value is Permission perm) { // Return the ToString value - return ((Permission)value).ToString(); + return perm.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create PermissionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Permission -// { -// partial class PermissionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultPermAD -// { -// get { return 0; } -// } -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfo.cs index a6c7edf3..5b2e583f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class PermissionInfo : ReadOnlyBase, IDisposable { public event PermissionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(PermissionInfo permissionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(permissionInfo)) _CacheList.Remove(permissionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Permission _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _PID; [System.ComponentModel.DataObjectField(true, true)] public int PID @@ -212,32 +196,19 @@ namespace VEPROMS.CSLA.Library return _UsrID; } } - // CSLATODO: Replace base PermissionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current PermissionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check PermissionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current PermissionInfo - protected override object GetIdValue() - { - return MyPermissionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyPermissionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _PermissionInfoUnique = 0; - private static int PermissionInfoUnique - { get { return ++_PermissionInfoUnique; } } - private int _MyPermissionInfoUnique = PermissionInfoUnique; - public int MyPermissionInfoUnique // Absolutely Unique ID - Info - { get { return _MyPermissionInfoUnique; } } + private static int PermissionInfoUnique => ++_PermissionInfoUnique; + private readonly int _MyPermissionInfoUnique = PermissionInfoUnique; + // Absolutely Unique ID - Info + public int MyPermissionInfoUnique => _MyPermissionInfoUnique; protected PermissionInfo() {/* require use of factory methods */ AddToCache(this); @@ -246,15 +217,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~PermissionInfo() { _CountFinalized++; @@ -271,10 +238,7 @@ namespace VEPROMS.CSLA.Library if (listPermissionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(PID.ToString()); // remove the list } - public virtual Permission Get() - { - return _Editable = Permission.Get(_PID); - } + public virtual Permission Get() => _Editable = Permission.Get(_PID); public static void Refresh(Permission tmp) { string key = tmp.PID.ToString(); @@ -287,11 +251,11 @@ namespace VEPROMS.CSLA.Library { if (_RID != tmp.RID) { - if (MyRole != null) MyRole.RefreshRolePermissions(); // Update List for old value + MyRole?.RefreshRolePermissions(); // Update List for old value _RID = tmp.RID; // Update the value } _MyRole = null; // Reset list so that the next line gets a new list - if (MyRole != null) MyRole.RefreshRolePermissions(); // Update List for new value + MyRole?.RefreshRolePermissions(); // Update List for new value _PermLevel = tmp.PermLevel; _VersionType = tmp.VersionType; _PermValue = tmp.PermValue; @@ -328,8 +292,6 @@ namespace VEPROMS.CSLA.Library } public static PermissionInfo Get(int pid) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Permission"); try { PermissionInfo tmp = GetCachedByPrimaryKey(pid); @@ -368,13 +330,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _PID; - public int PID - { get { return _PID; } } - public PKCriteria(int pid) - { - _PID = pid; - } + private readonly int _PID; + public int PID => _PID; + public PKCriteria(int pid) => _PID = pid; } private void ReadData(SafeDataReader dr) { @@ -439,7 +397,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - PermissionInfoExtension _PermissionInfoExtension = new PermissionInfoExtension(); + readonly PermissionInfoExtension _PermissionInfoExtension = new PermissionInfoExtension(); [Serializable()] partial class PermissionInfoExtension : extensionBase { } [Serializable()] @@ -455,10 +413,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PermissionInfo) + if (destType == typeof(string) && value is PermissionInfo info) { // Return the ToString value - return ((PermissionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfoList.cs index 58bf8712..5e8b7e10 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PermissionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (PermissionInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~PermissionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~PermissionInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on PermissionInfoList.Get", ex); } } - /// - /// Reset the list of all PermissionInfo. - /// - public static void Reset() - { - _PermissionInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static PermissionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on PermissionInfoList.Get", ex); - // } - //} - public static PermissionInfoList GetByRID(int rid) + /// + /// Reset the list of all PermissionInfo. + /// + public static void Reset() => _PermissionInfoList = null; + public static PermissionInfoList GetByRID(int rid) { try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PermissionInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -150,7 +128,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PermissionInfo(dr)); + while (dr.Read()) Add(new PermissionInfo(dr)); IsReadOnly = true; } } @@ -161,16 +139,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PermissionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("PermissionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class RIDCriteria { - public RIDCriteria(int rid) - { - _RID = rid; - } - private int _RID; + public RIDCriteria(int rid) => _RID = rid; + private int _RID; public int RID { get { return _RID; } @@ -179,7 +154,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] PermissionInfoList.DataPortal_FetchRID", GetHashCode()); try { @@ -194,7 +169,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new PermissionInfo(dr)); + while (dr.Read()) Add(new PermissionInfo(dr)); IsReadOnly = true; } } @@ -205,48 +180,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("PermissionInfoList.DataPortal_FetchRID", ex); throw new DbCslaException("PermissionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection PermissionInfoListPropertyDescriptor pd = new PermissionInfoListPropertyDescriptor(this, i); @@ -263,7 +227,6 @@ namespace VEPROMS.CSLA.Library /// public partial class PermissionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private PermissionInfo Item { get { return (PermissionInfo)_Item; } } public PermissionInfoListPropertyDescriptor(PermissionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -272,10 +235,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is PermissionInfoList) + if (destType == typeof(string) && value is PermissionInfoList list) { // Return department and department role separated by comma. - return ((PermissionInfoList)value).Items.Count.ToString() + " Permissions"; + return $"{list.Items.Count} Permissions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/PropertyDescriptor.cs b/PROMS/VEPROMS.CSLA.Library/Generated/PropertyDescriptor.cs index a087661f..1917ace7 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/PropertyDescriptor.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/PropertyDescriptor.cs @@ -9,12 +9,6 @@ // ======================================================================== using System; -using System.Data; -using System.Data.SqlClient; -using Csla; -using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using Csla.Validation; namespace VEPROMS.CSLA.Library @@ -29,225 +23,23 @@ namespace VEPROMS.CSLA.Library public vlnListPropertyDescriptor(System.Collections.IList collection, int index) : base("#" + index.ToString(), null) { _Item = collection[index]; } - public override bool CanResetValue(object component) - { return true; } - public override Type ComponentType - { get { return _Item.GetType(); } } - public override object GetValue(object component) - { return _Item; } - public override bool IsReadOnly - { get { return false; } } - public override Type PropertyType - { get { return _Item.GetType(); } } - public override void ResetValue(object component) + public override bool CanResetValue(object component) => true; + public override Type ComponentType => _Item.GetType(); + public override object GetValue(object component) => _Item; + public override bool IsReadOnly => false; + public override Type PropertyType => _Item.GetType(); + public override void ResetValue(object component) { ;} - public override bool ShouldSerializeValue(object component) - { return true; } - public override void SetValue(object component, object value) + public override bool ShouldSerializeValue(object component) => true; + public override void SetValue(object component, object value) { /*_Item = value*/;} - //public override AttributeCollection Attributes - //{ get { return new AttributeCollection(null); } } - public override string DisplayName - { get { return _Item.ToString(); } } - public override string Description - { get { return _Item.ToString(); } } - public override string Name - { get { return _Item.ToString(); } } - } // Class + public override string DisplayName => _Item.ToString(); + public override string Description => _Item.ToString(); + public override string Name => _Item.ToString(); + } // Class public interface IVEHasBrokenRules { IVEHasBrokenRules HasBrokenRules { get; } BrokenRulesCollection BrokenRules { get; } } } // Namespace -// The following are samples of ToString overrides -// public partial class Annotation -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class AnnotationInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class AnnotationType -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class AnnotationTypeAnnotation -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class AnnotationTypeInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Assignment -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class AssignmentInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Association -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class AssociationInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Connection -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ConnectionFolder -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ConnectionInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Content -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ContentDetail -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ContentItem -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ContentPart -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ContentRoUsage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ContentTransition -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ContentInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Detail -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DetailInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Document -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocumentDROUsage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocumentEntry -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocumentPdf -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocumentInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocVersion -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocVersionAssociation -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DocVersionInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DROUsage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class DROUsageInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Entry -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class EntryInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Figure -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FigureInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Folder -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FolderAssignment -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FolderDocVersion -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FolderInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Format -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FormatContent -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FormatDocVersion -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FormatFolder -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class FormatInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Grid -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class GridInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Group -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class GroupAssignment -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class GroupMembership -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class GroupInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Image -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ImageInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Item -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ItemAnnotation -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ItemDocVersion -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ItemPart -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ItemTransition_RangeID -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ItemTransition_ToID -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ItemInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Membership -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class MembershipInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Part -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class PartInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Pdf -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class PdfInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Permission -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class PermissionInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RODb -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RODbDROUsage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RODbROFst -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RODbROImage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RODbRoUsage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RODbInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROFst -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROFstAssociation -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROFstFigure -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROFstInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROImage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROImageFigure -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ROImageInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Role -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RoleAssignment -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RolePermission -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RoleInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RoUsage -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class RoUsageInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class Transition -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class TransitionInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class User -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class UserMembership -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class UserInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ZContent -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ZContentInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ZTransition -// { public override string ToString() { return string.Format("{0}", _Name); } } -// public partial class ZTransitionInfo -// { public override string ToString() { return string.Format("{0}", _Name); } } \ No newline at end of file diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODb.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODb.cs index 5ffab757..f6fbe1e1 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODb.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODb.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -108,6 +106,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(RODb rODb) { @@ -117,7 +116,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(rODb)) _CacheList.Remove(rODb); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByFolderPath = new Dictionary>(); private static void ConvertListToDictionary() { @@ -152,15 +153,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextRODbID = -1; - public static int NextRODbID - { - get { return _nextRODbID--; } - } + public static int NextRODbID => _nextRODbID--; private int _RODbID; [System.ComponentModel.DataObjectField(true, true)] public int RODbID @@ -325,10 +320,7 @@ namespace VEPROMS.CSLA.Library return _RODbDROUsages; } } - public void Reset_RODbDROUsages() - { - _RODbDROUsageCount = -1; - } + public void Reset_RODbDROUsages() => _RODbDROUsageCount = -1; private int _RODbROFstCount = 0; /// /// Count of RODbROFsts for this RODb @@ -360,10 +352,7 @@ namespace VEPROMS.CSLA.Library return _RODbROFsts; } } - public void Reset_RODbROFsts() - { - _RODbROFstCount = -1; - } + public void Reset_RODbROFsts() => _RODbROFstCount = -1; private int _RODbROImageCount = 0; /// /// Count of RODbROImages for this RODb @@ -395,10 +384,7 @@ namespace VEPROMS.CSLA.Library return _RODbROImages; } } - public void Reset_RODbROImages() - { - _RODbROImageCount = -1; - } + public void Reset_RODbROImages() => _RODbROImageCount = -1; private int _RODbRoUsageCount = 0; /// /// Count of RODbRoUsages for this RODb @@ -430,10 +416,7 @@ namespace VEPROMS.CSLA.Library return _RODbRoUsages; } } - public void Reset_RODbRoUsages() - { - _RODbRoUsageCount = -1; - } + public void Reset_RODbRoUsages() => _RODbRoUsageCount = -1; public override bool IsDirty { get @@ -448,37 +431,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_RODbDROUsages == null ? false : _RODbDROUsages.IsDirtyList(list)) || (_RODbROFsts == null ? false : _RODbROFsts.IsDirtyList(list)) || (_RODbROImages == null ? false : _RODbROImages.IsDirtyList(list)) || (_RODbRoUsages == null ? false : _RODbRoUsages.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_RODbDROUsages != null && _RODbDROUsages.IsDirtyList(list)) || (_RODbROFsts != null && _RODbROFsts.IsDirtyList(list)) || (_RODbROImages != null && _RODbROImages.IsDirtyList(list)) || (_RODbRoUsages != null && _RODbRoUsages.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_RODbDROUsages == null ? true : _RODbDROUsages.IsValidList(list)) && (_RODbROFsts == null ? true : _RODbROFsts.IsValidList(list)) && (_RODbROImages == null ? true : _RODbROImages.IsValidList(list)) && (_RODbRoUsages == null ? true : _RODbRoUsages.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_RODbDROUsages == null || _RODbDROUsages.IsValidList(list)) && (_RODbROFsts == null || _RODbROFsts.IsValidList(list)) && (_RODbROImages == null || _RODbROImages.IsValidList(list)) && (_RODbRoUsages == null || _RODbRoUsages.IsValidList(list)); } - // CSLATODO: Replace base RODb.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RODb - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check RODb.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RODb - protected override object GetIdValue() - { - return MyRODbUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRODbUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -510,8 +478,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -548,35 +516,11 @@ namespace VEPROMS.CSLA.Library _RODbExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowRead(ROName, ""); - //AuthorizationRules.AllowRead(FolderPath, ""); - //AuthorizationRules.AllowRead(DBConnectionString, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ROName, ""); - //AuthorizationRules.AllowWrite(FolderPath, ""); - //AuthorizationRules.AllowWrite(DBConnectionString, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _RODbExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -584,58 +528,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _RODbExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _RODbDROUsageCount; - usedByCount += _RODbROFstCount; - usedByCount += _RODbROImageCount; - usedByCount += _RODbRoUsageCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RODbUnique = 0; - protected static int RODbUnique - { get { return ++_RODbUnique; } } - private int _MyRODbUnique = RODbUnique; - public int MyRODbUnique // Absolutely Unique ID - Editable - { get { return _MyRODbUnique; } } + protected static int RODbUnique => ++_RODbUnique; + private readonly int _MyRODbUnique = RODbUnique; + // Absolutely Unique ID - Editable + public int MyRODbUnique => _MyRODbUnique; protected RODb() {/* require use of factory methods */ AddToCache(this); @@ -644,15 +544,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RODb() { _CountFinalized++; @@ -689,8 +585,6 @@ namespace VEPROMS.CSLA.Library } public static RODb New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a RODb"); try { return DataPortal.Create(); @@ -762,8 +656,6 @@ namespace VEPROMS.CSLA.Library } public static RODb Get(int rODbID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a RODb"); try { RODb tmp = GetCachedByPrimaryKey(rODbID); @@ -786,8 +678,6 @@ namespace VEPROMS.CSLA.Library } public static RODb GetByFolderPath(string folderPath) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a RODb"); try { RODb tmp = GetCachedByFolderPath(folderPath); @@ -813,14 +703,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new RODb(dr); return null; } - internal RODb(SafeDataReader dr) - { - ReadData(dr); - } + internal RODb(SafeDataReader dr) => ReadData(dr); public static void Delete(int rODbID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a RODb"); try { DataPortal.Delete(new PKCriteria(rODbID)); @@ -832,12 +717,6 @@ namespace VEPROMS.CSLA.Library } public override RODb Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a RODb"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a RODb"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a RODb"); try { BuildRefreshList(); @@ -857,24 +736,16 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _RODbID; - public int RODbID - { get { return _RODbID; } } - public PKCriteria(int rODbID) - { - _RODbID = rODbID; - } + private readonly int _RODbID; + public int RODbID => _RODbID; + public PKCriteria(int rODbID) => _RODbID = rODbID; } [Serializable()] private class FolderPathCriteria { - private string _FolderPath; - public string FolderPath - { get { return _FolderPath; } } - public FolderPathCriteria(string folderPath) - { - _FolderPath = folderPath; - } + private readonly string _FolderPath; + public string FolderPath => _FolderPath; + public FolderPathCriteria(string folderPath) => _FolderPath = folderPath; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -997,7 +868,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RODb.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -1022,44 +893,52 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addRODb"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ROName", _ROName); - cm.Parameters.AddWithValue("@FolderPath", _FolderPath); - cm.Parameters.AddWithValue("@DBConnectionString", _DBConnectionString); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_RODbID = new SqlParameter("@newRODbID", SqlDbType.Int); - param_RODbID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_RODbID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _RODbID = (int)cm.Parameters["@newRODbID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addRODb"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ROName", _ROName); + cm.Parameters.AddWithValue("@FolderPath", _FolderPath); + cm.Parameters.AddWithValue("@DBConnectionString", _DBConnectionString); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_RODbID = new SqlParameter("@newRODbID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_RODbID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _RODbID = (int)cm.Parameters["@newRODbID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_RODbRoUsages != null) _RODbRoUsages.Update(this); - if (_RODbDROUsages != null) _RODbDROUsages.Update(this); - if (_RODbROFsts != null) _RODbROFsts.Update(this); - if (_RODbROImages != null) _RODbROImages.Update(this); + _RODbRoUsages?.Update(this); + _RODbDROUsages?.Update(this); + _RODbROFsts?.Update(this); + _RODbROImages?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -1069,7 +948,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RODb.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int rODbID, string rOName, string folderPath, string dBConnectionString, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.Add", 0); @@ -1088,11 +967,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_RODbID = new SqlParameter("@newRODbID", SqlDbType.Int); - param_RODbID.Direction = ParameterDirection.Output; + SqlParameter param_RODbID = new SqlParameter("@newRODbID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_RODbID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1107,7 +990,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RODb.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1130,46 +1013,52 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateRODb"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@RODbID", _RODbID); - cm.Parameters.AddWithValue("@ROName", _ROName); - cm.Parameters.AddWithValue("@FolderPath", _FolderPath); - cm.Parameters.AddWithValue("@DBConnectionString", _DBConnectionString); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateRODb"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@RODbID", _RODbID); + cm.Parameters.AddWithValue("@ROName", _ROName); + cm.Parameters.AddWithValue("@FolderPath", _FolderPath); + cm.Parameters.AddWithValue("@DBConnectionString", _DBConnectionString); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_RODbRoUsages != null) _RODbRoUsages.Update(this); - if (_RODbDROUsages != null) _RODbDROUsages.Update(this); - if (_RODbROFsts != null) _RODbROFsts.Update(this); - if (_RODbROImages != null) _RODbROImages.Update(this); + _RODbRoUsages?.Update(this); + _RODbDROUsages?.Update(this); + _RODbROFsts?.Update(this); + _RODbROImages?.Update(this); } catch (Exception ex) { @@ -1180,22 +1069,26 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = RODb.Add(cn, ref _RODbID, _ROName, _FolderPath, _DBConnectionString, _Config, _DTS, _UserID); - else - _LastChanged = RODb.Update(cn, ref _RODbID, _ROName, _FolderPath, _DBConnectionString, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = RODb.Add(cn, ref _RODbID, _ROName, _FolderPath, _DBConnectionString, _Config, _DTS, _UserID); + else + _LastChanged = RODb.Update(cn, ref _RODbID, _ROName, _FolderPath, _DBConnectionString, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_RODbRoUsages != null) _RODbRoUsages.Update(this); - if (_RODbDROUsages != null) _RODbDROUsages.Update(this); - if (_RODbROFsts != null) _RODbROFsts.Update(this); - if (_RODbROImages != null) _RODbROImages.Update(this); + _RODbRoUsages?.Update(this); + _RODbDROUsages?.Update(this); + _RODbROFsts?.Update(this); + _RODbROImages?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int rODbID, string rOName, string folderPath, string dBConnectionString, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.Update", 0); @@ -1216,8 +1109,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1231,12 +1126,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RODb.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_RODbID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.DataPortal_Delete", GetHashCode()); @@ -1261,7 +1156,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RODb.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int rODbID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.Remove", 0); @@ -1302,16 +1197,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _RODbID; + private readonly int _RODbID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int rODbID) - { - _RODbID = rODbID; - } + public bool Exists => _exists; + public ExistsCommand(int rODbID) => _RODbID = rODbID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.DataPortal_Execute", GetHashCode()); @@ -1319,7 +1208,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1327,7 +1216,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsRODb"; cm.Parameters.AddWithValue("@RODbID", _RODbID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1341,7 +1230,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - RODbExtension _RODbExtension = new RODbExtension(); + readonly RODbExtension _RODbExtension = new RODbExtension(); [Serializable()] partial class RODbExtension : extensionBase { @@ -1350,14 +1239,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1386,57 +1269,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODb) + if (destType == typeof(string) && value is RODb db) { // Return the ToString value - return ((RODb)value).ToString(); + return db.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RODbExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RODb -// { -// partial class RODbExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsage.cs index a49b9cfe..1c13214f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsage.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _DROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int DROUsageID @@ -238,19 +232,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RODbDROUsage - protected override object GetIdValue() - { - return MyRODbDROUsageUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RODbDROUsage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RODbDROUsage - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyRODbDROUsageUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -265,18 +247,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyDocument != null && _MyDocument.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocument == null || _MyDocument.IsValidList(list)); } #endregion #region ValidationRules @@ -306,8 +285,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -337,78 +316,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(DROUsageID, ""); - //AuthorizationRules.AllowRead(DocID, ""); - //AuthorizationRules.AllowWrite(DocID, ""); - //AuthorizationRules.AllowRead(ROID, ""); - //AuthorizationRules.AllowWrite(ROID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RODbDROUsageUnique = 0; - private static int RODbDROUsageUnique - { get { return ++_RODbDROUsageUnique; } } - private int _MyRODbDROUsageUnique = RODbDROUsageUnique; - public int MyRODbDROUsageUnique // Absolutely Unique ID - Editable FK - { get { return _MyRODbDROUsageUnique; } } - internal static RODbDROUsage New(string roid) - { - return new RODbDROUsage(roid); - } - internal static RODbDROUsage Get(SafeDataReader dr) - { - return new RODbDROUsage(dr); - } + private static int RODbDROUsageUnique => ++_RODbDROUsageUnique; + private readonly int _MyRODbDROUsageUnique = RODbDROUsageUnique; + // Absolutely Unique ID - Editable FK + public int MyRODbDROUsageUnique => _MyRODbDROUsageUnique; + internal static RODbDROUsage New(string roid) => new RODbDROUsage(roid); + internal static RODbDROUsage Get(SafeDataReader dr) => new RODbDROUsage(dr); public RODbDROUsage() { MarkAsChild(); @@ -438,15 +361,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RODbDROUsage() { _CountFinalized++; @@ -489,33 +408,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DROUsage.Add(cn, ref _DROUsageID, _MyDocument, _ROID, _Config, _DTS, _UserID, myRODb); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DROUsage.Add(cn, ref _DROUsageID, _MyDocument, _ROID, _Config, _DTS, _UserID, myRODb); + } + MarkOld(); } internal void Update(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = DROUsage.Update(cn, ref _DROUsageID, _DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, myRODb.RODbID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = DROUsage.Update(cn, ref _DROUsageID, _DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, myRODb.RODbID); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - DROUsage.Remove(cn, _DROUsageID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + DROUsage.Remove(cn, _DROUsageID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RODbDROUsageExtension _RODbDROUsageExtension = new RODbDROUsageExtension(); + readonly RODbDROUsageExtension _RODbDROUsageExtension = new RODbDROUsageExtension(); [Serializable()] partial class RODbDROUsageExtension : extensionBase { @@ -524,18 +456,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultDocID - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultDocID => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -564,61 +487,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbDROUsage) + if (destType == typeof(string) && value is RODbDROUsage usage) { // Return the ToString value - return ((RODbDROUsage)value).ToString(); + return usage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RODbDROUsageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RODbDROUsage -// { -// partial class RODbDROUsageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultDocID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsages.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsages.cs index b0c47e23..9d744aca 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsages.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbDROUsages.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RODbDROUsage this[DROUsage myDROUsage] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RODbDROUsage this[DROUsage myDROUsage] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RODbDROUsage GetItem(DROUsage myDROUsage) + public new System.Collections.Generic.IList Items => base.Items; + public RODbDROUsage GetItem(DROUsage myDROUsage) { foreach (RODbDROUsage dROUsage in this) if (dROUsage.DROUsageID == myDROUsage.DROUsageID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RODbDROUsage Add(string roid) // One to Many { RODbDROUsage dROUsage = RODbDROUsage.New(roid); - this.Add(dROUsage); + Add(dROUsage); return dROUsage; } public void Remove(DROUsage myDROUsage) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RODbDROUsage child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RODbDROUsage child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RODbDROUsages New() - { - return new RODbDROUsages(); - } - internal static RODbDROUsages Get(SafeDataReader dr) - { - return new RODbDROUsages(dr); - } - public static RODbDROUsages GetByRODbID(int rODbID) + #endregion + #region Factory Methods + internal static RODbDROUsages New() => new RODbDROUsages(); + internal static RODbDROUsages Get(SafeDataReader dr) => new RODbDROUsages(dr); + public static RODbDROUsages GetByRODbID(int rODbID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RODbDROUsages.GetByRODbID", ex); } } - private RODbDROUsages() - { - MarkAsChild(); - } - internal RODbDROUsages(SafeDataReader dr) + private RODbDROUsages() => MarkAsChild(); + internal RODbDROUsages(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RODbDROUsages() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RODbDROUsages() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RODbDROUsage.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RODbDROUsage.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODbDROUsages.DataPortal_FetchRODbID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RODbDROUsage(dr)); + while (dr.Read()) Add(new RODbDROUsage(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RODbDROUsages.DataPortal_FetchRODbID", ex); throw new DbCslaException("RODbDROUsages.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(RODb rODb) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RODbDROUsagesPropertyDescriptor pd = new RODbDROUsagesPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RODbDROUsagesPropertyDescriptor : vlnListPropertyDescriptor { - private RODbDROUsage Item { get { return (RODbDROUsage)_Item; } } public RODbDROUsagesPropertyDescriptor(RODbDROUsages collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbDROUsages) + if (destType == typeof(string) && value is RODbDROUsages usages) { // Return department and department role separated by comma. - return ((RODbDROUsages)value).Items.Count.ToString() + " DROUsages"; + return $"{usages.Items.Count} DROUsages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfo.cs index 2f0fc1b8..89042367 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class RODbInfo : ReadOnlyBase, IDisposable { public event RODbInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(RODbInfo rODbInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(rODbInfo)) _CacheList.Remove(rODbInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected RODb _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _RODbID; [System.ComponentModel.DataObjectField(true, true)] public int RODbID @@ -306,32 +290,19 @@ namespace VEPROMS.CSLA.Library foreach (RODbInfo tmp in _CacheByPrimaryKey[_RODbID.ToString()]) tmp._RODbRoUsageCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base RODbInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RODbInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check RODbInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RODbInfo - protected override object GetIdValue() - { - return MyRODbInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRODbInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _RODbInfoUnique = 0; - private static int RODbInfoUnique - { get { return ++_RODbInfoUnique; } } - private int _MyRODbInfoUnique = RODbInfoUnique; - public int MyRODbInfoUnique // Absolutely Unique ID - Info - { get { return _MyRODbInfoUnique; } } + private static int RODbInfoUnique => ++_RODbInfoUnique; + private readonly int _MyRODbInfoUnique = RODbInfoUnique; + // Absolutely Unique ID - Info + public int MyRODbInfoUnique => _MyRODbInfoUnique; protected RODbInfo() {/* require use of factory methods */ AddToCache(this); @@ -340,15 +311,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RODbInfo() { _CountFinalized++; @@ -365,10 +332,7 @@ namespace VEPROMS.CSLA.Library if (listRODbInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(RODbID.ToString()); // remove the list } - public virtual RODb Get() - { - return _Editable = RODb.Get(_RODbID); - } + public virtual RODb Get() => _Editable = RODb.Get(_RODbID); public static void Refresh(RODb tmp) { string key = tmp.RODbID.ToString(); @@ -390,8 +354,6 @@ namespace VEPROMS.CSLA.Library } public static RODbInfo Get(int rODbID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a RODb"); try { RODbInfo tmp = GetCachedByPrimaryKey(rODbID); @@ -430,13 +392,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _RODbID; - public int RODbID - { get { return _RODbID; } } - public PKCriteria(int rODbID) - { - _RODbID = rODbID; - } + private readonly int _RODbID; + public int RODbID => _RODbID; + public PKCriteria(int rODbID) => _RODbID = rODbID; } private void ReadData(SafeDataReader dr) { @@ -501,7 +459,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - RODbInfoExtension _RODbInfoExtension = new RODbInfoExtension(); + readonly RODbInfoExtension _RODbInfoExtension = new RODbInfoExtension(); [Serializable()] partial class RODbInfoExtension : extensionBase { } [Serializable()] @@ -517,10 +475,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbInfo) + if (destType == typeof(string) && value is RODbInfo info) { // Return the ToString value - return ((RODbInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfoList.cs index fe4949a4..1e99fbdc 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (RODbInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~RODbInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RODbInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RODbInfoList.Get", ex); } } - /// - /// Reset the list of all RODbInfo. - /// - public static void Reset() - { - _RODbInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static RODbInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on RODbInfoList.Get", ex); - // } - //} - private RODbInfoList() + /// + /// Reset the list of all RODbInfo. + /// + public static void Reset() => _RODbInfoList = null; + private RODbInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODbInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RODbInfo(dr)); + while (dr.Read()) Add(new RODbInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RODbInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RODbInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RODbInfoListPropertyDescriptor pd = new RODbInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RODbInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private RODbInfo Item { get { return (RODbInfo)_Item; } } public RODbInfoListPropertyDescriptor(RODbInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbInfoList) + if (destType == typeof(string) && value is RODbInfoList list) { // Return department and department role separated by comma. - return ((RODbInfoList)value).Items.Count.ToString() + " RODbs"; + return $"{list.Items.Count} RODbs"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFst.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFst.cs index 5ab70e94..de1d201d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFst.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFst.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ROFstID; [System.ComponentModel.DataObjectField(true, true)] public int ROFstID @@ -138,35 +132,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RODbROFst - protected override object GetIdValue() - { - return MyRODbROFstUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RODbROFst.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RODbROFst - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyRODbROFstUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -194,8 +166,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -210,76 +182,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ROFstID, ""); - //AuthorizationRules.AllowRead(ROLookup, ""); - //AuthorizationRules.AllowWrite(ROLookup, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RODbROFstUnique = 0; - private static int RODbROFstUnique - { get { return ++_RODbROFstUnique; } } - private int _MyRODbROFstUnique = RODbROFstUnique; - public int MyRODbROFstUnique // Absolutely Unique ID - Editable FK - { get { return _MyRODbROFstUnique; } } - internal static RODbROFst New(byte[] rOLookup) - { - return new RODbROFst(rOLookup); - } - internal static RODbROFst Get(SafeDataReader dr) - { - return new RODbROFst(dr); - } + private static int RODbROFstUnique => ++_RODbROFstUnique; + private readonly int _MyRODbROFstUnique = RODbROFstUnique; + // Absolutely Unique ID - Editable FK + public int MyRODbROFstUnique => _MyRODbROFstUnique; + internal static RODbROFst New(byte[] rOLookup) => new RODbROFst(rOLookup); + internal static RODbROFst Get(SafeDataReader dr) => new RODbROFst(dr); public RODbROFst() { MarkAsChild(); @@ -307,15 +225,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RODbROFst() { _CountFinalized++; @@ -350,33 +264,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = ROFst.Add(cn, ref _ROFstID, myRODb, _ROLookup, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = ROFst.Add(cn, ref _ROFstID, myRODb, _ROLookup, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = ROFst.Update(cn, ref _ROFstID, myRODb.RODbID, _ROLookup, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = ROFst.Update(cn, ref _ROFstID, myRODb.RODbID, _ROLookup, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - ROFst.Remove(cn, _ROFstID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + ROFst.Remove(cn, _ROFstID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RODbROFstExtension _RODbROFstExtension = new RODbROFstExtension(); + readonly RODbROFstExtension _RODbROFstExtension = new RODbROFstExtension(); [Serializable()] partial class RODbROFstExtension : extensionBase { @@ -385,14 +312,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -421,57 +342,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbROFst) + if (destType == typeof(string) && value is RODbROFst fst) { // Return the ToString value - return ((RODbROFst)value).ToString(); + return fst.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RODbROFstExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RODbROFst -// { -// partial class RODbROFstExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFsts.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFsts.cs index 6ae37450..b5acd815 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFsts.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROFsts.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RODbROFst this[ROFst myROFst] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RODbROFst this[ROFst myROFst] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RODbROFst GetItem(ROFst myROFst) + public new System.Collections.Generic.IList Items => base.Items; + public RODbROFst GetItem(ROFst myROFst) { foreach (RODbROFst rOFst in this) if (rOFst.ROFstID == myROFst.ROFstID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RODbROFst Add(byte[] rOLookup) // One to Many { RODbROFst rOFst = RODbROFst.New(rOLookup); - this.Add(rOFst); + Add(rOFst); return rOFst; } public void Remove(ROFst myROFst) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RODbROFst child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RODbROFst child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(DateTime dts) { foreach (RODbROFst rOFst in this) @@ -151,20 +140,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RODbROFsts New() - { - return new RODbROFsts(); - } - internal static RODbROFsts Get(SafeDataReader dr) - { - return new RODbROFsts(dr); - } - public static RODbROFsts GetByRODbID(int rODbID) + #endregion + #region Factory Methods + internal static RODbROFsts New() => new RODbROFsts(); + internal static RODbROFsts Get(SafeDataReader dr) => new RODbROFsts(dr); + public static RODbROFsts GetByRODbID(int rODbID) { try { @@ -175,11 +158,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RODbROFsts.GetByRODbID", ex); } } - private RODbROFsts() - { - MarkAsChild(); - } - internal RODbROFsts(SafeDataReader dr) + private RODbROFsts() => MarkAsChild(); + internal RODbROFsts(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -188,16 +168,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RODbROFsts() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RODbROFsts() { _CountFinalized++; } @@ -212,19 +188,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RODbROFst.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RODbROFst.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODbROFsts.DataPortal_FetchRODbID", GetHashCode()); try { @@ -247,7 +220,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RODbROFst(dr)); + while (dr.Read()) Add(new RODbROFst(dr)); } } } @@ -257,11 +230,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RODbROFsts.DataPortal_FetchRODbID", ex); throw new DbCslaException("RODbROFsts.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(RODb rODb) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -280,49 +253,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RODbROFstsPropertyDescriptor pd = new RODbROFstsPropertyDescriptor(this, i); @@ -339,7 +301,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RODbROFstsPropertyDescriptor : vlnListPropertyDescriptor { - private RODbROFst Item { get { return (RODbROFst)_Item; } } public RODbROFstsPropertyDescriptor(RODbROFsts collection, int index) : base(collection, index) { ;} } #endregion @@ -348,10 +309,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbROFsts) + if (destType == typeof(string) && value is RODbROFsts fsts) { // Return department and department role separated by comma. - return ((RODbROFsts)value).Items.Count.ToString() + " ROFsts"; + return $"{fsts.Items.Count} ROFsts"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImage.cs index 3107a9e3..9c9785ed 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImage.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ImageID; [System.ComponentModel.DataObjectField(true, true)] public int ImageID @@ -157,35 +151,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RODbROImage - protected override object GetIdValue() - { - return MyRODbROImageUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RODbROImage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RODbROImage - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyRODbROImageUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -213,8 +185,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -234,78 +206,22 @@ namespace VEPROMS.CSLA.Library new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ImageID, ""); - //AuthorizationRules.AllowRead(FileName, ""); - //AuthorizationRules.AllowWrite(FileName, ""); - //AuthorizationRules.AllowRead(Content, ""); - //AuthorizationRules.AllowWrite(Content, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RODbROImageUnique = 0; - private static int RODbROImageUnique - { get { return ++_RODbROImageUnique; } } - private int _MyRODbROImageUnique = RODbROImageUnique; - public int MyRODbROImageUnique // Absolutely Unique ID - Editable FK - { get { return _MyRODbROImageUnique; } } - internal static RODbROImage New(string fileName, byte[] content) - { - return new RODbROImage(fileName, content); - } - internal static RODbROImage Get(SafeDataReader dr) - { - return new RODbROImage(dr); - } + private static int RODbROImageUnique => ++_RODbROImageUnique; + private readonly int _MyRODbROImageUnique = RODbROImageUnique; + // Absolutely Unique ID - Editable FK + public int MyRODbROImageUnique => _MyRODbROImageUnique; + internal static RODbROImage New(string fileName, byte[] content) => new RODbROImage(fileName, content); + internal static RODbROImage Get(SafeDataReader dr) => new RODbROImage(dr); public RODbROImage() { MarkAsChild(); @@ -334,15 +250,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RODbROImage() { _CountFinalized++; @@ -378,33 +290,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = ROImage.Add(cn, ref _ImageID, myRODb, _FileName, _Content, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = ROImage.Add(cn, ref _ImageID, myRODb, _FileName, _Content, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = ROImage.Update(cn, ref _ImageID, myRODb.RODbID, _FileName, _Content, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = ROImage.Update(cn, ref _ImageID, myRODb.RODbID, _FileName, _Content, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - ROImage.Remove(cn, _ImageID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + ROImage.Remove(cn, _ImageID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RODbROImageExtension _RODbROImageExtension = new RODbROImageExtension(); + readonly RODbROImageExtension _RODbROImageExtension = new RODbROImageExtension(); [Serializable()] partial class RODbROImageExtension : extensionBase { @@ -413,14 +338,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -449,57 +368,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbROImage) + if (destType == typeof(string) && value is RODbROImage image) { // Return the ToString value - return ((RODbROImage)value).ToString(); + return image.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RODbROImageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RODbROImage -// { -// partial class RODbROImageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImages.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImages.cs index e7fe25fe..d2bff599 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImages.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbROImages.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RODbROImage this[ROImage myROImage] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RODbROImage this[ROImage myROImage] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RODbROImage GetItem(ROImage myROImage) + public new System.Collections.Generic.IList Items => base.Items; + public RODbROImage GetItem(ROImage myROImage) { foreach (RODbROImage rOImage in this) if (rOImage.ImageID == myROImage.ImageID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RODbROImage Add(string fileName, byte[] content) // One to Many { RODbROImage rOImage = RODbROImage.New(fileName, content); - this.Add(rOImage); + Add(rOImage); return rOImage; } public void Remove(ROImage myROImage) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RODbROImage child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RODbROImage child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(string fileName, DateTime dts) { foreach (RODbROImage rOImage in this) @@ -151,20 +140,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RODbROImages New() - { - return new RODbROImages(); - } - internal static RODbROImages Get(SafeDataReader dr) - { - return new RODbROImages(dr); - } - public static RODbROImages GetByRODbID(int rODbID) + #endregion + #region Factory Methods + internal static RODbROImages New() => new RODbROImages(); + internal static RODbROImages Get(SafeDataReader dr) => new RODbROImages(dr); + public static RODbROImages GetByRODbID(int rODbID) { try { @@ -175,11 +158,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RODbROImages.GetByRODbID", ex); } } - private RODbROImages() - { - MarkAsChild(); - } - internal RODbROImages(SafeDataReader dr) + private RODbROImages() => MarkAsChild(); + internal RODbROImages(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -188,16 +168,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RODbROImages() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RODbROImages() { _CountFinalized++; } @@ -212,19 +188,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RODbROImage.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RODbROImage.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODbROImages.DataPortal_FetchRODbID", GetHashCode()); try { @@ -247,7 +220,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RODbROImage(dr)); + while (dr.Read()) Add(new RODbROImage(dr)); } } } @@ -257,11 +230,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RODbROImages.DataPortal_FetchRODbID", ex); throw new DbCslaException("RODbROImages.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(RODb rODb) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -280,49 +253,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RODbROImagesPropertyDescriptor pd = new RODbROImagesPropertyDescriptor(this, i); @@ -339,7 +301,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RODbROImagesPropertyDescriptor : vlnListPropertyDescriptor { - private RODbROImage Item { get { return (RODbROImage)_Item; } } public RODbROImagesPropertyDescriptor(RODbROImages collection, int index) : base(collection, index) { ;} } #endregion @@ -348,10 +309,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbROImages) + if (destType == typeof(string) && value is RODbROImages images) { // Return department and department role separated by comma. - return ((RODbROImages)value).Items.Count.ToString() + " ROImages"; + return $"{images.Items.Count} ROImages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsage.cs index 3ea92f4e..aba547fe 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsage.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _ROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int ROUsageID @@ -238,19 +232,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RODbRoUsage - protected override object GetIdValue() - { - return MyRODbRoUsageUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RODbRoUsage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RODbRoUsage - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyRODbRoUsageUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -265,18 +247,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)); } #endregion #region ValidationRules @@ -306,8 +285,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -337,78 +316,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ROUsageID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowRead(ROID, ""); - //AuthorizationRules.AllowWrite(ROID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RODbRoUsageUnique = 0; - private static int RODbRoUsageUnique - { get { return ++_RODbRoUsageUnique; } } - private int _MyRODbRoUsageUnique = RODbRoUsageUnique; - public int MyRODbRoUsageUnique // Absolutely Unique ID - Editable FK - { get { return _MyRODbRoUsageUnique; } } - internal static RODbRoUsage New(string roid) - { - return new RODbRoUsage(roid); - } - internal static RODbRoUsage Get(SafeDataReader dr) - { - return new RODbRoUsage(dr); - } + private static int RODbRoUsageUnique => ++_RODbRoUsageUnique; + private readonly int _MyRODbRoUsageUnique = RODbRoUsageUnique; + // Absolutely Unique ID - Editable FK + public int MyRODbRoUsageUnique => _MyRODbRoUsageUnique; + internal static RODbRoUsage New(string roid) => new RODbRoUsage(roid); + internal static RODbRoUsage Get(SafeDataReader dr) => new RODbRoUsage(dr); public RODbRoUsage() { MarkAsChild(); @@ -438,15 +361,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RODbRoUsage() { _CountFinalized++; @@ -489,33 +408,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = RoUsage.Add(cn, ref _ROUsageID, _MyContent, _ROID, _Config, _DTS, _UserID, myRODb); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = RoUsage.Add(cn, ref _ROUsageID, _MyContent, _ROID, _Config, _DTS, _UserID, myRODb); + } + MarkOld(); } internal void Update(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = RoUsage.Update(cn, ref _ROUsageID, _ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, myRODb.RODbID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = RoUsage.Update(cn, ref _ROUsageID, _ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, myRODb.RODbID); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(RODb myRODb) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - RoUsage.Remove(cn, _ROUsageID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + RoUsage.Remove(cn, _ROUsageID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RODbRoUsageExtension _RODbRoUsageExtension = new RODbRoUsageExtension(); + readonly RODbRoUsageExtension _RODbRoUsageExtension = new RODbRoUsageExtension(); [Serializable()] partial class RODbRoUsageExtension : extensionBase { @@ -524,18 +456,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultContentID - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultContentID => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -564,61 +487,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbRoUsage) + if (destType == typeof(string) && value is RODbRoUsage usage) { // Return the ToString value - return ((RODbRoUsage)value).ToString(); + return usage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RODbRoUsageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RODbRoUsage -// { -// partial class RODbRoUsageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultContentID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsages.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsages.cs index 51f120b4..224cf377 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsages.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RODbRoUsages.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RODbRoUsage this[RoUsage myRoUsage] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RODbRoUsage this[RoUsage myRoUsage] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RODbRoUsage GetItem(RoUsage myRoUsage) + public new System.Collections.Generic.IList Items => base.Items; + public RODbRoUsage GetItem(RoUsage myRoUsage) { foreach (RODbRoUsage roUsage in this) if (roUsage.ROUsageID == myRoUsage.ROUsageID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RODbRoUsage Add(string roid) // One to Many { RODbRoUsage roUsage = RODbRoUsage.New(roid); - this.Add(roUsage); + Add(roUsage); return roUsage; } public void Remove(RoUsage myRoUsage) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RODbRoUsage child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RODbRoUsage child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RODbRoUsages New() - { - return new RODbRoUsages(); - } - internal static RODbRoUsages Get(SafeDataReader dr) - { - return new RODbRoUsages(dr); - } - public static RODbRoUsages GetByRODbID(int rODbID) + #endregion + #region Factory Methods + internal static RODbRoUsages New() => new RODbRoUsages(); + internal static RODbRoUsages Get(SafeDataReader dr) => new RODbRoUsages(dr); + public static RODbRoUsages GetByRODbID(int rODbID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RODbRoUsages.GetByRODbID", ex); } } - private RODbRoUsages() - { - MarkAsChild(); - } - internal RODbRoUsages(SafeDataReader dr) + private RODbRoUsages() => MarkAsChild(); + internal RODbRoUsages(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RODbRoUsages() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RODbRoUsages() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RODbRoUsage.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RODbRoUsage.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODbRoUsages.DataPortal_FetchRODbID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RODbRoUsage(dr)); + while (dr.Read()) Add(new RODbRoUsage(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RODbRoUsages.DataPortal_FetchRODbID", ex); throw new DbCslaException("RODbRoUsages.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(RODb rODb) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RODbRoUsagesPropertyDescriptor pd = new RODbRoUsagesPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RODbRoUsagesPropertyDescriptor : vlnListPropertyDescriptor { - private RODbRoUsage Item { get { return (RODbRoUsage)_Item; } } public RODbRoUsagesPropertyDescriptor(RODbRoUsages collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RODbRoUsages) + if (destType == typeof(string) && value is RODbRoUsages usages) { // Return department and department role separated by comma. - return ((RODbRoUsages)value).Items.Count.ToString() + " RoUsages"; + return $"{usages.Items.Count} RoUsages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs index 33713bf3..6812ae24 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFst.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -85,7 +83,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Collection - + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ROFst rOFst) { @@ -100,7 +98,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(rOFst)) _CacheList.Remove(rOFst); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByRODbID_DTS = new Dictionary>(); private static void ConvertListToDictionary() { @@ -129,7 +129,7 @@ namespace VEPROMS.CSLA.Library protected static ROFst GetCachedByRODbID_DTS(int rODbID, DateTime dts) { ConvertListToDictionary(); - string key = rODbID.ToString() + "_" + dts.ToString(); + string key = $"{rODbID}_{dts}"; if (_CacheByRODbID_DTS.ContainsKey(key)) return _CacheByRODbID_DTS[key][0]; return null; } @@ -139,15 +139,9 @@ namespace VEPROMS.CSLA.Library #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextROFstID = -1; - public static int NextROFstID - { - get { return _nextROFstID--; } - } + public static int NextROFstID => _nextROFstID--; private int _ROFstID; [System.ComponentModel.DataObjectField(true, true)] public int ROFstID @@ -302,10 +296,7 @@ namespace VEPROMS.CSLA.Library return _ROFstAssociations; } } - public void Reset_ROFstAssociations() - { - _ROFstAssociationCount = -1; - } + public void Reset_ROFstAssociations() => _ROFstAssociationCount = -1; private int _ROFstFigureCount = 0; /// /// Count of ROFstFigures for this ROFst @@ -337,10 +328,7 @@ namespace VEPROMS.CSLA.Library return _ROFstFigures; } } - public void Reset_ROFstFigures() - { - _ROFstFigureCount = -1; - } + public void Reset_ROFstFigures() => _ROFstFigureCount = -1; public override bool IsDirty { get @@ -355,37 +343,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_ROFstAssociations == null ? false : _ROFstAssociations.IsDirtyList(list)) || (_ROFstFigures == null ? false : _ROFstFigures.IsDirtyList(list)) || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_ROFstAssociations != null && _ROFstAssociations.IsDirtyList(list)) || (_ROFstFigures != null && _ROFstFigures.IsDirtyList(list)) || (_MyRODb != null && _MyRODb.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_ROFstAssociations == null ? true : _ROFstAssociations.IsValidList(list)) && (_ROFstFigures == null ? true : _ROFstFigures.IsValidList(list)) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_ROFstAssociations == null || _ROFstAssociations.IsValidList(list)) && (_ROFstFigures == null || _ROFstFigures.IsValidList(list)) && (_MyRODb == null || _MyRODb.IsValidList(list)); } - // CSLATODO: Replace base ROFst.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROFst - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ROFst.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROFst - protected override object GetIdValue() - { - return MyROFstUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyROFstUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -416,8 +389,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -449,33 +422,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ROFstID, ""); - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowRead(ROLookup, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(RODbID, ""); - //AuthorizationRules.AllowWrite(ROLookup, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _ROFstExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -483,56 +434,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ROFstExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _ROFstAssociationCount; - usedByCount += _ROFstFigureCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ROFstUnique = 0; - protected static int ROFstUnique - { get { return ++_ROFstUnique; } } - private int _MyROFstUnique = ROFstUnique; - public int MyROFstUnique // Absolutely Unique ID - Editable - { get { return _MyROFstUnique; } } + protected static int ROFstUnique => ++_ROFstUnique; + private readonly int _MyROFstUnique = ROFstUnique; + // Absolutely Unique ID - Editable + public int MyROFstUnique => _MyROFstUnique; protected ROFst() {/* require use of factory methods */ AddToCache(this); @@ -541,15 +450,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROFst() { _CountFinalized++; @@ -588,8 +493,6 @@ namespace VEPROMS.CSLA.Library public static ROFst New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ROFst"); try { return DataPortal.Create(); @@ -640,7 +543,7 @@ namespace VEPROMS.CSLA.Library if (tmp.ROLookup != null && tmp.ROFstID > 0) { //Force Load the new Lookup Data - var RofstLookup = new ROFSTLookup(tmp.ROFstID); + _ = new ROFSTLookup(tmp.ROFstID); tmp.ROLookup = null; } } @@ -667,7 +570,7 @@ namespace VEPROMS.CSLA.Library // B2022-026 RO Memory reduction //Force Load the new Lookup Data - var RofstLookup = new ROFSTLookup(tmp.ROFstID); + _ = new ROFSTLookup(tmp.ROFstID); tmp.ROLookup = null; } else @@ -685,8 +588,6 @@ namespace VEPROMS.CSLA.Library public static ROFst Get(int rOFstID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ROFst"); try { ROFst tmp = GetCachedByPrimaryKey(rOFstID); @@ -712,8 +613,6 @@ namespace VEPROMS.CSLA.Library public static ROFst GetByRODbID_DTS(int rODbID, DateTime dts) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ROFst"); try { ROFst tmp = GetCachedByRODbID_DTS(rODbID, dts); @@ -739,14 +638,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new ROFst(dr); return null; } - internal ROFst(SafeDataReader dr) - { - ReadData(dr); - } + internal ROFst(SafeDataReader dr) => ReadData(dr); public static void Delete(int rOFstID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ROFst"); try { DataPortal.Delete(new PKCriteria(rOFstID)); @@ -758,12 +652,6 @@ namespace VEPROMS.CSLA.Library } public override ROFst Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ROFst"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ROFst"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ROFst"); try { BuildRefreshList(); @@ -784,23 +672,17 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - public PKCriteria(int rOFstID) - { - _ROFstID = rOFstID; - } + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + public PKCriteria(int rOFstID) => _ROFstID = rOFstID; } [Serializable()] private class RODbID_DTSCriteria { - private int _RODbID; - public int RODbID - { get { return _RODbID; } } - private DateTime _DTS; - public DateTime DTS - { get { return _DTS; } } + private readonly int _RODbID; + public int RODbID => _RODbID; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; public RODbID_DTSCriteria(int rODbID, DateTime dts) { _RODbID = rODbID; @@ -925,7 +807,7 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -951,48 +833,56 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addROFst"; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addROFst"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@RODbID", RODbID); - cm.Parameters.AddWithValue("@ROLookup", _ROLookup); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@RODbID", RODbID); + cm.Parameters.AddWithValue("@ROLookup", _ROLookup); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_ROFstID = new SqlParameter("@newROFstID", SqlDbType.Int); - param_ROFstID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ROFstID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_ROFstID = new SqlParameter("@newROFstID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ROFstID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); - cm.ExecuteNonQuery(); + cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _ROFstID = (int)cm.Parameters["@newROFstID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + // Save all values being returned from the Procedure + _ROFstID = (int)cm.Parameters["@newROFstID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; - // Clear Out Any Rofst Binary (Bytes[]) - B2022-026 RO Memory reduction - _ROLookup = null; + // Clear Out Any Rofst Binary (Bytes[]) - B2022-026 RO Memory reduction + _ROLookup = null; + } } + MarkOld(); // update child objects - if (_ROFstAssociations != null) _ROFstAssociations.Update(this); - if (_ROFstFigures != null) _ROFstFigures.Update(this); + _ROFstAssociations?.Update(this); + _ROFstFigures?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -1003,7 +893,7 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int rOFstID, RODb myRODb, byte[] rOLookup, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.Add", 0); @@ -1023,11 +913,15 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_ROFstID = new SqlParameter("@newROFstID", SqlDbType.Int); - param_ROFstID.Direction = ParameterDirection.Output; + SqlParameter param_ROFstID = new SqlParameter("@newROFstID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_ROFstID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); cm.ExecuteNonQuery(); @@ -1047,7 +941,7 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1071,47 +965,53 @@ namespace VEPROMS.CSLA.Library } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.SQLUpdate", GetHashCode()); try { - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateROFst"; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateROFst"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ROFstID", _ROFstID); - cm.Parameters.AddWithValue("@RODbID", RODbID); - cm.Parameters.AddWithValue("@ROLookup", ROFSTLookup.GetRofstLookupBytes(_ROFstID)); // B2022-026 RO Memory reduction - new calls - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ROFstID", _ROFstID); + cm.Parameters.AddWithValue("@RODbID", RODbID); + cm.Parameters.AddWithValue("@ROLookup", ROFSTLookup.GetRofstLookupBytes(_ROFstID)); // B2022-026 RO Memory reduction - new calls + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); - cm.ExecuteNonQuery(); + cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_ROFstAssociations != null) _ROFstAssociations.Update(this); - if (_ROFstFigures != null) _ROFstFigures.Update(this); + _ROFstAssociations?.Update(this); + _ROFstFigures?.Update(this); } catch (Exception ex) { @@ -1123,21 +1023,25 @@ namespace VEPROMS.CSLA.Library internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = ROFst.Add(cn, ref _ROFstID, _MyRODb, _ROLookup, _Config, _DTS, _UserID); - else - _LastChanged = ROFst.Update(cn, ref _ROFstID, _RODbID, _ROLookup, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = ROFst.Add(cn, ref _ROFstID, _MyRODb, _ROLookup, _Config, _DTS, _UserID); + else + _LastChanged = ROFst.Update(cn, ref _ROFstID, _RODbID, _ROLookup, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_ROFstAssociations != null) _ROFstAssociations.Update(this); - if (_ROFstFigures != null) _ROFstFigures.Update(this); + _ROFstAssociations?.Update(this); + _ROFstFigures?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int rOFstID, int rODbID, byte[] rOLookup, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.Update", 0); @@ -1163,8 +1067,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); cm.ExecuteNonQuery(); @@ -1179,12 +1085,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ROFstID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.DataPortal_Delete", GetHashCode()); @@ -1209,7 +1115,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROFst.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int rOFstID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.Remove", 0); @@ -1250,16 +1156,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ROFstID; + private readonly int _ROFstID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int rOFstID) - { - _ROFstID = rOFstID; - } + public bool Exists => _exists; + public ExistsCommand(int rOFstID) => _ROFstID = rOFstID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFst.DataPortal_Execute", GetHashCode()); @@ -1267,7 +1167,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1275,7 +1175,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsROFst"; cm.Parameters.AddWithValue("@ROFstID", _ROFstID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1289,7 +1189,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ROFstExtension _ROFstExtension = new ROFstExtension(); + readonly ROFstExtension _ROFstExtension = new ROFstExtension(); [Serializable()] partial class ROFstExtension : extensionBase { @@ -1298,14 +1198,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1334,57 +1228,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFst) + if (destType == typeof(string) && value is ROFst fst) { // Return the ToString value - return ((ROFst)value).ToString(); + return fst.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ROFstExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ROFst -// { -// partial class ROFstExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociation.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociation.cs index 4f38fa08..1d1ac649 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociation.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociation.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _AssociationID; [System.ComponentModel.DataObjectField(true, true)] public int AssociationID @@ -234,19 +228,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROFstAssociation - protected override object GetIdValue() - { - return MyROFstAssociationUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ROFstAssociation.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROFstAssociation - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyROFstAssociationUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -261,18 +243,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyDocVersion == null ? false : _MyDocVersion.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyDocVersion != null && _MyDocVersion.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocVersion == null ? true : _MyDocVersion.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocVersion == null || _MyDocVersion.IsValidList(list)); } #endregion #region ValidationRules @@ -302,8 +281,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -328,76 +307,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AssociationID, ""); - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowWrite(VersionID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ROFstAssociationUnique = 0; - private static int ROFstAssociationUnique - { get { return ++_ROFstAssociationUnique; } } - private int _MyROFstAssociationUnique = ROFstAssociationUnique; - public int MyROFstAssociationUnique // Absolutely Unique ID - Editable FK - { get { return _MyROFstAssociationUnique; } } - internal static ROFstAssociation New(DocVersion myDocVersion) - { - return new ROFstAssociation(myDocVersion); - } - internal static ROFstAssociation Get(SafeDataReader dr) - { - return new ROFstAssociation(dr); - } + private static int ROFstAssociationUnique => ++_ROFstAssociationUnique; + private readonly int _MyROFstAssociationUnique = ROFstAssociationUnique; + // Absolutely Unique ID - Editable FK + public int MyROFstAssociationUnique => _MyROFstAssociationUnique; + internal static ROFstAssociation New(DocVersion myDocVersion) => new ROFstAssociation(myDocVersion); + internal static ROFstAssociation Get(SafeDataReader dr) => new ROFstAssociation(dr); public ROFstAssociation() { MarkAsChild(); @@ -425,15 +350,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROFstAssociation() { _CountFinalized++; @@ -477,33 +398,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(ROFst myROFst) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Association.Add(cn, ref _AssociationID, _MyDocVersion, myROFst, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Association.Add(cn, ref _AssociationID, _MyDocVersion, myROFst, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(ROFst myROFst) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Association.Update(cn, ref _AssociationID, _VersionID, myROFst.ROFstID, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Association.Update(cn, ref _AssociationID, _VersionID, myROFst.ROFstID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(ROFst myROFst) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Association.Remove(cn, _AssociationID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Association.Remove(cn, _AssociationID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ROFstAssociationExtension _ROFstAssociationExtension = new ROFstAssociationExtension(); + readonly ROFstAssociationExtension _ROFstAssociationExtension = new ROFstAssociationExtension(); [Serializable()] partial class ROFstAssociationExtension : extensionBase { @@ -512,14 +446,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -548,57 +476,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFstAssociation) + if (destType == typeof(string) && value is ROFstAssociation association) { // Return the ToString value - return ((ROFstAssociation)value).ToString(); + return association.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ROFstAssociationExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ROFstAssociation -// { -// partial class ROFstAssociationExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociations.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociations.cs index a2e0af4d..bdfacf79 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociations.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstAssociations.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ROFstAssociation this[Association myAssociation] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ROFstAssociation this[Association myAssociation] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ROFstAssociation GetItem(Association myAssociation) + public new System.Collections.Generic.IList Items => base.Items; + public ROFstAssociation GetItem(Association myAssociation) { foreach (ROFstAssociation association in this) if (association.AssociationID == myAssociation.AssociationID) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(myDocVersion)) { ROFstAssociation association = ROFstAssociation.New(myDocVersion); - this.Add(association); + Add(association); return association; } else @@ -108,23 +100,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ROFstAssociation child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ROFstAssociation child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(DocVersion myDocVersion) { foreach (ROFstAssociation association in this) @@ -156,20 +145,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ROFstAssociations New() - { - return new ROFstAssociations(); - } - internal static ROFstAssociations Get(SafeDataReader dr) - { - return new ROFstAssociations(dr); - } - public static ROFstAssociations GetByROFstID(int rOFstID) + #endregion + #region Factory Methods + internal static ROFstAssociations New() => new ROFstAssociations(); + internal static ROFstAssociations Get(SafeDataReader dr) => new ROFstAssociations(dr); + public static ROFstAssociations GetByROFstID(int rOFstID) { try { @@ -180,11 +163,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFstAssociations.GetByROFstID", ex); } } - private ROFstAssociations() - { - MarkAsChild(); - } - internal ROFstAssociations(SafeDataReader dr) + private ROFstAssociations() => MarkAsChild(); + internal ROFstAssociations(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -193,16 +173,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ROFstAssociations() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ROFstAssociations() { _CountFinalized++; } @@ -217,19 +193,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ROFstAssociation.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ROFstAssociation.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ROFstIDCriteria { - public ROFstIDCriteria(int rOFstID) - { - _ROFstID = rOFstID; - } - private int _ROFstID; + public ROFstIDCriteria(int rOFstID) => _ROFstID = rOFstID; + private int _ROFstID; public int ROFstID { get { return _ROFstID; } @@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ROFstIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstAssociations.DataPortal_FetchROFstID", GetHashCode()); try { @@ -252,7 +225,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ROFstAssociation(dr)); + while (dr.Read()) Add(new ROFstAssociation(dr)); } } } @@ -262,11 +235,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROFstAssociations.DataPortal_FetchROFstID", ex); throw new DbCslaException("ROFstAssociations.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(ROFst rOFst) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -285,49 +258,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ROFstAssociationsPropertyDescriptor pd = new ROFstAssociationsPropertyDescriptor(this, i); @@ -344,7 +306,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ROFstAssociationsPropertyDescriptor : vlnListPropertyDescriptor { - private ROFstAssociation Item { get { return (ROFstAssociation)_Item; } } public ROFstAssociationsPropertyDescriptor(ROFstAssociations collection, int index) : base(collection, index) { ;} } #endregion @@ -353,10 +314,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFstAssociations) + if (destType == typeof(string) && value is ROFstAssociations associations) { // Return department and department role separated by comma. - return ((ROFstAssociations)value).Items.Count.ToString() + " Associations"; + return $"{associations.Items.Count} Associations"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigure.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigure.cs index 4f89775f..739adbdd 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigure.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigure.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _FigureID; [System.ComponentModel.DataObjectField(true, true)] public int FigureID @@ -204,19 +198,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROFstFigure - protected override object GetIdValue() - { - return MyROFstFigureUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ROFstFigure.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROFstFigure - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyROFstFigureUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -231,18 +213,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyROImage == null ? false : _MyROImage.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyROImage != null && _MyROImage.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyROImage == null ? true : _MyROImage.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyROImage == null || _MyROImage.IsValidList(list)); } #endregion #region ValidationRules @@ -272,8 +251,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -298,76 +277,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FigureID, ""); - //AuthorizationRules.AllowRead(ImageID, ""); - //AuthorizationRules.AllowWrite(ImageID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ROFstFigureUnique = 0; - private static int ROFstFigureUnique - { get { return ++_ROFstFigureUnique; } } - private int _MyROFstFigureUnique = ROFstFigureUnique; - public int MyROFstFigureUnique // Absolutely Unique ID - Editable FK - { get { return _MyROFstFigureUnique; } } - internal static ROFstFigure New(ROImage myROImage) - { - return new ROFstFigure(myROImage); - } - internal static ROFstFigure Get(SafeDataReader dr) - { - return new ROFstFigure(dr); - } + private static int ROFstFigureUnique => ++_ROFstFigureUnique; + private readonly int _MyROFstFigureUnique = ROFstFigureUnique; + // Absolutely Unique ID - Editable FK + public int MyROFstFigureUnique => _MyROFstFigureUnique; + internal static ROFstFigure New(ROImage myROImage) => new ROFstFigure(myROImage); + internal static ROFstFigure Get(SafeDataReader dr) => new ROFstFigure(dr); public ROFstFigure() { MarkAsChild(); @@ -395,15 +320,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROFstFigure() { _CountFinalized++; @@ -444,33 +365,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(ROFst myROFst) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Figure.Add(cn, ref _FigureID, myROFst, _MyROImage, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Figure.Add(cn, ref _FigureID, myROFst, _MyROImage, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(ROFst myROFst) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Figure.Update(cn, ref _FigureID, myROFst.ROFstID, _ImageID, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Figure.Update(cn, ref _FigureID, myROFst.ROFstID, _ImageID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(ROFst myROFst) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Figure.Remove(cn, _FigureID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Figure.Remove(cn, _FigureID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ROFstFigureExtension _ROFstFigureExtension = new ROFstFigureExtension(); + readonly ROFstFigureExtension _ROFstFigureExtension = new ROFstFigureExtension(); [Serializable()] partial class ROFstFigureExtension : extensionBase { @@ -479,14 +413,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -515,57 +443,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFstFigure) + if (destType == typeof(string) && value is ROFstFigure figure) { // Return the ToString value - return ((ROFstFigure)value).ToString(); + return figure.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ROFstFigureExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ROFstFigure -// { -// partial class ROFstFigureExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigures.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigures.cs index 13b990f8..e4610439 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigures.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstFigures.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ROFstFigure this[Figure myFigure] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ROFstFigure this[Figure myFigure] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ROFstFigure GetItem(Figure myFigure) + public new System.Collections.Generic.IList Items => base.Items; + public ROFstFigure GetItem(Figure myFigure) { foreach (ROFstFigure figure in this) if (figure.FigureID == myFigure.FigureID) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(myROImage)) { ROFstFigure figure = ROFstFigure.New(myROImage); - this.Add(figure); + Add(figure); return figure; } else @@ -108,23 +100,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ROFstFigure child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ROFstFigure child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(ROImage myROImage) { foreach (ROFstFigure figure in this) @@ -156,20 +145,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ROFstFigures New() - { - return new ROFstFigures(); - } - internal static ROFstFigures Get(SafeDataReader dr) - { - return new ROFstFigures(dr); - } - public static ROFstFigures GetByROFstID(int rOFstID) + #endregion + #region Factory Methods + internal static ROFstFigures New() => new ROFstFigures(); + internal static ROFstFigures Get(SafeDataReader dr) => new ROFstFigures(dr); + public static ROFstFigures GetByROFstID(int rOFstID) { try { @@ -180,11 +163,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFstFigures.GetByROFstID", ex); } } - private ROFstFigures() - { - MarkAsChild(); - } - internal ROFstFigures(SafeDataReader dr) + private ROFstFigures() => MarkAsChild(); + internal ROFstFigures(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -193,16 +173,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ROFstFigures() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ROFstFigures() { _CountFinalized++; } @@ -217,19 +193,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ROFstFigure.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ROFstFigure.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ROFstIDCriteria { - public ROFstIDCriteria(int rOFstID) - { - _ROFstID = rOFstID; - } - private int _ROFstID; + public ROFstIDCriteria(int rOFstID) => _ROFstID = rOFstID; + private int _ROFstID; public int ROFstID { get { return _ROFstID; } @@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ROFstIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstFigures.DataPortal_FetchROFstID", GetHashCode()); try { @@ -252,7 +225,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ROFstFigure(dr)); + while (dr.Read()) Add(new ROFstFigure(dr)); } } } @@ -262,11 +235,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROFstFigures.DataPortal_FetchROFstID", ex); throw new DbCslaException("ROFstFigures.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(ROFst rOFst) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -285,49 +258,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ROFstFiguresPropertyDescriptor pd = new ROFstFiguresPropertyDescriptor(this, i); @@ -344,7 +306,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ROFstFiguresPropertyDescriptor : vlnListPropertyDescriptor { - private ROFstFigure Item { get { return (ROFstFigure)_Item; } } public ROFstFiguresPropertyDescriptor(ROFstFigures collection, int index) : base(collection, index) { ;} } #endregion @@ -353,10 +314,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFstFigures) + if (destType == typeof(string) && value is ROFstFigures figures) { // Return department and department role separated by comma. - return ((ROFstFigures)value).Items.Count.ToString() + " Figures"; + return $"{figures.Items.Count} Figures"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs index ca54bb82..99591ca0 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,20 +26,17 @@ namespace VEPROMS.CSLA.Library public partial class ROFstInfo : ReadOnlyBase, IDisposable { public event ROFstInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ROFstInfo rOFstInfo) { if (!_CacheList.Contains(rOFstInfo)) { - rOFstInfo.ClearROLookupBytes(); // B2022-026 RO Memory reduction _CacheList.Add(rOFstInfo); // In AddToCache } } @@ -49,6 +44,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(rOFstInfo)) _CacheList.Remove(rOFstInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -60,7 +56,6 @@ namespace VEPROMS.CSLA.Library { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey } - tmp.ClearROLookupBytes(); // B2022-026 RO Memory reduction _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheList.RemoveAt(0); // Remove the first ROFstInfo } @@ -79,21 +74,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ROFst _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ROFstID; [System.ComponentModel.DataObjectField(true, true)] public int ROFstID @@ -124,19 +106,6 @@ namespace VEPROMS.CSLA.Library return _MyRODb; } } - - private byte[] _ROLookup; - public byte[] ROLookup - { - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] - get - { - - // B2022-026 RO Memory reduction - return null; - } - } - private string _Config = string.Empty; public string Config { @@ -241,21 +210,17 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROFstInfo - protected override object GetIdValue() - { - return MyROFstInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyROFstInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ROFstInfoUnique = 0; - private static int ROFstInfoUnique - { get { return ++_ROFstInfoUnique; } } - private int _MyROFstInfoUnique = ROFstInfoUnique; - public int MyROFstInfoUnique // Absolutely Unique ID - Info - { get { return _MyROFstInfoUnique; } } + private static int ROFstInfoUnique => ++_ROFstInfoUnique; + private readonly int _MyROFstInfoUnique = ROFstInfoUnique; + // Absolutely Unique ID - Info + public int MyROFstInfoUnique => _MyROFstInfoUnique; protected ROFstInfo() {/* require use of factory methods */ AddToCache(this); @@ -265,15 +230,11 @@ namespace VEPROMS.CSLA.Library 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 static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROFstInfo() { _CountFinalized++; @@ -290,10 +251,7 @@ namespace VEPROMS.CSLA.Library if (listROFstInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ROFstID.ToString()); // remove the list } - public virtual ROFst Get() - { - return _Editable = ROFst.Get(_ROFstID); - } + public virtual ROFst Get() => _Editable = ROFst.Get(_ROFstID); public static void Refresh(ROFst tmp) { string key = tmp.ROFstID.ToString(); @@ -302,23 +260,16 @@ namespace VEPROMS.CSLA.Library foreach (ROFstInfo tmpInfo in _CacheByPrimaryKey[key]) tmpInfo.RefreshFields(tmp); } - // B2022-026 RO Memory reduction - public void ClearROLookupBytes() - { - _ROLookup = null; - } protected virtual void RefreshFields(ROFst tmp) { if (_RODbID != tmp.RODbID) { - if (MyRODb != null) MyRODb.RefreshRODbROFsts(); // Update List for old value + MyRODb?.RefreshRODbROFsts(); // Update List for old value _RODbID = tmp.RODbID; // Update the value } _MyRODb = null; // Reset list so that the next line gets a new list - if (MyRODb != null) MyRODb.RefreshRODbROFsts(); // Update List for new value - //_ROLookup = tmp.ROLookup; - _ROLookup = null; // B2022-026 RO Memory reduction + MyRODb?.RefreshRODbROFsts(); // Update List for new value _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -335,8 +286,6 @@ namespace VEPROMS.CSLA.Library } protected virtual void RefreshFields(RODbROFst tmp) { - //_ROLookup = tmp.ROLookup; - _ROLookup = null; // B2022-026 RO Memory reduction _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; @@ -360,11 +309,6 @@ namespace VEPROMS.CSLA.Library tmp = null; } - if (tmp != null) - { - tmp.ClearROLookupBytes(); // B2022-026 RO Memory reduction - } - return tmp; } catch (Exception ex) @@ -394,13 +338,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ROFstID; - public int ROFstID - { get { return _ROFstID; } } - public PKCriteria(int rOFstID) - { - _ROFstID = rOFstID; - } + private readonly int _ROFstID; + public int ROFstID => _ROFstID; + public PKCriteria(int rOFstID) => _ROFstID = rOFstID; } private void ReadData(SafeDataReader dr) @@ -410,8 +350,6 @@ namespace VEPROMS.CSLA.Library { _ROFstID = dr.GetInt32("ROFstID"); _RODbID = dr.GetInt32("RODbID"); - //_ROLookup = (byte[])dr.GetValue("ROLookup"); - _ROLookup = null; // B2022-026 RO Memory reduction _Config = dr.GetString("Config"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); @@ -467,7 +405,7 @@ namespace VEPROMS.CSLA.Library // Standard Refresh #region extension - ROFstInfoExtension _ROFstInfoExtension = new ROFstInfoExtension(); + readonly ROFstInfoExtension _ROFstInfoExtension = new ROFstInfoExtension(); [Serializable()] partial class ROFstInfoExtension : extensionBase { } [Serializable()] @@ -485,10 +423,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFstInfo) + if (destType == typeof(string) && value is ROFstInfo info) { // Return the ToString value - return ((ROFstInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfoList.cs index 369beb4d..6e886f3e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROFstInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ROFstInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~ROFstInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ROFstInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROFstInfoList.Get", ex); } } - /// - /// Reset the list of all ROFstInfo. - /// - public static void Reset() - { - _ROFstInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ROFstInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ROFstInfoList.Get", ex); - // } - //} - public static ROFstInfoList GetByRODbID(int rODbID) + /// + /// Reset the list of all ROFstInfo. + /// + public static void Reset() => _ROFstInfoList = null; + public static ROFstInfoList GetByRODbID(int rODbID) { try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -150,7 +128,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ROFstInfo(dr)); + while (dr.Read()) Add(new ROFstInfo(dr)); IsReadOnly = true; } } @@ -161,16 +139,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROFstInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ROFstInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -179,7 +154,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROFstInfoList.DataPortal_FetchRODbID", GetHashCode()); try { @@ -194,7 +169,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ROFstInfo(dr)); + while (dr.Read()) Add(new ROFstInfo(dr)); IsReadOnly = true; } } @@ -205,48 +180,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROFstInfoList.DataPortal_FetchRODbID", ex); throw new DbCslaException("ROFstInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ROFstInfoListPropertyDescriptor pd = new ROFstInfoListPropertyDescriptor(this, i); @@ -263,7 +227,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ROFstInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ROFstInfo Item { get { return (ROFstInfo)_Item; } } public ROFstInfoListPropertyDescriptor(ROFstInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -272,10 +235,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROFstInfoList) + if (destType == typeof(string) && value is ROFstInfoList list) { // Return department and department role separated by comma. - return ((ROFstInfoList)value).Items.Count.ToString() + " ROFsts"; + return $"{list.Items.Count} ROFsts"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROImage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROImage.cs index 5b8f58f8..081505fc 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROImage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROImage.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -70,6 +68,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ROImage rOImage) { @@ -79,7 +78,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(rOImage)) _CacheList.Remove(rOImage); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByRODbID_FileName_DTS = new Dictionary>(); private static void ConvertListToDictionary() { @@ -114,15 +115,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextImageID = -1; - public static int NextImageID - { - get { return _nextImageID--; } - } + public static int NextImageID => _nextImageID--; private int _ImageID; [System.ComponentModel.DataObjectField(true, true)] public int ImageID @@ -288,10 +283,7 @@ namespace VEPROMS.CSLA.Library return _ROImageFigures; } } - public void Reset_ROImageFigures() - { - _ROImageFigureCount = -1; - } + public void Reset_ROImageFigures() => _ROImageFigureCount = -1; public override bool IsDirty { get @@ -306,37 +298,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_ROImageFigures == null ? false : _ROImageFigures.IsDirtyList(list)) || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_ROImageFigures != null && _ROImageFigures.IsDirtyList(list)) || (_MyRODb != null && _MyRODb.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_ROImageFigures == null ? true : _ROImageFigures.IsValidList(list)) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_ROImageFigures == null || _ROImageFigures.IsValidList(list)) && (_MyRODb == null || _MyRODb.IsValidList(list)); } - // CSLATODO: Replace base ROImage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROImage - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ROImage.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROImage - protected override object GetIdValue() - { - return MyROImageUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyROImageUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -366,8 +343,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -404,35 +381,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ImageID, ""); - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowRead(FileName, ""); - //AuthorizationRules.AllowRead(Content, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(RODbID, ""); - //AuthorizationRules.AllowWrite(FileName, ""); - //AuthorizationRules.AllowWrite(Content, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _ROImageExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -440,55 +393,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ROImageExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _ROImageFigureCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ROImageUnique = 0; - protected static int ROImageUnique - { get { return ++_ROImageUnique; } } - private int _MyROImageUnique = ROImageUnique; - public int MyROImageUnique // Absolutely Unique ID - Editable - { get { return _MyROImageUnique; } } + protected static int ROImageUnique => ++_ROImageUnique; + private readonly int _MyROImageUnique = ROImageUnique; + // Absolutely Unique ID - Editable + public int MyROImageUnique => _MyROImageUnique; protected ROImage() {/* require use of factory methods */ AddToCache(this); @@ -497,15 +409,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROImage() { _CountFinalized++; @@ -542,8 +450,6 @@ namespace VEPROMS.CSLA.Library } public static ROImage New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ROImage"); try { return DataPortal.Create(); @@ -615,8 +521,6 @@ namespace VEPROMS.CSLA.Library } public static ROImage Get(int imageID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ROImage"); try { ROImage tmp = GetCachedByPrimaryKey(imageID); @@ -639,8 +543,6 @@ namespace VEPROMS.CSLA.Library } public static ROImage GetJustROImage(int imageID)//Don't load figures or ROFST - Causing Memory Crash { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ROImage"); try { ROImage tmp = GetCachedByPrimaryKey(imageID); @@ -663,8 +565,6 @@ namespace VEPROMS.CSLA.Library } public static ROImage GetByRODbID_FileName_DTS(int rODbID, string fileName, DateTime dts) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ROImage"); try { ROImage tmp = GetCachedByRODbID_FileName_DTS(rODbID, fileName, dts); @@ -690,14 +590,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new ROImage(dr); return null; } - internal ROImage(SafeDataReader dr) - { - ReadData(dr); - } + internal ROImage(SafeDataReader dr) => ReadData(dr); public static void Delete(int imageID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ROImage"); try { DataPortal.Delete(new PKCriteria(imageID)); @@ -709,12 +604,6 @@ namespace VEPROMS.CSLA.Library } public override ROImage Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ROImage"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ROImage"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ROImage"); try { BuildRefreshList(); @@ -734,37 +623,26 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ImageID; - public int ImageID - { get { return _ImageID; } } - public PKCriteria(int imageID) - { - _ImageID = imageID; - } + private readonly int _ImageID; + public int ImageID => _ImageID; + public PKCriteria(int imageID) => _ImageID = imageID; } [Serializable()] protected class PKCriteriaJustROImage//Don't load figures or ROFST - Causing Memory Crash { - private int _ImageID; - public int ImageID - { get { return _ImageID; } } - public PKCriteriaJustROImage(int imageID) - { - _ImageID = imageID; - } + private readonly int _ImageID; + public int ImageID => _ImageID; + public PKCriteriaJustROImage(int imageID) => _ImageID = imageID; } [Serializable()] private class RODbID_FileName_DTSCriteria { - private int _RODbID; - public int RODbID - { get { return _RODbID; } } - private string _FileName; - public string FileName - { get { return _FileName; } } - private DateTime _DTS; - public DateTime DTS - { get { return _DTS; } } + private readonly int _RODbID; + public int RODbID => _RODbID; + private readonly string _FileName; + public string FileName => _FileName; + private readonly DateTime _DTS; + public DateTime DTS => _DTS; public RODbID_FileName_DTSCriteria(int rODbID, string fileName, DateTime dts) { _RODbID = rODbID; @@ -920,7 +798,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROImage.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -945,42 +823,50 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addROImage"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@RODbID", RODbID); - cm.Parameters.AddWithValue("@FileName", _FileName); - cm.Parameters.AddWithValue("@Content", _Content); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_ImageID = new SqlParameter("@newImageID", SqlDbType.Int); - param_ImageID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ImageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _ImageID = (int)cm.Parameters["@newImageID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addROImage"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@RODbID", RODbID); + cm.Parameters.AddWithValue("@FileName", _FileName); + cm.Parameters.AddWithValue("@Content", _Content); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_ImageID = new SqlParameter("@newImageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ImageID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _ImageID = (int)cm.Parameters["@newImageID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_ROImageFigures != null) _ROImageFigures.Update(this); + _ROImageFigures?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -990,7 +876,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROImage.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int imageID, RODb myRODb, string fileName, byte[] content, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.Add", 0); @@ -1009,11 +895,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_ImageID = new SqlParameter("@newImageID", SqlDbType.Int); - param_ImageID.Direction = ParameterDirection.Output; + SqlParameter param_ImageID = new SqlParameter("@newImageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_ImageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1028,7 +918,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROImage.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1051,44 +941,50 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.SQLUpdate", GetHashCode()); try { - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateROImage"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ImageID", _ImageID); - cm.Parameters.AddWithValue("@RODbID", RODbID); - cm.Parameters.AddWithValue("@FileName", _FileName); - cm.Parameters.AddWithValue("@Content", _Content); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateROImage"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ImageID", _ImageID); + cm.Parameters.AddWithValue("@RODbID", RODbID); + cm.Parameters.AddWithValue("@FileName", _FileName); + cm.Parameters.AddWithValue("@Content", _Content); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_ROImageFigures != null) _ROImageFigures.Update(this); + _ROImageFigures?.Update(this); } catch (Exception ex) { @@ -1099,19 +995,23 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = ROImage.Add(cn, ref _ImageID, _MyRODb, _FileName, _Content, _Config, _DTS, _UserID); - else - _LastChanged = ROImage.Update(cn, ref _ImageID, _RODbID, _FileName, _Content, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = ROImage.Add(cn, ref _ImageID, _MyRODb, _FileName, _Content, _Config, _DTS, _UserID); + else + _LastChanged = ROImage.Update(cn, ref _ImageID, _RODbID, _FileName, _Content, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_ROImageFigures != null) _ROImageFigures.Update(this); + _ROImageFigures?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int imageID, int rODbID, string fileName, byte[] content, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.Update", 0); @@ -1132,8 +1032,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1147,12 +1049,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROImage.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ImageID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.DataPortal_Delete", GetHashCode()); @@ -1177,7 +1079,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ROImage.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int imageID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.Remove", 0); @@ -1218,16 +1120,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ImageID; + private readonly int _ImageID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int imageID) - { - _ImageID = imageID; - } + public bool Exists => _exists; + public ExistsCommand(int imageID) => _ImageID = imageID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImage.DataPortal_Execute", GetHashCode()); @@ -1235,7 +1131,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1243,7 +1139,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsROImage"; cm.Parameters.AddWithValue("@ImageID", _ImageID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1257,7 +1153,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ROImageExtension _ROImageExtension = new ROImageExtension(); + readonly ROImageExtension _ROImageExtension = new ROImageExtension(); [Serializable()] partial class ROImageExtension : extensionBase { @@ -1266,14 +1162,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1302,57 +1192,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROImage) + if (destType == typeof(string) && value is ROImage image) { // Return the ToString value - return ((ROImage)value).ToString(); + return image.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ROImageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ROImage -// { -// partial class ROImageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigure.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigure.cs index 45226ad6..e5597b0c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigure.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigure.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _FigureID; [System.ComponentModel.DataObjectField(true, true)] public int FigureID @@ -195,19 +189,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROImageFigure - protected override object GetIdValue() - { - return MyROImageFigureUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base ROImageFigure.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROImageFigure - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyROImageFigureUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -222,18 +204,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyROFst == null ? false : _MyROFst.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyROFst != null && _MyROFst.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyROFst == null ? true : _MyROFst.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyROFst == null || _MyROFst.IsValidList(list)); } #endregion #region ValidationRules @@ -263,8 +242,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -289,76 +268,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(FigureID, ""); - //AuthorizationRules.AllowRead(ROFstID, ""); - //AuthorizationRules.AllowWrite(ROFstID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ROImageFigureUnique = 0; - private static int ROImageFigureUnique - { get { return ++_ROImageFigureUnique; } } - private int _MyROImageFigureUnique = ROImageFigureUnique; - public int MyROImageFigureUnique // Absolutely Unique ID - Editable FK - { get { return _MyROImageFigureUnique; } } - internal static ROImageFigure New(ROFst myROFst) - { - return new ROImageFigure(myROFst); - } - internal static ROImageFigure Get(SafeDataReader dr) - { - return new ROImageFigure(dr); - } + private static int ROImageFigureUnique => ++_ROImageFigureUnique; + private readonly int _MyROImageFigureUnique = ROImageFigureUnique; + // Absolutely Unique ID - Editable FK + public int MyROImageFigureUnique => _MyROImageFigureUnique; + internal static ROImageFigure New(ROFst myROFst) => new ROImageFigure(myROFst); + internal static ROImageFigure Get(SafeDataReader dr) => new ROImageFigure(dr); public ROImageFigure() { MarkAsChild(); @@ -386,15 +311,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROImageFigure() { _CountFinalized++; @@ -434,33 +355,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(ROImage myROImage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Figure.Add(cn, ref _FigureID, _MyROFst, myROImage, _Config, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Figure.Add(cn, ref _FigureID, _MyROFst, myROImage, _Config, _DTS, _UserID); + } + MarkOld(); } internal void Update(ROImage myROImage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Figure.Update(cn, ref _FigureID, _ROFstID, myROImage.ImageID, _Config, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Figure.Update(cn, ref _FigureID, _ROFstID, myROImage.ImageID, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(ROImage myROImage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Figure.Remove(cn, _FigureID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Figure.Remove(cn, _FigureID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - ROImageFigureExtension _ROImageFigureExtension = new ROImageFigureExtension(); + readonly ROImageFigureExtension _ROImageFigureExtension = new ROImageFigureExtension(); [Serializable()] partial class ROImageFigureExtension : extensionBase { @@ -469,14 +403,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -505,57 +433,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROImageFigure) + if (destType == typeof(string) && value is ROImageFigure figure) { // Return the ToString value - return ((ROImageFigure)value).ToString(); + return figure.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ROImageFigureExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ROImageFigure -// { -// partial class ROImageFigureExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigures.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigures.cs index 93aef621..18a88d1f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigures.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageFigures.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public ROImageFigure this[Figure myFigure] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public ROImageFigure this[Figure myFigure] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public ROImageFigure GetItem(Figure myFigure) + public new System.Collections.Generic.IList Items => base.Items; + public ROImageFigure GetItem(Figure myFigure) { foreach (ROImageFigure figure in this) if (figure.FigureID == myFigure.FigureID) @@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library if (!Contains(myROFst)) { ROImageFigure figure = ROImageFigure.New(myROFst); - this.Add(figure); + Add(figure); return figure; } else @@ -108,23 +100,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (ROImageFigure child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (ROImageFigure child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } public bool Contains(ROFst myROFst) { foreach (ROImageFigure figure in this) @@ -156,20 +145,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static ROImageFigures New() - { - return new ROImageFigures(); - } - internal static ROImageFigures Get(SafeDataReader dr) - { - return new ROImageFigures(dr); - } - public static ROImageFigures GetByImageID(int imageID) + #endregion + #region Factory Methods + internal static ROImageFigures New() => new ROImageFigures(); + internal static ROImageFigures Get(SafeDataReader dr) => new ROImageFigures(dr); + public static ROImageFigures GetByImageID(int imageID) { try { @@ -180,11 +163,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROImageFigures.GetByImageID", ex); } } - private ROImageFigures() - { - MarkAsChild(); - } - internal ROImageFigures(SafeDataReader dr) + private ROImageFigures() => MarkAsChild(); + internal ROImageFigures(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -193,16 +173,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~ROImageFigures() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ROImageFigures() { _CountFinalized++; } @@ -217,19 +193,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(ROImageFigure.Get(dr)); - this.RaiseListChangedEvents = true; + Add(ROImageFigure.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class ImageIDCriteria { - public ImageIDCriteria(int imageID) - { - _ImageID = imageID; - } - private int _ImageID; + public ImageIDCriteria(int imageID) => _ImageID = imageID; + private int _ImageID; public int ImageID { get { return _ImageID; } @@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ImageIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImageFigures.DataPortal_FetchImageID", GetHashCode()); try { @@ -252,7 +225,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new ROImageFigure(dr)); + while (dr.Read()) Add(new ROImageFigure(dr)); } } } @@ -262,11 +235,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROImageFigures.DataPortal_FetchImageID", ex); throw new DbCslaException("ROImageFigures.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(ROImage rOImage) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -285,49 +258,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ROImageFiguresPropertyDescriptor pd = new ROImageFiguresPropertyDescriptor(this, i); @@ -344,7 +306,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ROImageFiguresPropertyDescriptor : vlnListPropertyDescriptor { - private ROImageFigure Item { get { return (ROImageFigure)_Item; } } public ROImageFiguresPropertyDescriptor(ROImageFigures collection, int index) : base(collection, index) { ;} } #endregion @@ -353,10 +314,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROImageFigures) + if (destType == typeof(string) && value is ROImageFigures figures) { // Return department and department role separated by comma. - return ((ROImageFigures)value).Items.Count.ToString() + " Figures"; + return $"{figures.Items.Count} Figures"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfo.cs index a1b5463b..f0817812 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ROImageInfo : ReadOnlyBase, IDisposable { public event ROImageInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ROImageInfo rOImageInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(rOImageInfo)) _CacheList.Remove(rOImageInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ROImage _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ImageID; [System.ComponentModel.DataObjectField(true, true)] public int ImageID @@ -200,32 +184,19 @@ namespace VEPROMS.CSLA.Library foreach (ROImageInfo tmp in _CacheByPrimaryKey[_ImageID.ToString()]) tmp._ROImageFigureCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base ROImageInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ROImageInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ROImageInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ROImageInfo - protected override object GetIdValue() - { - return MyROImageInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyROImageInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ROImageInfoUnique = 0; - private static int ROImageInfoUnique - { get { return ++_ROImageInfoUnique; } } - private int _MyROImageInfoUnique = ROImageInfoUnique; - public int MyROImageInfoUnique // Absolutely Unique ID - Info - { get { return _MyROImageInfoUnique; } } + private static int ROImageInfoUnique => ++_ROImageInfoUnique; + private readonly int _MyROImageInfoUnique = ROImageInfoUnique; + // Absolutely Unique ID - Info + public int MyROImageInfoUnique => _MyROImageInfoUnique; protected ROImageInfo() {/* require use of factory methods */ AddToCache(this); @@ -234,15 +205,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ROImageInfo() { _CountFinalized++; @@ -261,10 +228,7 @@ namespace VEPROMS.CSLA.Library if (listROImageInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ImageID.ToString()); // remove the list } - public virtual ROImage Get() - { - return _Editable = ROImage.GetJustROImage(_ImageID);//Don't load figures or ROFST - Causing Memory Crash - } + public virtual ROImage Get() => _Editable = ROImage.GetJustROImage(_ImageID);//Don't load figures or ROFST - Causing Memory Crash public static void Refresh(ROImage tmp) { string key = tmp.ImageID.ToString(); @@ -277,11 +241,11 @@ namespace VEPROMS.CSLA.Library { if (_RODbID != tmp.RODbID) { - if (MyRODb != null) MyRODb.RefreshRODbROImages(); // Update List for old value + MyRODb?.RefreshRODbROImages(); // Update List for old value _RODbID = tmp.RODbID; // Update the value } _MyRODb = null; // Reset list so that the next line gets a new list - if (MyRODb != null) MyRODb.RefreshRODbROImages(); // Update List for new value + MyRODb?.RefreshRODbROImages(); // Update List for new value _FileName = tmp.FileName; _Content = tmp.Content; _Config = tmp.Config; @@ -310,8 +274,6 @@ namespace VEPROMS.CSLA.Library } public static ROImageInfo Get(int imageID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ROImage"); try { ROImageInfo tmp = GetCachedByPrimaryKey(imageID); @@ -350,13 +312,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ImageID; - public int ImageID - { get { return _ImageID; } } - public PKCriteria(int imageID) - { - _ImageID = imageID; - } + private readonly int _ImageID; + public int ImageID => _ImageID; + public PKCriteria(int imageID) => _ImageID = imageID; } private void ReadData(SafeDataReader dr) { @@ -418,7 +376,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ROImageInfoExtension _ROImageInfoExtension = new ROImageInfoExtension(); + readonly ROImageInfoExtension _ROImageInfoExtension = new ROImageInfoExtension(); [Serializable()] partial class ROImageInfoExtension : extensionBase { } [Serializable()] @@ -434,10 +392,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROImageInfo) + if (destType == typeof(string) && value is ROImageInfo info) { // Return the ToString value - return ((ROImageInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfoList.cs index b6c455fb..f743e5ad 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ROImageInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (ROImageInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~ROImageInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~ROImageInfoList() { _CountFinalized++; } @@ -98,26 +91,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ROImageInfoList.Get", ex); } } - /// - /// Reset the list of all ROImageInfo. - /// - public static void Reset() - { - _ROImageInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static ROImageInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on ROImageInfoList.Get", ex); - // } - //} - public static ROImageInfoList GetByRODbID(int rODbID) + /// + /// Reset the list of all ROImageInfo. + /// + public static void Reset() => _ROImageInfoList = null; + public static ROImageInfoList GetByRODbID(int rODbID) { try { @@ -137,7 +115,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImageInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -151,7 +129,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ROImageInfo(dr)); + while (dr.Read()) Add(new ROImageInfo(dr)); IsReadOnly = true; } } @@ -162,16 +140,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROImageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("ROImageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -180,7 +155,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImageInfoList.DataPortal_FetchRODbID", GetHashCode()); try { @@ -195,7 +170,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new ROImageInfo(dr)); + while (dr.Read()) Add(new ROImageInfo(dr)); IsReadOnly = true; } } @@ -206,48 +181,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("ROImageInfoList.DataPortal_FetchRODbID", ex); throw new DbCslaException("ROImageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection ROImageInfoListPropertyDescriptor pd = new ROImageInfoListPropertyDescriptor(this, i); @@ -264,7 +228,6 @@ namespace VEPROMS.CSLA.Library /// public partial class ROImageInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private ROImageInfo Item { get { return (ROImageInfo)_Item; } } public ROImageInfoListPropertyDescriptor(ROImageInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -273,10 +236,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ROImageInfoList) + if (destType == typeof(string) && value is ROImageInfoList list) { // Return department and department role separated by comma. - return ((ROImageInfoList)value).Items.Count.ToString() + " ROImages"; + return $"{list.Items.Count} ROImages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Revision.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Revision.cs index 72df59b0..3d4132fd 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Revision.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Revision.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -82,6 +80,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Revision revision) { @@ -91,6 +90,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(revision)) _CacheList.Remove(revision); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -116,15 +116,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextRevisionID = -1; - public static int NextRevisionID - { - get { return _nextRevisionID--; } - } + public static int NextRevisionID => _nextRevisionID--; private int _RevisionID; [System.ComponentModel.DataObjectField(true, true)] public int RevisionID @@ -315,10 +309,7 @@ namespace VEPROMS.CSLA.Library return _RevisionChecks; } } - public void Reset_RevisionChecks() - { - _RevisionCheckCount = -1; - } + public void Reset_RevisionChecks() => _RevisionCheckCount = -1; private int _RevisionVersionCount = 0; /// /// Count of RevisionVersions for this Revision @@ -350,10 +341,7 @@ namespace VEPROMS.CSLA.Library return _RevisionVersions; } } - public void Reset_RevisionVersions() - { - _RevisionVersionCount = -1; - } + public void Reset_RevisionVersions() => _RevisionVersionCount = -1; public override bool IsDirty { get @@ -368,37 +356,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_RevisionChecks == null ? false : _RevisionChecks.IsDirtyList(list)) || (_RevisionVersions == null ? false : _RevisionVersions.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_RevisionChecks != null && _RevisionChecks.IsDirtyList(list)) || (_RevisionVersions != null && _RevisionVersions.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_RevisionChecks == null ? true : _RevisionChecks.IsValidList(list)) && (_RevisionVersions == null ? true : _RevisionVersions.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_RevisionChecks == null || _RevisionChecks.IsValidList(list)) && (_RevisionVersions == null || _RevisionVersions.IsValidList(list)); } - // CSLATODO: Replace base Revision.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Revision - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Revision.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Revision - protected override object GetIdValue() - { - return MyRevisionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRevisionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -428,8 +401,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return (hasBrokenRules?.BrokenRules); } } protected override void AddBusinessRules() @@ -457,39 +430,11 @@ namespace VEPROMS.CSLA.Library _RevisionExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(RevisionID, ""); - //AuthorizationRules.AllowRead(ItemID, ""); - //AuthorizationRules.AllowRead(TypeID, ""); - //AuthorizationRules.AllowRead(RevisionNumber, ""); - //AuthorizationRules.AllowRead(RevisionDate, ""); - //AuthorizationRules.AllowRead(Notes, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(ItemID, ""); - //AuthorizationRules.AllowWrite(TypeID, ""); - //AuthorizationRules.AllowWrite(RevisionNumber, ""); - //AuthorizationRules.AllowWrite(RevisionDate, ""); - //AuthorizationRules.AllowWrite(Notes, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _RevisionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -497,56 +442,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _RevisionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _RevisionCheckCount; - usedByCount += _RevisionVersionCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RevisionUnique = 0; - protected static int RevisionUnique - { get { return ++_RevisionUnique; } } - private int _MyRevisionUnique = RevisionUnique; - public int MyRevisionUnique // Absolutely Unique ID - Editable - { get { return _MyRevisionUnique; } } + protected static int RevisionUnique => ++_RevisionUnique; + private readonly int _MyRevisionUnique = RevisionUnique; + // Absolutely Unique ID - Editable + public int MyRevisionUnique => _MyRevisionUnique; protected Revision() {/* require use of factory methods */ AddToCache(this); @@ -555,15 +458,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Revision() { _CountFinalized++; @@ -588,8 +487,6 @@ namespace VEPROMS.CSLA.Library } public static Revision New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Revision"); try { return DataPortal.Create(); @@ -662,8 +559,6 @@ namespace VEPROMS.CSLA.Library } public static Revision Get(int revisionID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Revision"); try { Revision tmp = GetCachedByPrimaryKey(revisionID); @@ -689,14 +584,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Revision(dr); return null; } - internal Revision(SafeDataReader dr) - { - ReadData(dr); - } + internal Revision(SafeDataReader dr) => ReadData(dr); public static void Delete(int revisionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Revision"); try { DataPortal.Delete(new PKCriteria(revisionID)); @@ -708,12 +598,6 @@ namespace VEPROMS.CSLA.Library } public override Revision Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Revision"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Revision"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Revision"); try { BuildRefreshList(); @@ -733,13 +617,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _RevisionID; - public int RevisionID - { get { return _RevisionID; } } - public PKCriteria(int revisionID) - { - _RevisionID = revisionID; - } + private readonly int _RevisionID; + public int RevisionID => _RevisionID; + public PKCriteria(int revisionID) => _RevisionID = revisionID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -821,7 +701,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Revision.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -846,44 +726,52 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addRevision"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@TypeID", _TypeID); - cm.Parameters.AddWithValue("@RevisionNumber", _RevisionNumber); - if (_RevisionDate != null && ((DateTime)_RevisionDate).Year >= 1753 && ((DateTime)_RevisionDate).Year <= 9999) cm.Parameters.AddWithValue("@RevisionDate", _RevisionDate); - cm.Parameters.AddWithValue("@Notes", _Notes); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_RevisionID = new SqlParameter("@newRevisionID", SqlDbType.Int); - param_RevisionID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_RevisionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _RevisionID = (int)cm.Parameters["@newRevisionID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addRevision"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@TypeID", _TypeID); + cm.Parameters.AddWithValue("@RevisionNumber", _RevisionNumber); + if (_RevisionDate != null && ((DateTime)_RevisionDate).Year >= 1753 && ((DateTime)_RevisionDate).Year <= 9999) cm.Parameters.AddWithValue("@RevisionDate", _RevisionDate); + cm.Parameters.AddWithValue("@Notes", _Notes); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_RevisionID = new SqlParameter("@newRevisionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_RevisionID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _RevisionID = (int)cm.Parameters["@newRevisionID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_RevisionChecks != null) _RevisionChecks.Update(this); - if (_RevisionVersions != null) _RevisionVersions.Update(this); + _RevisionChecks?.Update(this); + _RevisionVersions?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -893,7 +781,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Revision.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int revisionID, int itemID, int typeID, string revisionNumber, DateTime? revisionDate, string notes, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.Add", 0); @@ -914,11 +802,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_RevisionID = new SqlParameter("@newRevisionID", SqlDbType.Int); - param_RevisionID.Direction = ParameterDirection.Output; + SqlParameter param_RevisionID = new SqlParameter("@newRevisionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_RevisionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -933,7 +825,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Revision.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -956,46 +848,52 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateRevision"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@RevisionID", _RevisionID); - cm.Parameters.AddWithValue("@ItemID", _ItemID); - cm.Parameters.AddWithValue("@TypeID", _TypeID); - cm.Parameters.AddWithValue("@RevisionNumber", _RevisionNumber); - if (_RevisionDate != null && ((DateTime)_RevisionDate).Year >= 1753 && ((DateTime)_RevisionDate).Year <= 9999) cm.Parameters.AddWithValue("@RevisionDate", _RevisionDate); - cm.Parameters.AddWithValue("@Notes", _Notes); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateRevision"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@RevisionID", _RevisionID); + cm.Parameters.AddWithValue("@ItemID", _ItemID); + cm.Parameters.AddWithValue("@TypeID", _TypeID); + cm.Parameters.AddWithValue("@RevisionNumber", _RevisionNumber); + if (_RevisionDate != null && ((DateTime)_RevisionDate).Year >= 1753 && ((DateTime)_RevisionDate).Year <= 9999) cm.Parameters.AddWithValue("@RevisionDate", _RevisionDate); + cm.Parameters.AddWithValue("@Notes", _Notes); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_RevisionChecks != null) _RevisionChecks.Update(this); - if (_RevisionVersions != null) _RevisionVersions.Update(this); + _RevisionChecks?.Update(this); + _RevisionVersions?.Update(this); } catch (Exception ex) { @@ -1006,20 +904,24 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Revision.Add(cn, ref _RevisionID, _ItemID, _TypeID, _RevisionNumber, _RevisionDate, _Notes, _Config, _DTS, _UserID); - else - _LastChanged = Revision.Update(cn, ref _RevisionID, _ItemID, _TypeID, _RevisionNumber, _RevisionDate, _Notes, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Revision.Add(cn, ref _RevisionID, _ItemID, _TypeID, _RevisionNumber, _RevisionDate, _Notes, _Config, _DTS, _UserID); + else + _LastChanged = Revision.Update(cn, ref _RevisionID, _ItemID, _TypeID, _RevisionNumber, _RevisionDate, _Notes, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_RevisionChecks != null) _RevisionChecks.Update(this); - if (_RevisionVersions != null) _RevisionVersions.Update(this); + _RevisionChecks?.Update(this); + _RevisionVersions?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int revisionID, int itemID, int typeID, string revisionNumber, DateTime? revisionDate, string notes, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.Update", 0); @@ -1042,8 +944,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1057,12 +961,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Revision.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_RevisionID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.DataPortal_Delete", GetHashCode()); @@ -1087,7 +991,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Revision.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int revisionID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.Remove", 0); @@ -1128,16 +1032,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _RevisionID; + private readonly int _RevisionID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int revisionID) - { - _RevisionID = revisionID; - } + public bool Exists => _exists; + public ExistsCommand(int revisionID) => _RevisionID = revisionID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Revision.DataPortal_Execute", GetHashCode()); @@ -1145,7 +1043,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1167,7 +1065,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - RevisionExtension _RevisionExtension = new RevisionExtension(); + readonly RevisionExtension _RevisionExtension = new RevisionExtension(); [Serializable()] partial class RevisionExtension : extensionBase { @@ -1176,18 +1074,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultTypeID - { - get { return 1; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultTypeID => 1; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1216,61 +1105,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Revision) + if (destType == typeof(string) && value is Revision revision) { // Return the ToString value - return ((Revision)value).ToString(); + return revision.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RevisionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Revision -// { -// partial class RevisionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultTypeID -// { -// get { return 1; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionCheck.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionCheck.cs index 3f229c9b..3c2c1fc9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionCheck.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionCheck.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _CheckID; [System.ComponentModel.DataObjectField(true, true)] public int CheckID @@ -195,19 +189,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RevisionCheck - protected override object GetIdValue() - { - return MyRevisionCheckUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RevisionCheck.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RevisionCheck - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyRevisionCheckUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -222,18 +204,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyStage == null ? false : _MyStage.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyStage != null && _MyStage.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyStage == null ? true : _MyStage.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyStage == null || _MyStage.IsValidList(list)); } #endregion #region ValidationRules @@ -263,8 +242,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -289,76 +268,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(CheckID, ""); - //AuthorizationRules.AllowRead(StageID, ""); - //AuthorizationRules.AllowWrite(StageID, ""); - //AuthorizationRules.AllowRead(ConsistencyChecks, ""); - //AuthorizationRules.AllowWrite(ConsistencyChecks, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RevisionCheckUnique = 0; - private static int RevisionCheckUnique - { get { return ++_RevisionCheckUnique; } } - private int _MyRevisionCheckUnique = RevisionCheckUnique; - public int MyRevisionCheckUnique // Absolutely Unique ID - Editable FK - { get { return _MyRevisionCheckUnique; } } - internal static RevisionCheck New(Stage myStage) - { - return new RevisionCheck(myStage); - } - internal static RevisionCheck Get(SafeDataReader dr) - { - return new RevisionCheck(dr); - } + private static int RevisionCheckUnique => ++_RevisionCheckUnique; + private readonly int _MyRevisionCheckUnique = RevisionCheckUnique; + // Absolutely Unique ID - Editable FK + public int MyRevisionCheckUnique => _MyRevisionCheckUnique; + internal static RevisionCheck New(Stage myStage) => new RevisionCheck(myStage); + internal static RevisionCheck Get(SafeDataReader dr) => new RevisionCheck(dr); public RevisionCheck() { MarkAsChild(); @@ -386,15 +311,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RevisionCheck() { _CountFinalized++; @@ -434,33 +355,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Revision myRevision) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Check.Add(cn, ref _CheckID, myRevision, _MyStage, _ConsistencyChecks, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Check.Add(cn, ref _CheckID, myRevision, _MyStage, _ConsistencyChecks, _DTS, _UserID); + } + MarkOld(); } internal void Update(Revision myRevision) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Check.Update(cn, ref _CheckID, myRevision.RevisionID, _StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Check.Update(cn, ref _CheckID, myRevision.RevisionID, _StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Revision myRevision) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Check.Remove(cn, _CheckID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Check.Remove(cn, _CheckID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RevisionCheckExtension _RevisionCheckExtension = new RevisionCheckExtension(); + readonly RevisionCheckExtension _RevisionCheckExtension = new RevisionCheckExtension(); [Serializable()] partial class RevisionCheckExtension : extensionBase { @@ -469,14 +403,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -505,57 +433,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RevisionCheck) + if (destType == typeof(string) && value is RevisionCheck check) { // Return the ToString value - return ((RevisionCheck)value).ToString(); + return check.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RevisionCheckExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RevisionCheck -// { -// partial class RevisionCheckExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionChecks.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionChecks.cs index ea6126fd..d24c82c4 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionChecks.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionChecks.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RevisionCheck this[Check myCheck] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RevisionCheck this[Check myCheck] { get { @@ -61,7 +56,7 @@ namespace VEPROMS.CSLA.Library public RevisionCheck Add(Stage myStage) // One to Many { RevisionCheck check = RevisionCheck.New(myStage); - this.Add(check); + Add(check); return check; } public void Remove(Check myCheck) @@ -103,23 +98,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RevisionCheck child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RevisionCheck child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +129,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RevisionChecks New() - { - return new RevisionChecks(); - } - internal static RevisionChecks Get(SafeDataReader dr) - { - return new RevisionChecks(dr); - } - public static RevisionChecks GetByRevisionID(int revisionID) + #endregion + #region Factory Methods + internal static RevisionChecks New() => new RevisionChecks(); + internal static RevisionChecks Get(SafeDataReader dr) => new RevisionChecks(dr); + public static RevisionChecks GetByRevisionID(int revisionID) { try { @@ -161,11 +147,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RevisionChecks.GetByRevisionID", ex); } } - private RevisionChecks() - { - MarkAsChild(); - } - internal RevisionChecks(SafeDataReader dr) + private RevisionChecks() => MarkAsChild(); + internal RevisionChecks(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +157,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RevisionChecks() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RevisionChecks() { _CountFinalized++; } @@ -198,19 +177,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RevisionCheck.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RevisionCheck.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RevisionIDCriteria { - public RevisionIDCriteria(int revisionID) - { - _RevisionID = revisionID; - } - private int _RevisionID; + public RevisionIDCriteria(int revisionID) => _RevisionID = revisionID; + private int _RevisionID; public int RevisionID { get { return _RevisionID; } @@ -219,7 +195,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RevisionIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RevisionChecks.DataPortal_FetchRevisionID", GetHashCode()); try { @@ -233,7 +209,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RevisionCheck(dr)); + while (dr.Read()) Add(new RevisionCheck(dr)); } } } @@ -243,11 +219,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RevisionChecks.DataPortal_FetchRevisionID", ex); throw new DbCslaException("RevisionChecks.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Revision revision) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +242,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RevisionChecksPropertyDescriptor pd = new RevisionChecksPropertyDescriptor(this, i); @@ -325,7 +290,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RevisionChecksPropertyDescriptor : vlnListPropertyDescriptor { - private RevisionCheck Item { get { return (RevisionCheck)_Item; } } public RevisionChecksPropertyDescriptor(RevisionChecks collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +298,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RevisionChecks) + if (destType == typeof(string) && value is RevisionChecks checks) { // Return department and department role separated by comma. - return ((RevisionChecks)value).Items.Count.ToString() + " Checks"; + return $"{checks.Items.Count} Checks"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfo.cs index 02632fb9..328dcb1b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class RevisionInfo : ReadOnlyBase, IDisposable { public event RevisionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(RevisionInfo revisionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(revisionInfo)) _CacheList.Remove(revisionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Revision _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _RevisionID; [System.ComponentModel.DataObjectField(true, true)] public int RevisionID @@ -261,32 +245,19 @@ namespace VEPROMS.CSLA.Library foreach (RevisionInfo tmp in _CacheByPrimaryKey[_RevisionID.ToString()]) tmp._RevisionVersionCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base RevisionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RevisionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check RevisionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RevisionInfo - protected override object GetIdValue() - { - return MyRevisionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRevisionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _RevisionInfoUnique = 0; - private static int RevisionInfoUnique - { get { return ++_RevisionInfoUnique; } } - private int _MyRevisionInfoUnique = RevisionInfoUnique; - public int MyRevisionInfoUnique // Absolutely Unique ID - Info - { get { return _MyRevisionInfoUnique; } } + private static int RevisionInfoUnique => ++_RevisionInfoUnique; + private readonly int _MyRevisionInfoUnique = RevisionInfoUnique; + // Absolutely Unique ID - Info + public int MyRevisionInfoUnique => _MyRevisionInfoUnique; protected RevisionInfo() {/* require use of factory methods */ AddToCache(this); @@ -295,15 +266,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RevisionInfo() { _CountFinalized++; @@ -320,10 +287,7 @@ namespace VEPROMS.CSLA.Library if (listRevisionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(RevisionID.ToString()); // remove the list } - public virtual Revision Get() - { - return _Editable = Revision.Get(_RevisionID); - } + public virtual Revision Get() => _Editable = Revision.Get(_RevisionID); public static void Refresh(Revision tmp) { string key = tmp.RevisionID.ToString(); @@ -347,8 +311,6 @@ namespace VEPROMS.CSLA.Library } public static RevisionInfo Get(int revisionID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Revision"); try { RevisionInfo tmp = GetCachedByPrimaryKey(revisionID); @@ -387,13 +349,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _RevisionID; - public int RevisionID - { get { return _RevisionID; } } - public PKCriteria(int revisionID) - { - _RevisionID = revisionID; - } + private readonly int _RevisionID; + public int RevisionID => _RevisionID; + public PKCriteria(int revisionID) => _RevisionID = revisionID; } private void ReadData(SafeDataReader dr) { @@ -458,7 +416,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - RevisionInfoExtension _RevisionInfoExtension = new RevisionInfoExtension(); + readonly RevisionInfoExtension _RevisionInfoExtension = new RevisionInfoExtension(); [Serializable()] partial class RevisionInfoExtension : extensionBase { } [Serializable()] @@ -474,10 +432,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RevisionInfo) + if (destType == typeof(string) && value is RevisionInfo info) { // Return the ToString value - return ((RevisionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfoList.cs index bcd78a09..7fd9627a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (RevisionInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~RevisionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RevisionInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RevisionInfoList.Get", ex); } } - /// - /// Reset the list of all RevisionInfo. - /// - public static void Reset() - { - _RevisionInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static RevisionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on RevisionInfoList.Get", ex); - // } - //} - private RevisionInfoList() + /// + /// Reset the list of all RevisionInfo. + /// + public static void Reset() => _RevisionInfoList = null; + private RevisionInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RevisionInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RevisionInfo(dr)); + while (dr.Read()) Add(new RevisionInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RevisionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RevisionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RevisionInfoListPropertyDescriptor pd = new RevisionInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RevisionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private RevisionInfo Item { get { return (RevisionInfo)_Item; } } public RevisionInfoListPropertyDescriptor(RevisionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RevisionInfoList) + if (destType == typeof(string) && value is RevisionInfoList list) { // Return department and department role separated by comma. - return ((RevisionInfoList)value).Items.Count.ToString() + " Revisions"; + return $"{list.Items.Count} Revisions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersion.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersion.cs index 898f2c29..150e9b05 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersion.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersion.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -230,19 +224,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RevisionVersion - protected override object GetIdValue() - { - return MyRevisionVersionUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RevisionVersion.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RevisionVersion - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyRevisionVersionUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -257,18 +239,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyStage == null ? false : _MyStage.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyStage != null && _MyStage.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyStage == null ? true : _MyStage.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyStage == null || _MyStage.IsValidList(list)); } #endregion #region ValidationRules @@ -298,8 +277,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -321,78 +300,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(StageID, ""); - //AuthorizationRules.AllowWrite(StageID, ""); - //AuthorizationRules.AllowRead(PDF, ""); - //AuthorizationRules.AllowWrite(PDF, ""); - //AuthorizationRules.AllowRead(SummaryPDF, ""); - //AuthorizationRules.AllowWrite(SummaryPDF, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RevisionVersionUnique = 0; - private static int RevisionVersionUnique - { get { return ++_RevisionVersionUnique; } } - private int _MyRevisionVersionUnique = RevisionVersionUnique; - public int MyRevisionVersionUnique // Absolutely Unique ID - Editable FK - { get { return _MyRevisionVersionUnique; } } - internal static RevisionVersion New(Stage myStage, DateTime dts, string userID) - { - return new RevisionVersion(myStage, dts, userID); - } - internal static RevisionVersion Get(SafeDataReader dr) - { - return new RevisionVersion(dr); - } + private static int RevisionVersionUnique => ++_RevisionVersionUnique; + private readonly int _MyRevisionVersionUnique = RevisionVersionUnique; + // Absolutely Unique ID - Editable FK + public int MyRevisionVersionUnique => _MyRevisionVersionUnique; + internal static RevisionVersion New(Stage myStage, DateTime dts, string userID) => new RevisionVersion(myStage, dts, userID); + internal static RevisionVersion Get(SafeDataReader dr) => new RevisionVersion(dr); public RevisionVersion() { MarkAsChild(); @@ -420,15 +343,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RevisionVersion() { _CountFinalized++; @@ -469,33 +388,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Revision myRevision) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Version.Add(cn, ref _VersionID, myRevision, _MyStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Version.Add(cn, ref _VersionID, myRevision, _MyStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); + } + MarkOld(); } internal void Update(Revision myRevision) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Version.Update(cn, ref _VersionID, myRevision.RevisionID, _StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Version.Update(cn, ref _VersionID, myRevision.RevisionID, _StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Revision myRevision) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Version.Remove(cn, _VersionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Version.Remove(cn, _VersionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RevisionVersionExtension _RevisionVersionExtension = new RevisionVersionExtension(); + readonly RevisionVersionExtension _RevisionVersionExtension = new RevisionVersionExtension(); [Serializable()] partial class RevisionVersionExtension : extensionBase { @@ -532,49 +464,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RevisionVersion) + if (destType == typeof(string) && value is RevisionVersion version) { // Return the ToString value - return ((RevisionVersion)value).ToString(); + return version.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RevisionVersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RevisionVersion -// { -// partial class RevisionVersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersions.cs index 8f3b9433..388b3e74 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RevisionVersions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RevisionVersion this[Version myVersion] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RevisionVersion this[Version myVersion] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RevisionVersion GetItem(Version myVersion) + public new System.Collections.Generic.IList Items => base.Items; + public RevisionVersion GetItem(Version myVersion) { foreach (RevisionVersion version in this) if (version.VersionID == myVersion.VersionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RevisionVersion Add(Stage myStage, DateTime dts, string userID) // One to Many { RevisionVersion version = RevisionVersion.New(myStage, dts, userID); - this.Add(version); + Add(version); return version; } public void Remove(Version myVersion) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RevisionVersion child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RevisionVersion child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RevisionVersions New() - { - return new RevisionVersions(); - } - internal static RevisionVersions Get(SafeDataReader dr) - { - return new RevisionVersions(dr); - } - public static RevisionVersions GetByRevisionID(int revisionID) + #endregion + #region Factory Methods + internal static RevisionVersions New() => new RevisionVersions(); + internal static RevisionVersions Get(SafeDataReader dr) => new RevisionVersions(dr); + public static RevisionVersions GetByRevisionID(int revisionID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RevisionVersions.GetByRevisionID", ex); } } - private RevisionVersions() - { - MarkAsChild(); - } - internal RevisionVersions(SafeDataReader dr) + private RevisionVersions() => MarkAsChild(); + internal RevisionVersions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RevisionVersions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RevisionVersions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RevisionVersion.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RevisionVersion.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RevisionIDCriteria { - public RevisionIDCriteria(int revisionID) - { - _RevisionID = revisionID; - } - private int _RevisionID; + public RevisionIDCriteria(int revisionID) => _RevisionID = revisionID; + private int _RevisionID; public int RevisionID { get { return _RevisionID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RevisionIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RevisionVersions.DataPortal_FetchRevisionID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RevisionVersion(dr)); + while (dr.Read()) Add(new RevisionVersion(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RevisionVersions.DataPortal_FetchRevisionID", ex); throw new DbCslaException("RevisionVersions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Revision revision) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RevisionVersionsPropertyDescriptor pd = new RevisionVersionsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RevisionVersionsPropertyDescriptor : vlnListPropertyDescriptor { - private RevisionVersion Item { get { return (RevisionVersion)_Item; } } public RevisionVersionsPropertyDescriptor(RevisionVersions collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RevisionVersions) + if (destType == typeof(string) && value is RevisionVersions versions) { // Return department and department role separated by comma. - return ((RevisionVersions)value).Items.Count.ToString() + " Versions"; + return $"{versions.Items.Count} Versions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoUsage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoUsage.cs index 7cb91cf6..28d47aea 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoUsage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoUsage.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshRoUsages.Add(this); } - private void ClearRefreshList() - { - _RefreshRoUsages = new List(); - } + private void ClearRefreshList() => _RefreshRoUsages = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(RoUsage roUsage) { @@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(roUsage)) _CacheList.Remove(roUsage); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,15 +89,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextROUsageID = -1; - public static int NextROUsageID - { - get { return _nextROUsageID--; } - } + public static int NextROUsageID => _nextROUsageID--; private int _ROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int ROUsageID @@ -261,37 +252,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)) || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)) || (_MyRODb != null && _MyRODb.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)) && (_MyRODb == null || _MyRODb.IsValidList(list)); } - // CSLATODO: Replace base RoUsage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RoUsage - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check RoUsage.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RoUsage - protected override object GetIdValue() - { - return MyRoUsageUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRoUsageUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -321,8 +297,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -369,35 +345,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ROUsageID, ""); - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(ROID, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(RODbID, ""); - //AuthorizationRules.AllowWrite(ContentID, ""); - //AuthorizationRules.AllowWrite(ROID, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(RODbID, ""); _RoUsageExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -405,42 +357,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _RoUsageExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RoUsageUnique = 0; - protected static int RoUsageUnique - { get { return ++_RoUsageUnique; } } - private int _MyRoUsageUnique = RoUsageUnique; - public int MyRoUsageUnique // Absolutely Unique ID - Editable - { get { return _MyRoUsageUnique; } } + protected static int RoUsageUnique => ++_RoUsageUnique; + private readonly int _MyRoUsageUnique = RoUsageUnique; + // Absolutely Unique ID - Editable + public int MyRoUsageUnique => _MyRoUsageUnique; protected RoUsage() {/* require use of factory methods */ AddToCache(this); @@ -449,15 +373,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RoUsage() { _CountFinalized++; @@ -482,8 +402,6 @@ namespace VEPROMS.CSLA.Library } public static RoUsage New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a RoUsage"); try { return DataPortal.Create(); @@ -554,8 +472,6 @@ namespace VEPROMS.CSLA.Library } public static RoUsage Get(int rOUsageID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a RoUsage"); try { RoUsage tmp = GetCachedByPrimaryKey(rOUsageID); @@ -576,19 +492,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoUsage.Get", ex); } } - public static RoUsage Get(SafeDataReader dr) - { - if (dr.Read()) return new RoUsage(dr); - return null; - } - internal RoUsage(SafeDataReader dr) - { - ReadData(dr); - } + public static RoUsage Get(SafeDataReader dr) => dr.Read() ? new RoUsage(dr) : null; + internal RoUsage(SafeDataReader dr) => ReadData(dr); public static void Delete(int rOUsageID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a RoUsage"); try { DataPortal.Delete(new PKCriteria(rOUsageID)); @@ -600,12 +507,6 @@ namespace VEPROMS.CSLA.Library } public override RoUsage Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a RoUsage"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a RoUsage"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a RoUsage"); try { BuildRefreshList(); @@ -625,13 +526,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ROUsageID; - public int ROUsageID - { get { return _ROUsageID; } } - public PKCriteria(int rOUsageID) - { - _ROUsageID = rOUsageID; - } + private readonly int _ROUsageID; + public int ROUsageID => _ROUsageID; + public PKCriteria(int rOUsageID) => _ROUsageID = rOUsageID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -703,7 +600,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RoUsage.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -728,40 +625,48 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyContent != null) _MyContent.Update(); - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyContent?.Update(); + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addRoUsage"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@ROID", _ROID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@RODbID", RODbID); - // Output Calculated Columns - SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int); - param_ROUsageID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_ROUsageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _ROUsageID = (int)cm.Parameters["@newROUsageID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addRoUsage"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@ROID", _ROID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@RODbID", RODbID); + // Output Calculated Columns + SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_ROUsageID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _ROUsageID = (int)cm.Parameters["@newROUsageID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.SQLInsert", GetHashCode()); @@ -773,7 +678,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RoUsage.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int rOUsageID, Content myContent, string roid, string config, DateTime dts, string userID, RODb myRODb) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.Add", 0); @@ -792,11 +697,15 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID); // Output Calculated Columns - SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int); - param_ROUsageID.Direction = ParameterDirection.Output; + SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_ROUsageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -811,7 +720,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RoUsage.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -834,42 +743,48 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.SQLUpdate", GetHashCode()); try { - if (_MyContent != null) _MyContent.Update(); - if (_MyRODb != null) _MyRODb.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyContent?.Update(); + _MyRODb?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateRoUsage"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID); - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@ROID", _ROID); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - cm.Parameters.AddWithValue("@RODbID", RODbID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateRoUsage"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID); + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@ROID", _ROID); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + cm.Parameters.AddWithValue("@RODbID", RODbID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -882,18 +797,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = RoUsage.Add(cn, ref _ROUsageID, _MyContent, _ROID, _Config, _DTS, _UserID, _MyRODb); - else - _LastChanged = RoUsage.Update(cn, ref _ROUsageID, _ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = RoUsage.Add(cn, ref _ROUsageID, _MyContent, _ROID, _Config, _DTS, _UserID, _MyRODb); + else + _LastChanged = RoUsage.Update(cn, ref _ROUsageID, _ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int rOUsageID, int contentID, string roid, string config, DateTime dts, string userID, ref byte[] lastChanged, int rODbID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.Update", 0); @@ -914,8 +833,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@RODbID", rODbID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -929,12 +850,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RoUsage.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ROUsageID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.DataPortal_Delete", GetHashCode()); @@ -959,7 +880,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("RoUsage.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int rOUsageID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.Remove", 0); @@ -1000,16 +921,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ROUsageID; + private readonly int _ROUsageID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int rOUsageID) - { - _ROUsageID = rOUsageID; - } + public bool Exists => _exists; + public ExistsCommand(int rOUsageID) => _ROUsageID = rOUsageID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.DataPortal_Execute", GetHashCode()); @@ -1017,7 +932,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1025,7 +940,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsRoUsage"; cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1039,7 +954,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - RoUsageExtension _RoUsageExtension = new RoUsageExtension(); + readonly RoUsageExtension _RoUsageExtension = new RoUsageExtension(); [Serializable()] partial class RoUsageExtension : extensionBase { @@ -1048,18 +963,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultContentID - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultContentID => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1088,61 +994,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoUsage) + if (destType == typeof(string) && value is RoUsage usage) { // Return the ToString value - return ((RoUsage)value).ToString(); + return usage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion -} // Namespace - - -//// The following is a sample Extension File. You can use it to create RoUsageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RoUsage -// { -// partial class RoUsageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultContentID -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} +} // Namespace \ No newline at end of file diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfo.cs index 1c141b88..aca539ae 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class RoUsageInfo : ReadOnlyBase, IDisposable { public event RoUsageInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(RoUsageInfo roUsageInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(roUsageInfo)) _CacheList.Remove(roUsageInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected RoUsage _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ROUsageID; [System.ComponentModel.DataObjectField(true, true)] public int ROUsageID @@ -175,32 +159,19 @@ namespace VEPROMS.CSLA.Library return _MyRODb; } } - // CSLATODO: Replace base RoUsageInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RoUsageInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check RoUsageInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RoUsageInfo - protected override object GetIdValue() - { - return MyRoUsageInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRoUsageInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _RoUsageInfoUnique = 0; - private static int RoUsageInfoUnique - { get { return ++_RoUsageInfoUnique; } } - private int _MyRoUsageInfoUnique = RoUsageInfoUnique; - public int MyRoUsageInfoUnique // Absolutely Unique ID - Info - { get { return _MyRoUsageInfoUnique; } } + private static int RoUsageInfoUnique => ++_RoUsageInfoUnique; + private readonly int _MyRoUsageInfoUnique = RoUsageInfoUnique; + // Absolutely Unique ID - Info + public int MyRoUsageInfoUnique => _MyRoUsageInfoUnique; protected RoUsageInfo() {/* require use of factory methods */ AddToCache(this); @@ -209,15 +180,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RoUsageInfo() { _CountFinalized++; @@ -234,10 +201,7 @@ namespace VEPROMS.CSLA.Library if (listRoUsageInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ROUsageID.ToString()); // remove the list } - public virtual RoUsage Get() - { - return _Editable = RoUsage.Get(_ROUsageID); - } + public virtual RoUsage Get() => _Editable = RoUsage.Get(_ROUsageID); public static void Refresh(RoUsage tmp) { string key = tmp.ROUsageID.ToString(); @@ -250,22 +214,22 @@ namespace VEPROMS.CSLA.Library { if (_ContentID != tmp.ContentID) { - if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for old value + MyContent?.RefreshContentRoUsages(); // Update List for old value _ContentID = tmp.ContentID; // Update the value } _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for new value + MyContent?.RefreshContentRoUsages(); // Update List for new value _ROID = tmp.ROID; _Config = tmp.Config; _DTS = tmp.DTS; _UserID = tmp.UserID; if (_RODbID != tmp.RODbID) { - if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for old value + MyRODb?.RefreshRODbRoUsages(); // Update List for old value _RODbID = tmp.RODbID; // Update the value } _MyRODb = null; // Reset list so that the next line gets a new list - if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for new value + MyRODb?.RefreshRODbRoUsages(); // Update List for new value _RoUsageInfoExtension.Refresh(this); OnChange();// raise an event } @@ -285,11 +249,11 @@ namespace VEPROMS.CSLA.Library _UserID = tmp.UserID; if (_RODbID != tmp.RODbID) { - if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for old value + MyRODb?.RefreshRODbRoUsages(); // Update List for old value _RODbID = tmp.RODbID; // Update the value } _MyRODb = null; // Reset list so that the next line gets a new list - if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for new value + MyRODb?.RefreshRODbRoUsages(); // Update List for new value _RoUsageInfoExtension.Refresh(this); OnChange();// raise an event } @@ -305,11 +269,11 @@ namespace VEPROMS.CSLA.Library { if (_ContentID != tmp.ContentID) { - if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for old value + MyContent?.RefreshContentRoUsages(); // Update List for old value _ContentID = tmp.ContentID; // Update the value } _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for new value + MyContent?.RefreshContentRoUsages(); // Update List for new value _ROID = tmp.ROID; _Config = tmp.Config; _DTS = tmp.DTS; @@ -319,8 +283,6 @@ namespace VEPROMS.CSLA.Library } public static RoUsageInfo Get(int rOUsageID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a RoUsage"); try { RoUsageInfo tmp = GetCachedByPrimaryKey(rOUsageID); @@ -359,13 +321,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ROUsageID; - public int ROUsageID - { get { return _ROUsageID; } } - public PKCriteria(int rOUsageID) - { - _ROUsageID = rOUsageID; - } + private readonly int _ROUsageID; + public int ROUsageID => _ROUsageID; + public PKCriteria(int rOUsageID) => _ROUsageID = rOUsageID; } private void ReadData(SafeDataReader dr) { @@ -426,7 +384,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - RoUsageInfoExtension _RoUsageInfoExtension = new RoUsageInfoExtension(); + readonly RoUsageInfoExtension _RoUsageInfoExtension = new RoUsageInfoExtension(); [Serializable()] partial class RoUsageInfoExtension : extensionBase { } [Serializable()] @@ -442,10 +400,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoUsageInfo) + if (destType == typeof(string) && value is RoUsageInfo info) { // Return the ToString value - return ((RoUsageInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfoList.cs index 9fef4117..f43c049c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoUsageInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (RoUsageInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~RoUsageInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RoUsageInfoList() { _CountFinalized++; } @@ -97,15 +90,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoUsageInfoList.Get", ex); } } - //public static RoUsageInfoList GetByFolder(FolderInfo fi) - //{ - //} public static RoUsageInfoList GetByDocVersion(DocVersionInfo dvi) { try { - //if (_RoUsageInfoList != null) - // return _RoUsageInfoList; RoUsageInfoList tmp = DataPortal.Fetch(new VersionIDCriteria(dvi.VersionID)); RoUsageInfo.AddList(tmp); tmp.AddEvents(); @@ -121,8 +109,6 @@ namespace VEPROMS.CSLA.Library { try { - //if (_RoUsageInfoList != null) - // return _RoUsageInfoList; RoUsageInfoList tmp = DataPortal.Fetch(new ItemIDCriteria(pi.ItemID)); RoUsageInfo.AddList(tmp); tmp.AddEvents(); @@ -134,27 +120,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoUsageInfoList.Get", ex); } } - - /// - /// Reset the list of all RoUsageInfo. - /// - public static void Reset() - { - _RoUsageInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static RoUsageInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on RoUsageInfoList.Get", ex); - // } - //} - public static RoUsageInfoList GetByContentID(int contentID) + + /// + /// Reset the list of all RoUsageInfo. + /// + public static void Reset() => _RoUsageInfoList = null; + public static RoUsageInfoList GetByContentID(int contentID) { try { @@ -189,11 +160,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class VersionIDCriteria { - public VersionIDCriteria(int versionID) - { - _VersionID = versionID; - } - private int _VersionID; + public VersionIDCriteria(int versionID) => _VersionID = versionID; + private int _VersionID; public int VersionID { get { return _VersionID; } @@ -202,7 +170,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(VersionIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -217,7 +185,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RoUsageInfo(dr)); + while (dr.Read()) Add(new RoUsageInfo(dr)); IsReadOnly = true; } } @@ -228,16 +196,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ItemIDCriteria { - public ItemIDCriteria(int itemID) - { - _ItemID = itemID; - } - private int _ItemID; + public ItemIDCriteria(int itemID) => _ItemID = itemID; + private int _ItemID; public int ItemID { get { return _ItemID; } @@ -246,7 +211,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ItemIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -261,7 +226,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RoUsageInfo(dr)); + while (dr.Read()) Add(new RoUsageInfo(dr)); IsReadOnly = true; } } @@ -272,11 +237,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -290,7 +255,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RoUsageInfo(dr)); + while (dr.Read()) Add(new RoUsageInfo(dr)); IsReadOnly = true; } } @@ -301,16 +266,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ContentIDCriteria { - public ContentIDCriteria(int contentID) - { - _ContentID = contentID; - } - private int _ContentID; + public ContentIDCriteria(int contentID) => _ContentID = contentID; + private int _ContentID; public int ContentID { get { return _ContentID; } @@ -319,7 +281,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ContentIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_FetchContentID", GetHashCode()); try { @@ -334,7 +296,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RoUsageInfo(dr)); + while (dr.Read()) Add(new RoUsageInfo(dr)); IsReadOnly = true; } } @@ -345,16 +307,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_FetchContentID", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class RODbIDCriteria { - public RODbIDCriteria(int rODbID) - { - _RODbID = rODbID; - } - private int _RODbID; + public RODbIDCriteria(int rODbID) => _RODbID = rODbID; + private int _RODbID; public int RODbID { get { return _RODbID; } @@ -363,7 +322,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RODbIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_FetchRODbID", GetHashCode()); try { @@ -378,7 +337,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new RoUsageInfo(dr)); + while (dr.Read()) Add(new RoUsageInfo(dr)); IsReadOnly = true; } } @@ -389,48 +348,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_FetchRODbID", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RoUsageInfoListPropertyDescriptor pd = new RoUsageInfoListPropertyDescriptor(this, i); @@ -447,7 +395,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RoUsageInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private RoUsageInfo Item { get { return (RoUsageInfo)_Item; } } public RoUsageInfoListPropertyDescriptor(RoUsageInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -456,10 +403,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoUsageInfoList) + if (destType == typeof(string) && value is RoUsageInfoList list) { // Return department and department role separated by comma. - return ((RoUsageInfoList)value).Items.Count.ToString() + " RoUsages"; + return $"{list.Items.Count} RoUsages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Role.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Role.cs index 1e497a4c..410241e8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Role.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Role.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -82,6 +80,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Role role) { @@ -91,7 +90,9 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(role)) _CacheList.Remove(role); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByName = new Dictionary>(); private static void ConvertListToDictionary() { @@ -126,15 +127,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextRID = -1; - public static int NextRID - { - get { return _nextRID--; } - } + public static int NextRID => _nextRID--; private int _RID; [System.ComponentModel.DataObjectField(true, true)] public int RID @@ -252,10 +247,7 @@ namespace VEPROMS.CSLA.Library return _RoleAssignments; } } - public void Reset_RoleAssignments() - { - _RoleAssignmentCount = -1; - } + public void Reset_RoleAssignments() => _RoleAssignmentCount = -1; private int _RolePermissionCount = 0; /// /// Count of RolePermissions for this Role @@ -287,10 +279,7 @@ namespace VEPROMS.CSLA.Library return _RolePermissions; } } - public void Reset_RolePermissions() - { - _RolePermissionCount = -1; - } + public void Reset_RolePermissions() => _RolePermissionCount = -1; public override bool IsDirty { get @@ -305,37 +294,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_RoleAssignments == null ? false : _RoleAssignments.IsDirtyList(list)) || (_RolePermissions == null ? false : _RolePermissions.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_RoleAssignments != null && _RoleAssignments.IsDirtyList(list)) || (_RolePermissions != null && _RolePermissions.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_RoleAssignments == null ? true : _RoleAssignments.IsValidList(list)) && (_RolePermissions == null ? true : _RolePermissions.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_RoleAssignments == null || _RoleAssignments.IsValidList(list)) && (_RolePermissions == null || _RolePermissions.IsValidList(list)); } - // CSLATODO: Replace base Role.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Role - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Role.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Role - protected override object GetIdValue() - { - return MyRoleUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRoleUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -365,8 +339,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -395,31 +369,11 @@ namespace VEPROMS.CSLA.Library _RoleExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(RID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Title, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Title, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); _RoleExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -427,56 +381,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _RoleExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _RoleAssignmentCount; - usedByCount += _RolePermissionCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RoleUnique = 0; - protected static int RoleUnique - { get { return ++_RoleUnique; } } - private int _MyRoleUnique = RoleUnique; - public int MyRoleUnique // Absolutely Unique ID - Editable - { get { return _MyRoleUnique; } } + protected static int RoleUnique => ++_RoleUnique; + private readonly int _MyRoleUnique = RoleUnique; + // Absolutely Unique ID - Editable + public int MyRoleUnique => _MyRoleUnique; protected Role() {/* require use of factory methods */ AddToCache(this); @@ -485,15 +397,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Role() { _CountFinalized++; @@ -530,8 +438,6 @@ namespace VEPROMS.CSLA.Library } public static Role New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Role"); try { return DataPortal.Create(); @@ -591,8 +497,6 @@ namespace VEPROMS.CSLA.Library } public static Role Get(int rid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Role"); try { Role tmp = GetCachedByPrimaryKey(rid); @@ -615,8 +519,6 @@ namespace VEPROMS.CSLA.Library } public static Role GetByName(string name) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Role"); try { Role tmp = GetCachedByName(name); @@ -642,14 +544,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Role(dr); return null; } - internal Role(SafeDataReader dr) - { - ReadData(dr); - } + internal Role(SafeDataReader dr) => ReadData(dr); public static void Delete(int rid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Role"); try { DataPortal.Delete(new PKCriteria(rid)); @@ -661,12 +558,6 @@ namespace VEPROMS.CSLA.Library } public override Role Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Role"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Role"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Role"); try { BuildRefreshList(); @@ -686,24 +577,16 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _RID; - public int RID - { get { return _RID; } } - public PKCriteria(int rid) - { - _RID = rid; - } + private readonly int _RID; + public int RID => _RID; + public PKCriteria(int rid) => _RID = rid; } [Serializable()] private class NameCriteria { - private string _Name; - public string Name - { get { return _Name; } } - public NameCriteria(string name) - { - _Name = name; - } + private readonly string _Name; + public string Name => _Name; + public NameCriteria(string name) => _Name = name; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -816,7 +699,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Role.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -841,40 +724,48 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addRole"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_RID = new SqlParameter("@newRID", SqlDbType.Int); - param_RID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_RID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _RID = (int)cm.Parameters["@newRID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addRole"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_RID = new SqlParameter("@newRID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_RID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _RID = (int)cm.Parameters["@newRID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_RoleAssignments != null) _RoleAssignments.Update(this); - if (_RolePermissions != null) _RolePermissions.Update(this); + _RoleAssignments?.Update(this); + _RolePermissions?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -884,7 +775,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Role.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int rid, string name, string title, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.Add", 0); @@ -901,11 +792,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_RID = new SqlParameter("@newRID", SqlDbType.Int); - param_RID.Direction = ParameterDirection.Output; + SqlParameter param_RID = new SqlParameter("@newRID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_RID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -920,7 +815,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Role.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -943,42 +838,48 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateRole"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@RID", _RID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Title", _Title); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateRole"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@RID", _RID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Title", _Title); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_RoleAssignments != null) _RoleAssignments.Update(this); - if (_RolePermissions != null) _RolePermissions.Update(this); + _RoleAssignments?.Update(this); + _RolePermissions?.Update(this); } catch (Exception ex) { @@ -989,20 +890,24 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Role.Add(cn, ref _RID, _Name, _Title, _DTS, _UsrID); - else - _LastChanged = Role.Update(cn, ref _RID, _Name, _Title, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Role.Add(cn, ref _RID, _Name, _Title, _DTS, _UsrID); + else + _LastChanged = Role.Update(cn, ref _RID, _Name, _Title, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } - if (_RoleAssignments != null) _RoleAssignments.Update(this); - if (_RolePermissions != null) _RolePermissions.Update(this); + _RoleAssignments?.Update(this); + _RolePermissions?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int rid, string name, string title, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.Update", 0); @@ -1021,8 +926,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1036,12 +943,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Role.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_RID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.DataPortal_Delete", GetHashCode()); @@ -1066,7 +973,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Role.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int rid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.Remove", 0); @@ -1107,16 +1014,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _RID; + private readonly int _RID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int rid) - { - _RID = rid; - } + public bool Exists => _exists; + public ExistsCommand(int rid) => _RID = rid; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Role.DataPortal_Execute", GetHashCode()); @@ -1124,7 +1025,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1146,7 +1047,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - RoleExtension _RoleExtension = new RoleExtension(); + readonly RoleExtension _RoleExtension = new RoleExtension(); [Serializable()] partial class RoleExtension : extensionBase { @@ -1155,14 +1056,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1191,57 +1086,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Role) + if (destType == typeof(string) && value is Role role) { // Return the ToString value - return ((Role)value).ToString(); + return role.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RoleExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Role -// { -// partial class RoleExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignment.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignment.cs index e1d072f9..b4f04dc8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignment.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignment.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _AID; [System.ComponentModel.DataObjectField(true, true)] public int AID @@ -352,19 +346,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RoleAssignment - protected override object GetIdValue() - { - return MyRoleAssignmentUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RoleAssignment.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RoleAssignment - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyRoleAssignmentUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -379,18 +361,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyGroup == null ? false : _MyGroup.IsDirtyList(list)) || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyGroup != null && _MyGroup.IsDirtyList(list)) || (_MyFolder != null && _MyFolder.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyGroup == null ? true : _MyGroup.IsValidList(list)) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyGroup == null || _MyGroup.IsValidList(list)) && (_MyFolder == null || _MyFolder.IsValidList(list)); } #endregion #region ValidationRules @@ -421,8 +400,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -484,80 +463,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(AID, ""); - //AuthorizationRules.AllowRead(GID, ""); - //AuthorizationRules.AllowWrite(GID, ""); - //AuthorizationRules.AllowRead(FolderID, ""); - //AuthorizationRules.AllowWrite(FolderID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RoleAssignmentUnique = 0; - private static int RoleAssignmentUnique - { get { return ++_RoleAssignmentUnique; } } - private int _MyRoleAssignmentUnique = RoleAssignmentUnique; - public int MyRoleAssignmentUnique // Absolutely Unique ID - Editable FK - { get { return _MyRoleAssignmentUnique; } } - internal static RoleAssignment New(Group myGroup, Folder myFolder) - { - return new RoleAssignment(myGroup, myFolder); - } - internal static RoleAssignment Get(SafeDataReader dr) - { - return new RoleAssignment(dr); - } + private static int RoleAssignmentUnique => ++_RoleAssignmentUnique; + private readonly int _MyRoleAssignmentUnique = RoleAssignmentUnique; + // Absolutely Unique ID - Editable FK + public int MyRoleAssignmentUnique => _MyRoleAssignmentUnique; + internal static RoleAssignment New(Group myGroup, Folder myFolder) => new RoleAssignment(myGroup, myFolder); + internal static RoleAssignment Get(SafeDataReader dr) => new RoleAssignment(dr); public RoleAssignment() { MarkAsChild(); @@ -588,15 +509,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RoleAssignment() { _CountFinalized++; @@ -648,33 +565,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Role myRole) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, myRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, myRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); + } + MarkOld(); } internal void Update(Role myRole) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Assignment.Update(cn, ref _AID, _GID, myRole.RID, _FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Assignment.Update(cn, ref _AID, _GID, myRole.RID, _FolderID, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Role myRole) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Assignment.Remove(cn, _AID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Assignment.Remove(cn, _AID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RoleAssignmentExtension _RoleAssignmentExtension = new RoleAssignmentExtension(); + readonly RoleAssignmentExtension _RoleAssignmentExtension = new RoleAssignmentExtension(); [Serializable()] partial class RoleAssignmentExtension : extensionBase { @@ -683,18 +613,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -723,61 +644,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoleAssignment) + if (destType == typeof(string) && value is RoleAssignment assignment) { // Return the ToString value - return ((RoleAssignment)value).ToString(); + return assignment.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RoleAssignmentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RoleAssignment -// { -// partial class RoleAssignmentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignments.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignments.cs index e03ec266..8a875c4f 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignments.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoleAssignments.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RoleAssignment this[Assignment myAssignment] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RoleAssignment this[Assignment myAssignment] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RoleAssignment GetItem(Assignment myAssignment) + public new System.Collections.Generic.IList Items => base.Items; + public RoleAssignment GetItem(Assignment myAssignment) { foreach (RoleAssignment assignment in this) if (assignment.AID == myAssignment.AID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RoleAssignment Add(Group myGroup, Folder myFolder) // One to Many { RoleAssignment assignment = RoleAssignment.New(myGroup, myFolder); - this.Add(assignment); + Add(assignment); return assignment; } public void Remove(Assignment myAssignment) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RoleAssignment child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RoleAssignment child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RoleAssignments New() - { - return new RoleAssignments(); - } - internal static RoleAssignments Get(SafeDataReader dr) - { - return new RoleAssignments(dr); - } - public static RoleAssignments GetByRID(int rid) + #endregion + #region Factory Methods + internal static RoleAssignments New() => new RoleAssignments(); + internal static RoleAssignments Get(SafeDataReader dr) => new RoleAssignments(dr); + public static RoleAssignments GetByRID(int rid) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoleAssignments.GetByRID", ex); } } - private RoleAssignments() - { - MarkAsChild(); - } - internal RoleAssignments(SafeDataReader dr) + private RoleAssignments() => MarkAsChild(); + internal RoleAssignments(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RoleAssignments() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RoleAssignments() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RoleAssignment.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RoleAssignment.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RIDCriteria { - public RIDCriteria(int rid) - { - _RID = rid; - } - private int _RID; + public RIDCriteria(int rid) => _RID = rid; + private int _RID; public int RID { get { return _RID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoleAssignments.DataPortal_FetchRID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RoleAssignment(dr)); + while (dr.Read()) Add(new RoleAssignment(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RoleAssignments.DataPortal_FetchRID", ex); throw new DbCslaException("RoleAssignments.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Role role) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RoleAssignmentsPropertyDescriptor pd = new RoleAssignmentsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RoleAssignmentsPropertyDescriptor : vlnListPropertyDescriptor { - private RoleAssignment Item { get { return (RoleAssignment)_Item; } } public RoleAssignmentsPropertyDescriptor(RoleAssignments collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoleAssignments) + if (destType == typeof(string) && value is RoleAssignments assignments) { // Return department and department role separated by comma. - return ((RoleAssignments)value).Items.Count.ToString() + " Assignments"; + return $"{assignments.Items.Count} Assignments"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfo.cs index efcc37ea..21165cb3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class RoleInfo : ReadOnlyBase, IDisposable { public event RoleInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(RoleInfo roleInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(roleInfo)) _CacheList.Remove(roleInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Role _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _RID; [System.ComponentModel.DataObjectField(true, true)] public int RID @@ -207,32 +191,19 @@ namespace VEPROMS.CSLA.Library foreach (RoleInfo tmp in _CacheByPrimaryKey[_RID.ToString()]) tmp._RolePermissionCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base RoleInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RoleInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check RoleInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RoleInfo - protected override object GetIdValue() - { - return MyRoleInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyRoleInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _RoleInfoUnique = 0; - private static int RoleInfoUnique - { get { return ++_RoleInfoUnique; } } - private int _MyRoleInfoUnique = RoleInfoUnique; - public int MyRoleInfoUnique // Absolutely Unique ID - Info - { get { return _MyRoleInfoUnique; } } + private static int RoleInfoUnique => ++_RoleInfoUnique; + private readonly int _MyRoleInfoUnique = RoleInfoUnique; + // Absolutely Unique ID - Info + public int MyRoleInfoUnique => _MyRoleInfoUnique; protected RoleInfo() {/* require use of factory methods */ AddToCache(this); @@ -241,15 +212,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RoleInfo() { _CountFinalized++; @@ -266,10 +233,7 @@ namespace VEPROMS.CSLA.Library if (listRoleInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(RID.ToString()); // remove the list } - public virtual Role Get() - { - return _Editable = Role.Get(_RID); - } + public virtual Role Get() => _Editable = Role.Get(_RID); public static void Refresh(Role tmp) { string key = tmp.RID.ToString(); @@ -289,8 +253,6 @@ namespace VEPROMS.CSLA.Library } public static RoleInfo Get(int rid) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Role"); try { RoleInfo tmp = GetCachedByPrimaryKey(rid); @@ -329,13 +291,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _RID; - public int RID - { get { return _RID; } } - public PKCriteria(int rid) - { - _RID = rid; - } + private readonly int _RID; + public int RID => _RID; + public PKCriteria(int rid) => _RID = rid; } private void ReadData(SafeDataReader dr) { @@ -396,7 +354,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - RoleInfoExtension _RoleInfoExtension = new RoleInfoExtension(); + readonly RoleInfoExtension _RoleInfoExtension = new RoleInfoExtension(); [Serializable()] partial class RoleInfoExtension : extensionBase { } [Serializable()] @@ -412,10 +370,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoleInfo) + if (destType == typeof(string) && value is RoleInfo info) { // Return the ToString value - return ((RoleInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfoList.cs index 55bbf650..5a4daff6 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RoleInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (RoleInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RoleInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RoleInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RoleInfoList.Get", ex); } } - /// - /// Reset the list of all RoleInfo. - /// - public static void Reset() - { - _RoleInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static RoleInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on RoleInfoList.Get", ex); - // } - //} - private RoleInfoList() + /// + /// Reset the list of all RoleInfo. + /// + public static void Reset() => _RoleInfoList = null; + private RoleInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -149,35 +127,25 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return GetProperties(); } /// /// Called to get the properties of this type. @@ -205,7 +173,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RoleInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private RoleInfo Item { get { return (RoleInfo)_Item; } } public RoleInfoListPropertyDescriptor(RoleInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +181,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RoleInfoList) + if (destType == typeof(string) && value is RoleInfoList list) { // Return department and department role separated by comma. - return ((RoleInfoList)value).Items.Count.ToString() + " Roles"; + return $"{list.Items.Count} Roles"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RolePermission.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RolePermission.cs index d48fff75..10dfb501 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RolePermission.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RolePermission.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _PID; [System.ComponentModel.DataObjectField(true, true)] public int PID @@ -260,35 +254,13 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current RolePermission - protected override object GetIdValue() - { - return MyRolePermissionUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base RolePermission.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current RolePermission - //public override string ToString() - //{ - // return base.ToString(); - //} - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } + protected override object GetIdValue() => MyRolePermissionUnique; // Absolutely Unique ID + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; #endregion #region ValidationRules [NonSerialized] @@ -316,8 +288,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -362,86 +334,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(PID, ""); - //AuthorizationRules.AllowRead(PermLevel, ""); - //AuthorizationRules.AllowWrite(PermLevel, ""); - //AuthorizationRules.AllowRead(VersionType, ""); - //AuthorizationRules.AllowWrite(VersionType, ""); - //AuthorizationRules.AllowRead(PermValue, ""); - //AuthorizationRules.AllowWrite(PermValue, ""); - //AuthorizationRules.AllowRead(PermAD, ""); - //AuthorizationRules.AllowWrite(PermAD, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _RolePermissionUnique = 0; - private static int RolePermissionUnique - { get { return ++_RolePermissionUnique; } } - private int _MyRolePermissionUnique = RolePermissionUnique; - public int MyRolePermissionUnique // Absolutely Unique ID - Editable FK - { get { return _MyRolePermissionUnique; } } - internal static RolePermission New(int permLevel, int versionType, int permValue) - { - return new RolePermission(permLevel, versionType, permValue); - } - internal static RolePermission Get(SafeDataReader dr) - { - return new RolePermission(dr); - } + private static int RolePermissionUnique => ++_RolePermissionUnique; + private readonly int _MyRolePermissionUnique = RolePermissionUnique; + // Absolutely Unique ID - Editable FK + public int MyRolePermissionUnique => _MyRolePermissionUnique; + internal static RolePermission New(int permLevel, int versionType, int permValue) => new RolePermission(permLevel, versionType, permValue); + internal static RolePermission Get(SafeDataReader dr) => new RolePermission(dr); public RolePermission() { MarkAsChild(); @@ -475,15 +383,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~RolePermission() { _CountFinalized++; @@ -523,33 +427,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Role myRole) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Permission.Add(cn, ref _PID, myRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Permission.Add(cn, ref _PID, myRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + } + MarkOld(); } internal void Update(Role myRole) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Permission.Update(cn, ref _PID, myRole.RID, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Permission.Update(cn, ref _PID, myRole.RID, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Role myRole) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Permission.Remove(cn, _PID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Permission.Remove(cn, _PID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - RolePermissionExtension _RolePermissionExtension = new RolePermissionExtension(); + readonly RolePermissionExtension _RolePermissionExtension = new RolePermissionExtension(); [Serializable()] partial class RolePermissionExtension : extensionBase { @@ -558,22 +475,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultPermAD - { - get { return 0; } - } - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultPermAD => 0; + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -602,65 +507,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RolePermission) + if (destType == typeof(string) && value is RolePermission permission) { // Return the ToString value - return ((RolePermission)value).ToString(); + return permission.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create RolePermissionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class RolePermission -// { -// partial class RolePermissionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultPermAD -// { -// get { return 0; } -// } -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/RolePermissions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/RolePermissions.cs index 09cea5da..2abe2140 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/RolePermissions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/RolePermissions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public RolePermission this[Permission myPermission] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public RolePermission this[Permission myPermission] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public RolePermission GetItem(Permission myPermission) + public new System.Collections.Generic.IList Items => base.Items; + public RolePermission GetItem(Permission myPermission) { foreach (RolePermission permission in this) if (permission.PID == myPermission.PID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public RolePermission Add(int permLevel, int versionType, int permValue) // One to Many { RolePermission permission = RolePermission.New(permLevel, versionType, permValue); - this.Add(permission); + Add(permission); return permission; } public void Remove(Permission myPermission) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (RolePermission child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (RolePermission child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static RolePermissions New() - { - return new RolePermissions(); - } - internal static RolePermissions Get(SafeDataReader dr) - { - return new RolePermissions(dr); - } - public static RolePermissions GetByRID(int rid) + #endregion + #region Factory Methods + internal static RolePermissions New() => new RolePermissions(); + internal static RolePermissions Get(SafeDataReader dr) => new RolePermissions(dr); + public static RolePermissions GetByRID(int rid) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on RolePermissions.GetByRID", ex); } } - private RolePermissions() - { - MarkAsChild(); - } - internal RolePermissions(SafeDataReader dr) + private RolePermissions() => MarkAsChild(); + internal RolePermissions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~RolePermissions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~RolePermissions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(RolePermission.Get(dr)); - this.RaiseListChangedEvents = true; + Add(RolePermission.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class RIDCriteria { - public RIDCriteria(int rid) - { - _RID = rid; - } - private int _RID; + public RIDCriteria(int rid) => _RID = rid; + private int _RID; public int RID { get { return _RID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RolePermissions.DataPortal_FetchRID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new RolePermission(dr)); + while (dr.Read()) Add(new RolePermission(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("RolePermissions.DataPortal_FetchRID", ex); throw new DbCslaException("RolePermissions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Role role) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection RolePermissionsPropertyDescriptor pd = new RolePermissionsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class RolePermissionsPropertyDescriptor : vlnListPropertyDescriptor { - private RolePermission Item { get { return (RolePermission)_Item; } } public RolePermissionsPropertyDescriptor(RolePermissions collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is RolePermissions) + if (destType == typeof(string) && value is RolePermissions permissions) { // Return department and department role separated by comma. - return ((RolePermissions)value).Items.Count.ToString() + " Permissions"; + return $"{permissions.Items.Count} Permissions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Session.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Session.cs index 713d67e5..95103f02 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Session.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Session.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshSessions.Add(this); } - private void ClearRefreshList() - { - _RefreshSessions = new List(); - } + private void ClearRefreshList() => _RefreshSessions = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Session session) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(session)) _CacheList.Remove(session); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextSessionID = -1; - public static int NextSessionID - { - get { return _nextSessionID--; } - } + public static int NextSessionID => _nextSessionID--; private int _SessionID; [System.ComponentModel.DataObjectField(true, true)] public int SessionID @@ -220,40 +211,14 @@ namespace VEPROMS.CSLA.Library } } } - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base Session.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Session - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check Session.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Session - protected override object GetIdValue() - { - return MySessionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MySessionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -281,8 +246,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -306,35 +271,11 @@ namespace VEPROMS.CSLA.Library _SessionExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(SessionID, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(DTSDtart, ""); - //AuthorizationRules.AllowRead(DTSEnd, ""); - //AuthorizationRules.AllowRead(DTSActivity, ""); - //AuthorizationRules.AllowRead(MachineName, ""); - //AuthorizationRules.AllowRead(ProcessID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(DTSDtart, ""); - //AuthorizationRules.AllowWrite(DTSEnd, ""); - //AuthorizationRules.AllowWrite(DTSActivity, ""); - //AuthorizationRules.AllowWrite(MachineName, ""); - //AuthorizationRules.AllowWrite(ProcessID, ""); _SessionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -342,42 +283,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _SessionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _SessionUnique = 0; - protected static int SessionUnique - { get { return ++_SessionUnique; } } - private int _MySessionUnique = SessionUnique; - public int MySessionUnique // Absolutely Unique ID - Editable - { get { return _MySessionUnique; } } + protected static int SessionUnique => ++_SessionUnique; + private readonly int _MySessionUnique = SessionUnique; + // Absolutely Unique ID - Editable + public int MySessionUnique => _MySessionUnique; protected Session() {/* require use of factory methods */ AddToCache(this); @@ -386,15 +299,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Session() { _CountFinalized++; @@ -419,8 +328,6 @@ namespace VEPROMS.CSLA.Library } public static Session New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Session"); try { return DataPortal.Create(); @@ -490,8 +397,6 @@ namespace VEPROMS.CSLA.Library } public static Session Get(int sessionID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Session"); try { Session tmp = GetCachedByPrimaryKey(sessionID); @@ -512,19 +417,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on Session.Get", ex); } } - public static Session Get(SafeDataReader dr) - { - if (dr.Read()) return new Session(dr); - return null; - } - internal Session(SafeDataReader dr) - { - ReadData(dr); - } + public static Session Get(SafeDataReader dr) => dr.Read() ? new Session(dr) : null; + internal Session(SafeDataReader dr) => ReadData(dr); public static void Delete(int sessionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Session"); try { DataPortal.Delete(new PKCriteria(sessionID)); @@ -536,12 +432,6 @@ namespace VEPROMS.CSLA.Library } public override Session Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Session"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Session"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Session"); try { BuildRefreshList(); @@ -561,13 +451,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _SessionID; - public int SessionID - { get { return _SessionID; } } - public PKCriteria(int sessionID) - { - _SessionID = sessionID; - } + private readonly int _SessionID; + public int SessionID => _SessionID; + public PKCriteria(int sessionID) => _SessionID = sessionID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -639,7 +525,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Session.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -664,38 +550,46 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addSession"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@UserID", _UserID); - if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart); - if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd); - if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity); - cm.Parameters.AddWithValue("@MachineName", _MachineName); - cm.Parameters.AddWithValue("@ProcessID", _ProcessID); - // Output Calculated Columns - SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int); - param_SessionID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_SessionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _SessionID = (int)cm.Parameters["@newSessionID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addSession"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@UserID", _UserID); + if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart); + if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd); + if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity); + cm.Parameters.AddWithValue("@MachineName", _MachineName); + cm.Parameters.AddWithValue("@ProcessID", _ProcessID); + // Output Calculated Columns + SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_SessionID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _SessionID = (int)cm.Parameters["@newSessionID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.SQLInsert", GetHashCode()); @@ -707,7 +601,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Session.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int sessionID, string userID, DateTime dTSDtart, DateTime? dTSEnd, DateTime dTSActivity, string machineName, int processID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.Add", 0); @@ -726,11 +620,15 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@MachineName", machineName); cm.Parameters.AddWithValue("@ProcessID", processID); // Output Calculated Columns - SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int); - param_SessionID.Direction = ParameterDirection.Output; + SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_SessionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -745,7 +643,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Session.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -768,40 +666,46 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateSession"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@SessionID", _SessionID); - cm.Parameters.AddWithValue("@UserID", _UserID); - if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart); - if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd); - if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - cm.Parameters.AddWithValue("@MachineName", _MachineName); - cm.Parameters.AddWithValue("@ProcessID", _ProcessID); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateSession"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@SessionID", _SessionID); + cm.Parameters.AddWithValue("@UserID", _UserID); + if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart); + if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd); + if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + cm.Parameters.AddWithValue("@MachineName", _MachineName); + cm.Parameters.AddWithValue("@ProcessID", _ProcessID); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -814,18 +718,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Session.Add(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, _MachineName, _ProcessID); - else - _LastChanged = Session.Update(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, ref _LastChanged, _MachineName, _ProcessID); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Session.Add(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, _MachineName, _ProcessID); + else + _LastChanged = Session.Update(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, ref _LastChanged, _MachineName, _ProcessID); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int sessionID, string userID, DateTime dTSDtart, DateTime? dTSEnd, DateTime dTSActivity, ref byte[] lastChanged, string machineName, int processID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.Update", 0); @@ -846,8 +754,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@MachineName", machineName); cm.Parameters.AddWithValue("@ProcessID", processID); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -861,12 +771,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Session.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_SessionID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.DataPortal_Delete", GetHashCode()); @@ -891,7 +801,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Session.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int sessionID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.Remove", 0); @@ -932,16 +842,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _SessionID; + private readonly int _SessionID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int sessionID) - { - _SessionID = sessionID; - } + public bool Exists => _exists; + public ExistsCommand(int sessionID) => _SessionID = sessionID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.DataPortal_Execute", GetHashCode()); @@ -949,7 +853,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -957,7 +861,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsSession"; cm.Parameters.AddWithValue("@SessionID", _SessionID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -971,7 +875,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - SessionExtension _SessionExtension = new SessionExtension(); + readonly SessionExtension _SessionExtension = new SessionExtension(); [Serializable()] partial class SessionExtension : extensionBase { @@ -980,18 +884,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultUserID - { - get { return Environment.UserName.ToUpper(); } - } - public virtual DateTime DefaultDTSDtart - { - get { return DateTime.Now; } - } - public virtual DateTime DefaultDTSActivity - { - get { return DateTime.Now; } - } + public virtual string DefaultUserID => Environment.UserName.ToUpper(); + public virtual DateTime DefaultDTSDtart => DateTime.Now; + public virtual DateTime DefaultDTSActivity => DateTime.Now; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1020,61 +915,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Session) + if (destType == typeof(string) && value is Session mysession) { // Return the ToString value - return ((Session)value).ToString(); + return mysession.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create SessionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Session -// { -// partial class SessionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public virtual DateTime DefaultDTSDtart -// { -// get { return DateTime.Now; } -// } -// public virtual DateTime DefaultDTSActivity -// { -// get { return DateTime.Now; } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfo.cs index 01dd67ff..a1d60a8b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class SessionInfo : ReadOnlyBase, IDisposable { public event SessionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(SessionInfo sessionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(sessionInfo)) _CacheList.Remove(sessionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Session _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _SessionID; [System.ComponentModel.DataObjectField(true, true)] public int SessionID @@ -153,32 +137,19 @@ namespace VEPROMS.CSLA.Library return _ProcessID; } } - // CSLATODO: Replace base SessionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current SessionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check SessionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current SessionInfo - protected override object GetIdValue() - { - return MySessionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MySessionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _SessionInfoUnique = 0; - private static int SessionInfoUnique - { get { return ++_SessionInfoUnique; } } - private int _MySessionInfoUnique = SessionInfoUnique; - public int MySessionInfoUnique // Absolutely Unique ID - Info - { get { return _MySessionInfoUnique; } } + private static int SessionInfoUnique => ++_SessionInfoUnique; + private readonly int _MySessionInfoUnique = SessionInfoUnique; + // Absolutely Unique ID - Info + public int MySessionInfoUnique => _MySessionInfoUnique; protected SessionInfo() {/* require use of factory methods */ AddToCache(this); @@ -187,15 +158,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~SessionInfo() { _CountFinalized++; @@ -212,10 +179,7 @@ namespace VEPROMS.CSLA.Library if (listSessionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(SessionID.ToString()); // remove the list } - public virtual Session Get() - { - return _Editable = Session.Get(_SessionID); - } + public virtual Session Get() => _Editable = Session.Get(_SessionID); public static void Refresh(Session tmp) { string key = tmp.SessionID.ToString(); @@ -237,8 +201,6 @@ namespace VEPROMS.CSLA.Library } public static SessionInfo Get(int sessionID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Session"); try { SessionInfo tmp = GetCachedByPrimaryKey(sessionID); @@ -277,13 +239,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _SessionID; - public int SessionID - { get { return _SessionID; } } - public PKCriteria(int sessionID) - { - _SessionID = sessionID; - } + private readonly int _SessionID; + public int SessionID => _SessionID; + public PKCriteria(int sessionID) => _SessionID = sessionID; } private void ReadData(SafeDataReader dr) { @@ -346,7 +304,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - SessionInfoExtension _SessionInfoExtension = new SessionInfoExtension(); + readonly SessionInfoExtension _SessionInfoExtension = new SessionInfoExtension(); [Serializable()] partial class SessionInfoExtension : extensionBase { } [Serializable()] @@ -362,10 +320,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is SessionInfo) + if (destType == typeof(string) && value is SessionInfo info) { // Return the ToString value - return ((SessionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfoList.cs index 74ef18ba..7f325b16 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/SessionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (SessionInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~SessionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~SessionInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on SessionInfoList.Get", ex); } } - /// - /// Reset the list of all SessionInfo. - /// - public static void Reset() - { - _SessionInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static SessionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on SessionInfoList.Get", ex); - // } - //} - private SessionInfoList() + /// + /// Reset the list of all SessionInfo. + /// + public static void Reset() => _SessionInfoList = null; + private SessionInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new SessionInfo(dr)); + while (dr.Read()) Add(new SessionInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("SessionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection SessionInfoListPropertyDescriptor pd = new SessionInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class SessionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private SessionInfo Item { get { return (SessionInfo)_Item; } } public SessionInfoListPropertyDescriptor(SessionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is SessionInfoList) + if (destType == typeof(string) && value is SessionInfoList list) { // Return department and department role separated by comma. - return ((SessionInfoList)value).Items.Count.ToString() + " Sessions"; + return $"{list.Items.Count} Sessions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Stage.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Stage.cs index 05dcf71e..bd1928e9 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Stage.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Stage.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -82,6 +80,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Stage stage) { @@ -91,6 +90,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(stage)) _CacheList.Remove(stage); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -116,15 +116,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextStageID = -1; - public static int NextStageID - { - get { return _nextStageID--; } - } + public static int NextStageID => _nextStageID--; private int _StageID; [System.ComponentModel.DataObjectField(true, true)] public int StageID @@ -260,10 +254,7 @@ namespace VEPROMS.CSLA.Library return _StageChecks; } } - public void Reset_StageChecks() - { - _StageCheckCount = -1; - } + public void Reset_StageChecks() => _StageCheckCount = -1; private int _StageVersionCount = 0; /// /// Count of StageVersions for this Stage @@ -295,10 +286,7 @@ namespace VEPROMS.CSLA.Library return _StageVersions; } } - public void Reset_StageVersions() - { - _StageVersionCount = -1; - } + public void Reset_StageVersions() => _StageVersionCount = -1; public override bool IsDirty { get @@ -313,37 +301,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_StageChecks == null ? false : _StageChecks.IsDirtyList(list)) || (_StageVersions == null ? false : _StageVersions.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_StageChecks != null && _StageChecks.IsDirtyList(list)) || (_StageVersions != null && _StageVersions.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_StageChecks == null ? true : _StageChecks.IsValidList(list)) && (_StageVersions == null ? true : _StageVersions.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_StageChecks == null || _StageChecks.IsValidList(list)) && (_StageVersions == null || _StageVersions.IsValidList(list)); } - // CSLATODO: Replace base Stage.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Stage - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Stage.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Stage - protected override object GetIdValue() - { - return MyStageUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyStageUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -373,8 +346,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -401,33 +374,11 @@ namespace VEPROMS.CSLA.Library _StageExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(StageID, ""); - //AuthorizationRules.AllowRead(Name, ""); - //AuthorizationRules.AllowRead(Description, ""); - //AuthorizationRules.AllowRead(IsApproved, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(Name, ""); - //AuthorizationRules.AllowWrite(Description, ""); - //AuthorizationRules.AllowWrite(IsApproved, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _StageExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -435,56 +386,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _StageExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _StageCheckCount; - usedByCount += _StageVersionCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _StageUnique = 0; - protected static int StageUnique - { get { return ++_StageUnique; } } - private int _MyStageUnique = StageUnique; - public int MyStageUnique // Absolutely Unique ID - Editable - { get { return _MyStageUnique; } } + protected static int StageUnique => ++_StageUnique; + private readonly int _MyStageUnique = StageUnique; + // Absolutely Unique ID - Editable + public int MyStageUnique => _MyStageUnique; protected Stage() {/* require use of factory methods */ AddToCache(this); @@ -493,15 +402,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Stage() { _CountFinalized++; @@ -526,8 +431,6 @@ namespace VEPROMS.CSLA.Library } public static Stage New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Stage"); try { return DataPortal.Create(); @@ -594,8 +497,6 @@ namespace VEPROMS.CSLA.Library } public static Stage Get(int stageID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Stage"); try { Stage tmp = GetCachedByPrimaryKey(stageID); @@ -616,19 +517,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on Stage.Get", ex); } } - public static Stage Get(SafeDataReader dr) - { - if (dr.Read()) return new Stage(dr); - return null; - } - internal Stage(SafeDataReader dr) - { - ReadData(dr); - } + public static Stage Get(SafeDataReader dr) => dr.Read() ? new Stage(dr) : null; + internal Stage(SafeDataReader dr) => ReadData(dr); public static void Delete(int stageID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Stage"); try { DataPortal.Delete(new PKCriteria(stageID)); @@ -640,12 +532,6 @@ namespace VEPROMS.CSLA.Library } public override Stage Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Stage"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Stage"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Stage"); try { BuildRefreshList(); @@ -665,13 +551,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _StageID; - public int StageID - { get { return _StageID; } } - public PKCriteria(int stageID) - { - _StageID = stageID; - } + private readonly int _StageID; + public int StageID => _StageID; + public PKCriteria(int stageID) => _StageID = stageID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -750,7 +632,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Stage.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -775,41 +657,49 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addStage"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Description", _Description); - cm.Parameters.AddWithValue("@IsApproved", _IsApproved); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int); - param_StageID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_StageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _StageID = (int)cm.Parameters["@newStageID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addStage"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Description", _Description); + cm.Parameters.AddWithValue("@IsApproved", _IsApproved); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_StageID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _StageID = (int)cm.Parameters["@newStageID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_StageChecks != null) _StageChecks.Update(this); - if (_StageVersions != null) _StageVersions.Update(this); + _StageChecks?.Update(this); + _StageVersions?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -819,7 +709,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Stage.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int stageID, string name, string description, int isApproved, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.Add", 0); @@ -837,11 +727,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int); - param_StageID.Direction = ParameterDirection.Output; + SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_StageID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -856,7 +750,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Stage.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -879,43 +773,49 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateStage"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@StageID", _StageID); - cm.Parameters.AddWithValue("@Name", _Name); - cm.Parameters.AddWithValue("@Description", _Description); - cm.Parameters.AddWithValue("@IsApproved", _IsApproved); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateStage"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@StageID", _StageID); + cm.Parameters.AddWithValue("@Name", _Name); + cm.Parameters.AddWithValue("@Description", _Description); + cm.Parameters.AddWithValue("@IsApproved", _IsApproved); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_StageChecks != null) _StageChecks.Update(this); - if (_StageVersions != null) _StageVersions.Update(this); + _StageChecks?.Update(this); + _StageVersions?.Update(this); } catch (Exception ex) { @@ -926,20 +826,24 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Stage.Add(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID); - else - _LastChanged = Stage.Update(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Stage.Add(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID); + else + _LastChanged = Stage.Update(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_StageChecks != null) _StageChecks.Update(this); - if (_StageVersions != null) _StageVersions.Update(this); + _StageChecks?.Update(this); + _StageVersions?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int stageID, string name, string description, int isApproved, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.Update", 0); @@ -959,8 +863,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -974,12 +880,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Stage.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_StageID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.DataPortal_Delete", GetHashCode()); @@ -1004,7 +910,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Stage.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int stageID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.Remove", 0); @@ -1045,16 +951,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _StageID; + private readonly int _StageID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int stageID) - { - _StageID = stageID; - } + public bool Exists => _exists; + public ExistsCommand(int stageID) => _StageID = stageID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.DataPortal_Execute", GetHashCode()); @@ -1062,7 +962,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1070,7 +970,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsStage"; cm.Parameters.AddWithValue("@StageID", _StageID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1084,7 +984,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - StageExtension _StageExtension = new StageExtension(); + readonly StageExtension _StageExtension = new StageExtension(); [Serializable()] partial class StageExtension : extensionBase { @@ -1093,18 +993,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultIsApproved - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultIsApproved => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1133,61 +1024,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Stage) + if (destType == typeof(string) && value is Stage stage) { // Return the ToString value - return ((Stage)value).ToString(); + return stage.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create StageExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Stage -// { -// partial class StageExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultIsApproved -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/StageCheck.cs b/PROMS/VEPROMS.CSLA.Library/Generated/StageCheck.cs index c541becc..5a8988ba 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/StageCheck.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/StageCheck.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _CheckID; [System.ComponentModel.DataObjectField(true, true)] public int CheckID @@ -222,19 +216,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current StageCheck - protected override object GetIdValue() - { - return MyStageCheckUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base StageCheck.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current StageCheck - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyStageCheckUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -249,18 +231,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list)); } #endregion #region ValidationRules @@ -290,8 +269,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -316,76 +295,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(CheckID, ""); - //AuthorizationRules.AllowRead(RevisionID, ""); - //AuthorizationRules.AllowWrite(RevisionID, ""); - //AuthorizationRules.AllowRead(ConsistencyChecks, ""); - //AuthorizationRules.AllowWrite(ConsistencyChecks, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _StageCheckUnique = 0; - private static int StageCheckUnique - { get { return ++_StageCheckUnique; } } - private int _MyStageCheckUnique = StageCheckUnique; - public int MyStageCheckUnique // Absolutely Unique ID - Editable FK - { get { return _MyStageCheckUnique; } } - internal static StageCheck New(Revision myRevision) - { - return new StageCheck(myRevision); - } - internal static StageCheck Get(SafeDataReader dr) - { - return new StageCheck(dr); - } + private static int StageCheckUnique => ++_StageCheckUnique; + private readonly int _MyStageCheckUnique = StageCheckUnique; + // Absolutely Unique ID - Editable FK + public int MyStageCheckUnique => _MyStageCheckUnique; + internal static StageCheck New(Revision myRevision) => new StageCheck(myRevision); + internal static StageCheck Get(SafeDataReader dr) => new StageCheck(dr); public StageCheck() { MarkAsChild(); @@ -413,15 +338,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~StageCheck() { _CountFinalized++; @@ -464,33 +385,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Stage myStage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, myStage, _ConsistencyChecks, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, myStage, _ConsistencyChecks, _DTS, _UserID); + } + MarkOld(); } internal void Update(Stage myStage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Check.Update(cn, ref _CheckID, _RevisionID, myStage.StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Check.Update(cn, ref _CheckID, _RevisionID, myStage.StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Stage myStage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Check.Remove(cn, _CheckID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Check.Remove(cn, _CheckID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - StageCheckExtension _StageCheckExtension = new StageCheckExtension(); + readonly StageCheckExtension _StageCheckExtension = new StageCheckExtension(); [Serializable()] partial class StageCheckExtension : extensionBase { @@ -499,14 +433,8 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -535,57 +463,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is StageCheck) + if (destType == typeof(string) && value is StageCheck check) { // Return the ToString value - return ((StageCheck)value).ToString(); + return check.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create StageCheckExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class StageCheck -// { -// partial class StageCheckExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/StageChecks.cs b/PROMS/VEPROMS.CSLA.Library/Generated/StageChecks.cs index c9010b52..8b02f751 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/StageChecks.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/StageChecks.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public StageCheck this[Check myCheck] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public StageCheck this[Check myCheck] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public StageCheck GetItem(Check myCheck) + public new System.Collections.Generic.IList Items => base.Items; + public StageCheck GetItem(Check myCheck) { foreach (StageCheck check in this) if (check.CheckID == myCheck.CheckID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public StageCheck Add(Revision myRevision) // One to Many { StageCheck check = StageCheck.New(myRevision); - this.Add(check); + Add(check); return check; } public void Remove(Check myCheck) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (StageCheck child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (StageCheck child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static StageChecks New() - { - return new StageChecks(); - } - internal static StageChecks Get(SafeDataReader dr) - { - return new StageChecks(dr); - } - public static StageChecks GetByStageID(int stageID) + #endregion + #region Factory Methods + internal static StageChecks New() => new StageChecks(); + internal static StageChecks Get(SafeDataReader dr) => new StageChecks(dr); + public static StageChecks GetByStageID(int stageID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on StageChecks.GetByStageID", ex); } } - private StageChecks() - { - MarkAsChild(); - } - internal StageChecks(SafeDataReader dr) + private StageChecks() => MarkAsChild(); + internal StageChecks(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~StageChecks() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~StageChecks() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(StageCheck.Get(dr)); - this.RaiseListChangedEvents = true; + Add(StageCheck.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class StageIDCriteria { - public StageIDCriteria(int stageID) - { - _StageID = stageID; - } - private int _StageID; + public StageIDCriteria(int stageID) => _StageID = stageID; + private int _StageID; public int StageID { get { return _StageID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(StageIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageChecks.DataPortal_FetchStageID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new StageCheck(dr)); + while (dr.Read()) Add(new StageCheck(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("StageChecks.DataPortal_FetchStageID", ex); throw new DbCslaException("StageChecks.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Stage stage) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection StageChecksPropertyDescriptor pd = new StageChecksPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class StageChecksPropertyDescriptor : vlnListPropertyDescriptor { - private StageCheck Item { get { return (StageCheck)_Item; } } public StageChecksPropertyDescriptor(StageChecks collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is StageChecks) + if (destType == typeof(string) && value is StageChecks checks) { // Return department and department role separated by comma. - return ((StageChecks)value).Items.Count.ToString() + " Checks"; + return $"{checks.Items.Count} Checks"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/StageInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/StageInfo.cs index 2d4170d5..d0a65049 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/StageInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/StageInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class StageInfo : ReadOnlyBase, IDisposable { public event StageInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(StageInfo stageInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(stageInfo)) _CacheList.Remove(stageInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Stage _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _StageID; [System.ComponentModel.DataObjectField(true, true)] public int StageID @@ -216,32 +200,19 @@ namespace VEPROMS.CSLA.Library foreach (StageInfo tmp in _CacheByPrimaryKey[_StageID.ToString()]) tmp._StageVersionCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base StageInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current StageInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check StageInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current StageInfo - protected override object GetIdValue() - { - return MyStageInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyStageInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _StageInfoUnique = 0; - private static int StageInfoUnique - { get { return ++_StageInfoUnique; } } - private int _MyStageInfoUnique = StageInfoUnique; - public int MyStageInfoUnique // Absolutely Unique ID - Info - { get { return _MyStageInfoUnique; } } + private static int StageInfoUnique => ++_StageInfoUnique; + private readonly int _MyStageInfoUnique = StageInfoUnique; + // Absolutely Unique ID - Info + public int MyStageInfoUnique => _MyStageInfoUnique; protected StageInfo() {/* require use of factory methods */ AddToCache(this); @@ -250,15 +221,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~StageInfo() { _CountFinalized++; @@ -275,10 +242,7 @@ namespace VEPROMS.CSLA.Library if (listStageInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(StageID.ToString()); // remove the list } - public virtual Stage Get() - { - return _Editable = Stage.GetJustStage(_StageID); - } + public virtual Stage Get() => _Editable = Stage.GetJustStage(_StageID); public static void Refresh(Stage tmp) { string key = tmp.StageID.ToString(); @@ -299,8 +263,6 @@ namespace VEPROMS.CSLA.Library } public static StageInfo Get(int stageID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Stage"); try { StageInfo tmp = GetCachedByPrimaryKey(stageID); @@ -339,13 +301,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _StageID; - public int StageID - { get { return _StageID; } } - public PKCriteria(int stageID) - { - _StageID = stageID; - } + private readonly int _StageID; + public int StageID => _StageID; + public PKCriteria(int stageID) => _StageID = stageID; } private void ReadData(SafeDataReader dr) { @@ -408,7 +366,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - StageInfoExtension _StageInfoExtension = new StageInfoExtension(); + readonly StageInfoExtension _StageInfoExtension = new StageInfoExtension(); [Serializable()] partial class StageInfoExtension : extensionBase { } [Serializable()] @@ -424,10 +382,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is StageInfo) + if (destType == typeof(string) && value is StageInfo info) { // Return the ToString value - return ((StageInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/StageInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/StageInfoList.cs index 964112eb..911b11ca 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/StageInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/StageInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -27,14 +25,10 @@ namespace VEPROMS.CSLA.Library [TypeConverter(typeof(StageInfoListConverter))] public partial class StageInfoList : ReadOnlyListBase, ICustomTypeDescriptor, IDisposable { - public static event StageInfoListEvent ListChanged; - private static void OnListChanged() - { - if (ListChanged != null) - ListChanged(); - } - #region Log4Net - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + public new static event StageInfoListEvent ListChanged; + private static void OnListChanged() => ListChanged?.Invoke(); + #region Log4Net + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods internal new IList Items @@ -58,16 +52,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~StageInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~StageInfoList() { _CountFinalized++; } @@ -105,26 +95,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on StageInfoList.Get", ex); } } - /// - /// Reset the list of all StageInfo. - /// - public static void Reset() - { - _StageInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static StageInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on StageInfoList.Get", ex); - // } - //} - private StageInfoList() + /// + /// Reset the list of all StageInfo. + /// + public static void Reset() => _StageInfoList = null; + private StageInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal @@ -157,41 +132,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -213,7 +177,6 @@ namespace VEPROMS.CSLA.Library /// public partial class StageInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private StageInfo Item { get { return (StageInfo)_Item; } } public StageInfoListPropertyDescriptor(StageInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -222,10 +185,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is StageInfoList) + if (destType == typeof(string) && value is StageInfoList list) { // Return department and department role separated by comma. - return ((StageInfoList)value).Items.Count.ToString() + " Stages"; + return $"{list.Items.Count} Stages"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/StageVersion.cs b/PROMS/VEPROMS.CSLA.Library/Generated/StageVersion.cs index aa5e9bf0..049664ac 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/StageVersion.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/StageVersion.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -257,19 +251,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current StageVersion - protected override object GetIdValue() - { - return MyStageVersionUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base StageVersion.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current StageVersion - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyStageVersionUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -284,18 +266,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list)); } #endregion #region ValidationRules @@ -325,8 +304,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -348,78 +327,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(RevisionID, ""); - //AuthorizationRules.AllowWrite(RevisionID, ""); - //AuthorizationRules.AllowRead(PDF, ""); - //AuthorizationRules.AllowWrite(PDF, ""); - //AuthorizationRules.AllowRead(SummaryPDF, ""); - //AuthorizationRules.AllowWrite(SummaryPDF, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _StageVersionUnique = 0; - private static int StageVersionUnique - { get { return ++_StageVersionUnique; } } - private int _MyStageVersionUnique = StageVersionUnique; - public int MyStageVersionUnique // Absolutely Unique ID - Editable FK - { get { return _MyStageVersionUnique; } } - internal static StageVersion New(Revision myRevision, DateTime dts, string userID) - { - return new StageVersion(myRevision, dts, userID); - } - internal static StageVersion Get(SafeDataReader dr) - { - return new StageVersion(dr); - } + private static int StageVersionUnique => ++_StageVersionUnique; + private readonly int _MyStageVersionUnique = StageVersionUnique; + // Absolutely Unique ID - Editable FK + public int MyStageVersionUnique => _MyStageVersionUnique; + internal static StageVersion New(Revision myRevision, DateTime dts, string userID) => new StageVersion(myRevision, dts, userID); + internal static StageVersion Get(SafeDataReader dr) => new StageVersion(dr); public StageVersion() { MarkAsChild(); @@ -447,15 +370,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~StageVersion() { _CountFinalized++; @@ -499,33 +418,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(Stage myStage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, myStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, myStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); + } + MarkOld(); } internal void Update(Stage myStage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, myStage.StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, myStage.StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Stage myStage) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Version.Remove(cn, _VersionID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Version.Remove(cn, _VersionID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - StageVersionExtension _StageVersionExtension = new StageVersionExtension(); + readonly StageVersionExtension _StageVersionExtension = new StageVersionExtension(); [Serializable()] partial class StageVersionExtension : extensionBase { @@ -562,49 +494,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is StageVersion) + if (destType == typeof(string) && value is StageVersion version) { // Return the ToString value - return ((StageVersion)value).ToString(); + return version.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create StageVersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class StageVersion -// { -// partial class StageVersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/StageVersions.cs b/PROMS/VEPROMS.CSLA.Library/Generated/StageVersions.cs index 15235d2e..aac02a8a 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/StageVersions.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/StageVersions.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public StageVersion this[Version myVersion] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public StageVersion this[Version myVersion] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public StageVersion GetItem(Version myVersion) + public new System.Collections.Generic.IList Items => base.Items; + public StageVersion GetItem(Version myVersion) { foreach (StageVersion version in this) if (version.VersionID == myVersion.VersionID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public StageVersion Add(Revision myRevision, DateTime dts, string userID) // One to Many { StageVersion version = StageVersion.New(myRevision, dts, userID); - this.Add(version); + Add(version); return version; } public void Remove(Version myVersion) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (StageVersion child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (StageVersion child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static StageVersions New() - { - return new StageVersions(); - } - internal static StageVersions Get(SafeDataReader dr) - { - return new StageVersions(dr); - } - public static StageVersions GetByStageID(int stageID) + #endregion + #region Factory Methods + internal static StageVersions New() => new StageVersions(); + internal static StageVersions Get(SafeDataReader dr) => new StageVersions(dr); + public static StageVersions GetByStageID(int stageID) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on StageVersions.GetByStageID", ex); } } - private StageVersions() - { - MarkAsChild(); - } - internal StageVersions(SafeDataReader dr) + private StageVersions() => MarkAsChild(); + internal StageVersions(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~StageVersions() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~StageVersions() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(StageVersion.Get(dr)); - this.RaiseListChangedEvents = true; + Add(StageVersion.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class StageIDCriteria { - public StageIDCriteria(int stageID) - { - _StageID = stageID; - } - private int _StageID; + public StageIDCriteria(int stageID) => _StageID = stageID; + private int _StageID; public int StageID { get { return _StageID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(StageIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageVersions.DataPortal_FetchStageID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new StageVersion(dr)); + while (dr.Read()) Add(new StageVersion(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("StageVersions.DataPortal_FetchStageID", ex); throw new DbCslaException("StageVersions.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(Stage stage) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection StageVersionsPropertyDescriptor pd = new StageVersionsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class StageVersionsPropertyDescriptor : vlnListPropertyDescriptor { - private StageVersion Item { get { return (StageVersion)_Item; } } public StageVersionsPropertyDescriptor(StageVersions collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is StageVersions) + if (destType == typeof(string) && value is StageVersions versions) { // Return department and department role separated by comma. - return ((StageVersions)value).Items.Count.ToString() + " Versions"; + return $"{versions.Items.Count} Versions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Transition.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Transition.cs index 45464f93..bc4d5db8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Transition.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Transition.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshTransitions.Add(this); } - private void ClearRefreshList() - { - _RefreshTransitions = new List(); - } + private void ClearRefreshList() => _RefreshTransitions = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -59,6 +54,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Transition transition) { @@ -68,6 +64,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(transition)) _CacheList.Remove(transition); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -93,15 +90,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextTransitionID = -1; - public static int NextTransitionID - { - get { return _nextTransitionID--; } - } + public static int NextTransitionID => _nextTransitionID--; private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -341,37 +332,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyZTransition == null ? false : _MyZTransition.IsDirtyList(list)) || (_MyContent == null ? false : _MyContent.IsDirtyList(list)) || (_MyItemRangeID == null ? false : _MyItemRangeID.IsDirtyList(list)) || (_MyItemToID == null ? false : _MyItemToID.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyZTransition != null && _MyZTransition.IsDirtyList(list)) || (_MyContent != null && _MyContent.IsDirtyList(list)) || (_MyItemRangeID != null && _MyItemRangeID.IsDirtyList(list)) || (_MyItemToID != null && _MyItemToID.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyZTransition == null ? true : _MyZTransition.IsValidList(list)) && (_MyContent == null ? true : _MyContent.IsValidList(list)) && (_MyItemRangeID == null ? true : _MyItemRangeID.IsValidList(list)) && (_MyItemToID == null ? true : _MyItemToID.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyZTransition == null || _MyZTransition.IsValidList(list)) && (_MyContent == null || _MyContent.IsValidList(list)) && (_MyItemRangeID == null || _MyItemRangeID.IsValidList(list)) && (_MyItemToID == null || _MyItemToID.IsValidList(list)); } - // CSLATODO: Replace base Transition.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Transition - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Transition.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Transition - protected override object GetIdValue() - { - return MyTransitionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyTransitionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -403,8 +379,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -456,39 +432,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(TransitionID, ""); - //AuthorizationRules.AllowRead(FromID, ""); - //AuthorizationRules.AllowRead(ToID, ""); - //AuthorizationRules.AllowRead(RangeID, ""); - //AuthorizationRules.AllowRead(IsRange, ""); - //AuthorizationRules.AllowRead(TranType, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(FromID, ""); - //AuthorizationRules.AllowWrite(ToID, ""); - //AuthorizationRules.AllowWrite(RangeID, ""); - //AuthorizationRules.AllowWrite(IsRange, ""); - //AuthorizationRules.AllowWrite(TranType, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _TransitionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -496,55 +444,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _TransitionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _TransitionZTransitionCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _TransitionUnique = 0; - protected static int TransitionUnique - { get { return ++_TransitionUnique; } } - private int _MyTransitionUnique = TransitionUnique; - public int MyTransitionUnique // Absolutely Unique ID - Editable - { get { return _MyTransitionUnique; } } + protected static int TransitionUnique => ++_TransitionUnique; + private readonly int _MyTransitionUnique = TransitionUnique; + // Absolutely Unique ID - Editable + public int MyTransitionUnique => _MyTransitionUnique; protected Transition() {/* require use of factory methods */ AddToCache(this); @@ -553,15 +460,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Transition() { _CountFinalized++; @@ -579,12 +482,6 @@ namespace VEPROMS.CSLA.Library } if (_MyContent != null) _MyContent = null; - //if (_MyItemRangeID!=null) - // _MyItemRangeID = null; - //if (_MyItemToID != null) - // _MyItemToID = null; - //if (_MyItemRangeID != null) - // _MyItemRangeID = null; } private void RemoveFromDictionaries() { @@ -599,8 +496,6 @@ namespace VEPROMS.CSLA.Library } public static Transition New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Transition"); try { return DataPortal.Create(); @@ -674,8 +569,6 @@ namespace VEPROMS.CSLA.Library } public static Transition Get(int transitionID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Transition"); try { Transition tmp = GetCachedByPrimaryKey(transitionID); @@ -701,14 +594,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new Transition(dr); return null; } - internal Transition(SafeDataReader dr) - { - ReadData(dr); - } + internal Transition(SafeDataReader dr) => ReadData(dr); public static void Delete(int transitionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Transition"); try { DataPortal.Delete(new PKCriteria(transitionID)); @@ -720,12 +608,6 @@ namespace VEPROMS.CSLA.Library } public override Transition Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Transition"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Transition"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Transition"); try { BuildRefreshList(); @@ -745,13 +627,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _TransitionID; - public int TransitionID - { get { return _TransitionID; } } - public PKCriteria(int transitionID) - { - _TransitionID = transitionID; - } + private readonly int _TransitionID; + public int TransitionID => _TransitionID; + public PKCriteria(int transitionID) => _TransitionID = transitionID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -830,7 +708,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Transition.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -855,46 +733,54 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyContent != null) _MyContent.Update(); - if (_MyItemRangeID != null) _MyItemRangeID.Update(); - if (_MyItemToID != null) _MyItemToID.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyContent?.Update(); + _MyItemRangeID?.Update(); + _MyItemToID?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addTransition"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@FromID", FromID); - cm.Parameters.AddWithValue("@ToID", ToID); - cm.Parameters.AddWithValue("@RangeID", RangeID); - cm.Parameters.AddWithValue("@IsRange", _IsRange); - cm.Parameters.AddWithValue("@TranType", _TranType); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int); - param_TransitionID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_TransitionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _TransitionID = (int)cm.Parameters["@newTransitionID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addTransition"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@FromID", FromID); + cm.Parameters.AddWithValue("@ToID", ToID); + cm.Parameters.AddWithValue("@RangeID", RangeID); + cm.Parameters.AddWithValue("@IsRange", _IsRange); + cm.Parameters.AddWithValue("@TranType", _TranType); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_TransitionID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _TransitionID = (int)cm.Parameters["@newTransitionID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_MyZTransition != null) _MyZTransition.Update(this); + _MyZTransition?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -904,7 +790,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Transition.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int transitionID, Content myContent, Item myItemToID, Item myItemRangeID, int isRange, int tranType, string config, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.Add", 0); @@ -925,11 +811,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int); - param_TransitionID.Direction = ParameterDirection.Output; + SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_TransitionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -944,7 +834,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Transition.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -967,48 +857,54 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.SQLUpdate", GetHashCode()); try { - if (_MyContent != null) _MyContent.Update(); - if (_MyItemRangeID != null) _MyItemRangeID.Update(); - if (_MyItemToID != null) _MyItemToID.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyContent?.Update(); + _MyItemRangeID?.Update(); + _MyItemToID?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateTransition"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@TransitionID", _TransitionID); - cm.Parameters.AddWithValue("@FromID", FromID); - cm.Parameters.AddWithValue("@ToID", ToID); - cm.Parameters.AddWithValue("@RangeID", RangeID); - cm.Parameters.AddWithValue("@IsRange", _IsRange); - cm.Parameters.AddWithValue("@TranType", _TranType); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateTransition"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@TransitionID", _TransitionID); + cm.Parameters.AddWithValue("@FromID", FromID); + cm.Parameters.AddWithValue("@ToID", ToID); + cm.Parameters.AddWithValue("@RangeID", RangeID); + cm.Parameters.AddWithValue("@IsRange", _IsRange); + cm.Parameters.AddWithValue("@TranType", _TranType); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_MyZTransition != null) _MyZTransition.Update(this); + _MyZTransition?.Update(this); } catch (Exception ex) { @@ -1019,19 +915,23 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, _MyItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); - else - _LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, _MyItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); + else + _LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } - if (_MyZTransition != null) _MyZTransition.Update(this); + _MyZTransition?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int transitionID, int fromID, int toID, int rangeID, int isRange, int tranType, string config, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.Update", 0); @@ -1054,8 +954,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1069,12 +971,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Transition.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_TransitionID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.DataPortal_Delete", GetHashCode()); @@ -1099,7 +1001,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Transition.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int transitionID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.Remove", 0); @@ -1140,16 +1042,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _TransitionID; + private readonly int _TransitionID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int transitionID) - { - _TransitionID = transitionID; - } + public bool Exists => _exists; + public ExistsCommand(int transitionID) => _TransitionID = transitionID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.DataPortal_Execute", GetHashCode()); @@ -1157,7 +1053,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1165,7 +1061,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsTransition"; cm.Parameters.AddWithValue("@TransitionID", _TransitionID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1179,7 +1075,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - TransitionExtension _TransitionExtension = new TransitionExtension(); + readonly TransitionExtension _TransitionExtension = new TransitionExtension(); [Serializable()] partial class TransitionExtension : extensionBase { @@ -1188,22 +1084,10 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual int DefaultIsRange - { - get { return 0; } - } - public virtual int DefaultTranType - { - get { return 0; } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUserID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual int DefaultIsRange => 0; + public virtual int DefaultTranType => 0; + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1232,65 +1116,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Transition) + if (destType == typeof(string) && value is Transition transs) { // Return the ToString value - return ((Transition)value).ToString(); + return transs.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create TransitionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Transition -// { -// partial class TransitionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual int DefaultIsRange -// { -// get { return 0; } -// } -// public virtual int DefaultTranType -// { -// get { return 0; } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfo.cs index 8988c6c1..9c2f62a2 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class TransitionInfo : ReadOnlyBase, IDisposable { public event TransitionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(TransitionInfo transitionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(transitionInfo)) _CacheList.Remove(transitionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Transition _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -237,32 +221,19 @@ namespace VEPROMS.CSLA.Library return _MyZTransition; } } - // CSLATODO: Replace base TransitionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current TransitionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check TransitionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current TransitionInfo - protected override object GetIdValue() - { - return MyTransitionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyTransitionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _TransitionInfoUnique = 0; - private static int TransitionInfoUnique - { get { return ++_TransitionInfoUnique; } } - private int _MyTransitionInfoUnique = TransitionInfoUnique; - public int MyTransitionInfoUnique // Absolutely Unique ID - Info - { get { return _MyTransitionInfoUnique; } } + private static int TransitionInfoUnique => ++_TransitionInfoUnique; + private readonly int _MyTransitionInfoUnique = TransitionInfoUnique; + // Absolutely Unique ID - Info + public int MyTransitionInfoUnique => _MyTransitionInfoUnique; protected TransitionInfo() {/* require use of factory methods */ AddToCache(this); @@ -271,15 +242,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~TransitionInfo() { _CountFinalized++; @@ -296,10 +263,7 @@ namespace VEPROMS.CSLA.Library if (listTransitionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list } - public virtual Transition Get() - { - return _Editable = Transition.Get(_TransitionID); - } + public virtual Transition Get() => _Editable = Transition.Get(_TransitionID); public static void Refresh(Transition tmp) { string key = tmp.TransitionID.ToString(); @@ -312,25 +276,25 @@ namespace VEPROMS.CSLA.Library { if (_FromID != tmp.FromID) { - if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value + MyContent?.RefreshContentTransitions(); // Update List for old value _FromID = tmp.FromID; // Update the value } _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value + MyContent?.RefreshContentTransitions(); // Update List for new value if (_ToID != tmp.ToID) { - if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value + MyItemToID?.RefreshItemTransitions_ToID(); // Update List for old value _ToID = tmp.ToID; // Update the value } _MyItemToID = null; // Reset list so that the next line gets a new list - if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value + MyItemToID?.RefreshItemTransitions_ToID(); // Update List for new value if (_RangeID != tmp.RangeID) { - if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value + MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for old value _RangeID = tmp.RangeID; // Update the value } _MyItemRangeID = null; // Reset list so that the next line gets a new list - if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value + MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for new value _IsRange = tmp.IsRange; _TranType = tmp.TranType; _Config = tmp.Config; @@ -352,18 +316,18 @@ namespace VEPROMS.CSLA.Library { if (_ToID != tmp.ToID) { - if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value + MyItemToID?.RefreshItemTransitions_ToID(); // Update List for old value _ToID = tmp.ToID; // Update the value } _MyItemToID = null; // Reset list so that the next line gets a new list - if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value + MyItemToID?.RefreshItemTransitions_ToID(); // Update List for new value if (_RangeID != tmp.RangeID) { - if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value + MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for old value _RangeID = tmp.RangeID; // Update the value } _MyItemRangeID = null; // Reset list so that the next line gets a new list - if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value + MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for new value _IsRange = tmp.IsRange; _TranType = tmp.TranType; _Config = tmp.Config; @@ -385,18 +349,18 @@ namespace VEPROMS.CSLA.Library { if (_FromID != tmp.FromID) { - if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value + MyContent?.RefreshContentTransitions(); // Update List for old value _FromID = tmp.FromID; // Update the value } _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value + MyContent?.RefreshContentTransitions(); // Update List for new value if (_ToID != tmp.ToID) { - if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value + MyItemToID?.RefreshItemTransitions_ToID(); // Update List for old value _ToID = tmp.ToID; // Update the value } _MyItemToID = null; // Reset list so that the next line gets a new list - if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value + MyItemToID?.RefreshItemTransitions_ToID(); // Update List for new value _IsRange = tmp.IsRange; _TranType = tmp.TranType; _Config = tmp.Config; @@ -418,18 +382,18 @@ namespace VEPROMS.CSLA.Library { if (_FromID != tmp.FromID) { - if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value + MyContent?.RefreshContentTransitions(); // Update List for old value _FromID = tmp.FromID; // Update the value } _MyContent = null; // Reset list so that the next line gets a new list - if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value + MyContent?.RefreshContentTransitions(); // Update List for new value if (_RangeID != tmp.RangeID) { - if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value + MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for old value _RangeID = tmp.RangeID; // Update the value } _MyItemRangeID = null; // Reset list so that the next line gets a new list - if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value + MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for new value _IsRange = tmp.IsRange; _TranType = tmp.TranType; _Config = tmp.Config; @@ -441,8 +405,6 @@ namespace VEPROMS.CSLA.Library } public static TransitionInfo Get(int transitionID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Transition"); try { TransitionInfo tmp = GetCachedByPrimaryKey(transitionID); @@ -481,13 +443,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _TransitionID; - public int TransitionID - { get { return _TransitionID; } } - public PKCriteria(int transitionID) - { - _TransitionID = transitionID; - } + private readonly int _TransitionID; + public int TransitionID => _TransitionID; + public PKCriteria(int transitionID) => _TransitionID = transitionID; } private void ReadData(SafeDataReader dr) { @@ -551,7 +509,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - TransitionInfoExtension _TransitionInfoExtension = new TransitionInfoExtension(); + readonly TransitionInfoExtension _TransitionInfoExtension = new TransitionInfoExtension(); [Serializable()] partial class TransitionInfoExtension : extensionBase { } [Serializable()] @@ -567,10 +525,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is TransitionInfo) + if (destType == typeof(string) && value is TransitionInfo info) { // Return the ToString value - return ((TransitionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfoList.cs index c99c8aa2..53f8684d 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/TransitionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (TransitionInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~TransitionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~TransitionInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on TransitionInfoList.Get", ex); } } - /// - /// Reset the list of all TransitionInfo. - /// - public static void Reset() - { - _TransitionInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static TransitionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on TransitionInfoList.Get", ex); - // } - //} - public static TransitionInfoList GetByFromID(int fromID) + /// + /// Reset the list of all TransitionInfo. + /// + public static void Reset() => _TransitionInfoList = null; + public static TransitionInfoList GetByFromID(int fromID) { try { @@ -164,7 +142,7 @@ namespace VEPROMS.CSLA.Library #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -178,7 +156,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new TransitionInfo(dr)); + while (dr.Read()) Add(new TransitionInfo(dr)); IsReadOnly = true; } } @@ -189,16 +167,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class FromIDCriteria { - public FromIDCriteria(int fromID) - { - _FromID = fromID; - } - private int _FromID; + public FromIDCriteria(int fromID) => _FromID = fromID; + private int _FromID; public int FromID { get { return _FromID; } @@ -207,7 +182,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(FromIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchFromID", GetHashCode()); try { @@ -222,7 +197,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new TransitionInfo(dr)); + while (dr.Read()) Add(new TransitionInfo(dr)); IsReadOnly = true; } } @@ -233,16 +208,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchFromID", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class RangeIDCriteria { - public RangeIDCriteria(int rangeID) - { - _RangeID = rangeID; - } - private int _RangeID; + public RangeIDCriteria(int rangeID) => _RangeID = rangeID; + private int _RangeID; public int RangeID { get { return _RangeID; } @@ -251,7 +223,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(RangeIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchRangeID", GetHashCode()); try { @@ -266,7 +238,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new TransitionInfo(dr)); + while (dr.Read()) Add(new TransitionInfo(dr)); IsReadOnly = true; } } @@ -277,16 +249,13 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchRangeID", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } [Serializable()] private class ToIDCriteria { - public ToIDCriteria(int toID) - { - _ToID = toID; - } - private int _ToID; + public ToIDCriteria(int toID) => _ToID = toID; + private int _ToID; public int ToID { get { return _ToID; } @@ -295,7 +264,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(ToIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchToID", GetHashCode()); try { @@ -310,7 +279,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new TransitionInfo(dr)); + while (dr.Read()) Add(new TransitionInfo(dr)); IsReadOnly = true; } } @@ -321,48 +290,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchToID", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection TransitionInfoListPropertyDescriptor pd = new TransitionInfoListPropertyDescriptor(this, i); @@ -379,7 +337,6 @@ namespace VEPROMS.CSLA.Library /// public partial class TransitionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private TransitionInfo Item { get { return (TransitionInfo)_Item; } } public TransitionInfoListPropertyDescriptor(TransitionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -388,10 +345,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is TransitionInfoList) + if (destType == typeof(string) && value is TransitionInfoList list) { // Return department and department role separated by comma. - return ((TransitionInfoList)value).Items.Count.ToString() + " Transitions"; + return $"{list.Items.Count} Transitions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/User.cs b/PROMS/VEPROMS.CSLA.Library/Generated/User.cs index 5734aa8f..74aad0b1 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/User.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/User.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -69,6 +67,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(User user) { @@ -78,6 +77,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(user)) _CacheList.Remove(user); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -103,15 +103,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextUID = -1; - public static int NextUID - { - get { return _nextUID--; } - } + public static int NextUID => _nextUID--; private int _UID; [System.ComponentModel.DataObjectField(true, true)] public int UID @@ -400,10 +394,7 @@ namespace VEPROMS.CSLA.Library return _UserMemberships; } } - public void Reset_UserMemberships() - { - _UserMembershipCount = -1; - } + public void Reset_UserMemberships() => _UserMembershipCount = -1; public override bool IsDirty { get @@ -418,37 +409,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_UserMemberships == null ? false : _UserMemberships.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_UserMemberships != null && _UserMemberships.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_UserMemberships == null ? true : _UserMemberships.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_UserMemberships == null || _UserMemberships.IsValidList(list)); } - // CSLATODO: Replace base User.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current User - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check User.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current User - protected override object GetIdValue() - { - return MyUserUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyUserUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -477,8 +453,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -532,49 +508,11 @@ namespace VEPROMS.CSLA.Library _UserExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(UID, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowRead(FirstName, ""); - //AuthorizationRules.AllowRead(MiddleName, ""); - //AuthorizationRules.AllowRead(LastName, ""); - //AuthorizationRules.AllowRead(Suffix, ""); - //AuthorizationRules.AllowRead(CourtesyTitle, ""); - //AuthorizationRules.AllowRead(PhoneNumber, ""); - //AuthorizationRules.AllowRead(CFGName, ""); - //AuthorizationRules.AllowRead(UserLogin, ""); - //AuthorizationRules.AllowRead(UserName, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UserID, ""); - //AuthorizationRules.AllowWrite(FirstName, ""); - //AuthorizationRules.AllowWrite(MiddleName, ""); - //AuthorizationRules.AllowWrite(LastName, ""); - //AuthorizationRules.AllowWrite(Suffix, ""); - //AuthorizationRules.AllowWrite(CourtesyTitle, ""); - //AuthorizationRules.AllowWrite(PhoneNumber, ""); - //AuthorizationRules.AllowWrite(CFGName, ""); - //AuthorizationRules.AllowWrite(UserLogin, ""); - //AuthorizationRules.AllowWrite(UserName, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); _UserExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -582,55 +520,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _UserExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - /// - /// determines if related records (Foreign Keys) will keep this Item from being deleted - /// - public bool CanDelete - { - get - { - // Check to make sure that there are not any related records - int usedByCount = 0; - usedByCount += _UserMembershipCount; - return (usedByCount == 0); - } - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _UserUnique = 0; - protected static int UserUnique - { get { return ++_UserUnique; } } - private int _MyUserUnique = UserUnique; - public int MyUserUnique // Absolutely Unique ID - Editable - { get { return _MyUserUnique; } } + protected static int UserUnique => ++_UserUnique; + private readonly int _MyUserUnique = UserUnique; + // Absolutely Unique ID - Editable + public int MyUserUnique => _MyUserUnique; protected User() {/* require use of factory methods */ AddToCache(this); @@ -639,15 +536,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~User() { _CountFinalized++; @@ -672,8 +565,6 @@ namespace VEPROMS.CSLA.Library } public static User New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a User"); try { return DataPortal.Create(); @@ -750,8 +641,6 @@ namespace VEPROMS.CSLA.Library } public static User Get(int uid) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a User"); try { User tmp = GetCachedByPrimaryKey(uid); @@ -772,19 +661,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on User.Get", ex); } } - public static User Get(SafeDataReader dr) - { - if (dr.Read()) return new User(dr); - return null; - } - internal User(SafeDataReader dr) - { - ReadData(dr); - } + public static User Get(SafeDataReader dr) => dr.Read() ? new User(dr) : null; + internal User(SafeDataReader dr) => ReadData(dr); public static void Delete(int uid) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a User"); try { DataPortal.Delete(new PKCriteria(uid)); @@ -796,12 +676,6 @@ namespace VEPROMS.CSLA.Library } public override User Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a User"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a User"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a User"); try { BuildRefreshList(); @@ -821,13 +695,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _UID; - public int UID - { get { return _UID; } } - public PKCriteria(int uid) - { - _UID = uid; - } + private readonly int _UID; + public int UID => _UID; + public PKCriteria(int uid) => _UID = uid; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -910,7 +780,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("User.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -935,48 +805,56 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addUser"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@FirstName", _FirstName); - cm.Parameters.AddWithValue("@MiddleName", _MiddleName); - cm.Parameters.AddWithValue("@LastName", _LastName); - cm.Parameters.AddWithValue("@Suffix", _Suffix); - cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle); - cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber); - cm.Parameters.AddWithValue("@CFGName", _CFGName); - cm.Parameters.AddWithValue("@UserLogin", _UserLogin); - cm.Parameters.AddWithValue("@UserName", _UserName); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - // Output Calculated Columns - SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int); - param_UID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_UID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _UID = (int)cm.Parameters["@newUID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addUser"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@FirstName", _FirstName); + cm.Parameters.AddWithValue("@MiddleName", _MiddleName); + cm.Parameters.AddWithValue("@LastName", _LastName); + cm.Parameters.AddWithValue("@Suffix", _Suffix); + cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle); + cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber); + cm.Parameters.AddWithValue("@CFGName", _CFGName); + cm.Parameters.AddWithValue("@UserLogin", _UserLogin); + cm.Parameters.AddWithValue("@UserName", _UserName); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + // Output Calculated Columns + SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_UID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _UID = (int)cm.Parameters["@newUID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects - if (_UserMemberships != null) _UserMemberships.Update(this); + _UserMemberships?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.SQLInsert", GetHashCode()); } catch (Exception ex) @@ -986,7 +864,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("User.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int uid, string userID, string firstName, string middleName, string lastName, string suffix, string courtesyTitle, string phoneNumber, string cFGName, string userLogin, string userName, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.Add", 0); @@ -1012,11 +890,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns - SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int); - param_UID.Direction = ParameterDirection.Output; + SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_UID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1031,7 +913,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("User.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -1054,50 +936,56 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateUser"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@UID", _UID); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@FirstName", _FirstName); - cm.Parameters.AddWithValue("@MiddleName", _MiddleName); - cm.Parameters.AddWithValue("@LastName", _LastName); - cm.Parameters.AddWithValue("@Suffix", _Suffix); - cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle); - cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber); - cm.Parameters.AddWithValue("@CFGName", _CFGName); - cm.Parameters.AddWithValue("@UserLogin", _UserLogin); - cm.Parameters.AddWithValue("@UserName", _UserName); - cm.Parameters.AddWithValue("@Config", _Config); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UsrID", _UsrID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateUser"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@UID", _UID); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@FirstName", _FirstName); + cm.Parameters.AddWithValue("@MiddleName", _MiddleName); + cm.Parameters.AddWithValue("@LastName", _LastName); + cm.Parameters.AddWithValue("@Suffix", _Suffix); + cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle); + cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber); + cm.Parameters.AddWithValue("@CFGName", _CFGName); + cm.Parameters.AddWithValue("@UserLogin", _UserLogin); + cm.Parameters.AddWithValue("@UserName", _UserName); + cm.Parameters.AddWithValue("@Config", _Config); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UsrID", _UsrID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects - if (_UserMemberships != null) _UserMemberships.Update(this); + _UserMemberships?.Update(this); } catch (Exception ex) { @@ -1108,19 +996,23 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = User.Add(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID); - else - _LastChanged = User.Update(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = User.Add(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID); + else + _LastChanged = User.Update(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } - if (_UserMemberships != null) _UserMemberships.Update(this); + _UserMemberships?.Update(this); } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int uid, string userID, string firstName, string middleName, string lastName, string suffix, string courtesyTitle, string phoneNumber, string cFGName, string userLogin, string userName, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.Update", 0); @@ -1148,8 +1040,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -1163,12 +1057,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("User.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_UID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.DataPortal_Delete", GetHashCode()); @@ -1193,7 +1087,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("User.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int uid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.Remove", 0); @@ -1234,16 +1128,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _UID; + private readonly int _UID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int uid) - { - _UID = uid; - } + public bool Exists => _exists; + public ExistsCommand(int uid) => _UID = uid; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.DataPortal_Execute", GetHashCode()); @@ -1251,7 +1139,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1259,7 +1147,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsUser"; cm.Parameters.AddWithValue("@UID", _UID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1273,7 +1161,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - UserExtension _UserExtension = new UserExtension(); + readonly UserExtension _UserExtension = new UserExtension(); [Serializable()] partial class UserExtension : extensionBase { @@ -1282,18 +1170,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultUserID - { - get { return Environment.UserName.ToUpper(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultUserID => Environment.UserName.ToUpper(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -1322,61 +1201,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is User) + if (destType == typeof(string) && value is User myuser) { // Return the ToString value - return ((User)value).ToString(); + return myuser.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create UserExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class User -// { -// partial class UserExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual string DefaultUserID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/UserInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/UserInfo.cs index b1caa2a4..018e88b3 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/UserInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/UserInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class UserInfo : ReadOnlyBase, IDisposable { public event UserInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(UserInfo userInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(userInfo)) _CacheList.Remove(userInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,10 +71,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected User _Editable; private IVEHasBrokenRules HasBrokenRules { @@ -252,32 +246,19 @@ namespace VEPROMS.CSLA.Library foreach (UserInfo tmp in _CacheByPrimaryKey[_UID.ToString()]) tmp._UserMembershipCount = -1; // This will cause the data to be requeried } - // CSLATODO: Replace base UserInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current UserInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check UserInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current UserInfo - protected override object GetIdValue() - { - return MyUserInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyUserInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _UserInfoUnique = 0; - private static int UserInfoUnique - { get { return ++_UserInfoUnique; } } - private int _MyUserInfoUnique = UserInfoUnique; - public int MyUserInfoUnique // Absolutely Unique ID - Info - { get { return _MyUserInfoUnique; } } + private static int UserInfoUnique => ++_UserInfoUnique; + private readonly int _MyUserInfoUnique = UserInfoUnique; + // Absolutely Unique ID - Info + public int MyUserInfoUnique => _MyUserInfoUnique; protected UserInfo() {/* require use of factory methods */ AddToCache(this); @@ -286,15 +267,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~UserInfo() { _CountFinalized++; @@ -311,10 +288,7 @@ namespace VEPROMS.CSLA.Library if (listUserInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(UID.ToString()); // remove the list } - public virtual User Get() - { - return _Editable = User.Get(_UID); - } + public virtual User Get() => _Editable = User.Get(_UID); public static void Refresh(User tmp) { string key = tmp.UID.ToString(); @@ -343,8 +317,6 @@ namespace VEPROMS.CSLA.Library } public static UserInfo Get(int uid) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a User"); try { UserInfo tmp = GetCachedByPrimaryKey(uid); @@ -383,13 +355,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _UID; - public int UID - { get { return _UID; } } - public PKCriteria(int uid) - { - _UID = uid; - } + private readonly int _UID; + public int UID => _UID; + public PKCriteria(int uid) => _UID = uid; } private void ReadData(SafeDataReader dr) { @@ -458,7 +426,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - UserInfoExtension _UserInfoExtension = new UserInfoExtension(); + readonly UserInfoExtension _UserInfoExtension = new UserInfoExtension(); [Serializable()] partial class UserInfoExtension : extensionBase { } [Serializable()] @@ -474,10 +442,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is UserInfo) + if (destType == typeof(string) && value is UserInfo info) { // Return the ToString value - return ((UserInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/UserInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/UserInfoList.cs index b9322fa8..94941774 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/UserInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/UserInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (UserInfo tmp in this) { @@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library for (int i = 0; i < Count; i++) { if (base[i] == sender) - this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); } } 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; } } - ~UserInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~UserInfoList() { _CountFinalized++; } @@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on UserInfoList.Get", ex); } } - /// - /// Reset the list of all UserInfo. - /// - public static void Reset() - { - _UserInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static UserInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on UserInfoList.Get", ex); - // } - //} - private UserInfoList() + /// + /// Reset the list of all UserInfo. + /// + public static void Reset() => _UserInfoList = null; + private UserInfoList() { /* require use of factory methods */ } #endregion #region Data Access Portal private void DataPortal_Fetch() { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserInfoList.DataPortal_Fetch", GetHashCode()); try { @@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { IsReadOnly = false; - while (dr.Read()) this.Add(new UserInfo(dr)); + while (dr.Read()) Add(new UserInfo(dr)); IsReadOnly = true; } } @@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("UserInfoList.DataPortal_Fetch", ex); throw new DbCslaException("UserInfoList.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection UserInfoListPropertyDescriptor pd = new UserInfoListPropertyDescriptor(this, i); @@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library /// public partial class UserInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private UserInfo Item { get { return (UserInfo)_Item; } } public UserInfoListPropertyDescriptor(UserInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is UserInfoList) + if (destType == typeof(string) && value is UserInfoList list) { // Return department and department role separated by comma. - return ((UserInfoList)value).Items.Count.ToString() + " Users"; + return $"{list.Items.Count} Users"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/UserMembership.cs b/PROMS/VEPROMS.CSLA.Library/Generated/UserMembership.cs index 976e0629..14873aa7 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/UserMembership.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/UserMembership.cs @@ -9,12 +9,9 @@ // ======================================================================== using System; -using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; private int _UGID; [System.ComponentModel.DataObjectField(true, true)] public int UGID @@ -251,19 +245,7 @@ namespace VEPROMS.CSLA.Library /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current UserMembership - protected override object GetIdValue() - { - return MyUserMembershipUnique; // Absolutely Unique ID - } - // CSLATODO: Replace base UserMembership.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current UserMembership - //public override string ToString() - //{ - // return base.ToString(); - //} + protected override object GetIdValue() => MyUserMembershipUnique; // Absolutely Unique ID public override bool IsDirty { get @@ -278,18 +260,15 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyGroup == null ? false : _MyGroup.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyGroup != null && _MyGroup.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyGroup == null ? true : _MyGroup.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyGroup == null || _MyGroup.IsValidList(list)); } #endregion #region ValidationRules @@ -319,8 +298,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -375,80 +354,22 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(UGID, ""); - //AuthorizationRules.AllowRead(GID, ""); - //AuthorizationRules.AllowWrite(GID, ""); - //AuthorizationRules.AllowRead(StartDate, ""); - //AuthorizationRules.AllowWrite(StartDate, ""); - //AuthorizationRules.AllowRead(EndDate, ""); - //AuthorizationRules.AllowWrite(EndDate, ""); - //AuthorizationRules.AllowRead(Config, ""); - //AuthorizationRules.AllowWrite(Config, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowRead(UsrID, ""); - //AuthorizationRules.AllowWrite(UsrID, ""); - } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _UserMembershipUnique = 0; - private static int UserMembershipUnique - { get { return ++_UserMembershipUnique; } } - private int _MyUserMembershipUnique = UserMembershipUnique; - public int MyUserMembershipUnique // Absolutely Unique ID - Editable FK - { get { return _MyUserMembershipUnique; } } - internal static UserMembership New(Group myGroup) - { - return new UserMembership(myGroup); - } - internal static UserMembership Get(SafeDataReader dr) - { - return new UserMembership(dr); - } + private static int UserMembershipUnique => ++_UserMembershipUnique; + private readonly int _MyUserMembershipUnique = UserMembershipUnique; + // Absolutely Unique ID - Editable FK + public int MyUserMembershipUnique => _MyUserMembershipUnique; + internal static UserMembership New(Group myGroup) => new UserMembership(myGroup); + internal static UserMembership Get(SafeDataReader dr) => new UserMembership(dr); public UserMembership() { MarkAsChild(); @@ -478,15 +399,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~UserMembership() { _CountFinalized++; @@ -528,33 +445,46 @@ namespace VEPROMS.CSLA.Library internal void Insert(User myUser) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Membership.Add(cn, ref _UGID, myUser, _MyGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Membership.Add(cn, ref _UGID, myUser, _MyGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); + } + MarkOld(); } internal void Update(User myUser) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - _LastChanged = Membership.Update(cn, ref _UGID, myUser.UID, _GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + if (!IsDirty) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + _LastChanged = Membership.Update(cn, ref _UGID, myUser.UID, _GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); + } + MarkOld(); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(User myUser) { // if we're not dirty then don't update the database - if (!this.IsDirty) return; + if (!IsDirty) return; // if we're new then don't update the database - if (this.IsNew) return; - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - Membership.Remove(cn, _UGID); + if (IsNew) return; + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + Membership.Remove(cn, _UGID); + } + MarkNew(); } #endregion // Standard Default Code #region extension - UserMembershipExtension _UserMembershipExtension = new UserMembershipExtension(); + readonly UserMembershipExtension _UserMembershipExtension = new UserMembershipExtension(); [Serializable()] partial class UserMembershipExtension : extensionBase { @@ -563,18 +493,9 @@ namespace VEPROMS.CSLA.Library class extensionBase { // Default Values - public virtual string DefaultStartDate - { - get { return DateTime.Now.ToShortDateString(); } - } - public virtual DateTime DefaultDTS - { - get { return DateTime.Now; } - } - public virtual string DefaultUsrID - { - get { return Volian.Base.Library.VlnSettings.UserID; } - } + public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); + public virtual DateTime DefaultDTS => DateTime.Now; + public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { @@ -603,61 +524,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is UserMembership) + if (destType == typeof(string) && value is UserMembership membership) { // Return the ToString value - return ((UserMembership)value).ToString(); + return membership.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create UserMembershipExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class UserMembership -// { -// partial class UserMembershipExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public virtual SmartDate DefaultStartDate -// { -// get { return DateTime.Now.ToShortDateString(); } -// } -// public virtual DateTime DefaultDTS -// { -// get { return DateTime.Now; } -// } -// public virtual string DefaultUsrID -// { -// get { return Environment.UserName.ToUpper(); } -// } -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/UserMemberships.cs b/PROMS/VEPROMS.CSLA.Library/Generated/UserMemberships.cs index 68790e4c..7e4e0106 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/UserMemberships.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/UserMemberships.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Business Methods - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } - // One To Many - public UserMembership this[Membership myMembership] + private readonly string _ErrorMessage = string.Empty; + public string ErrorMessage => _ErrorMessage; + // One To Many + public UserMembership this[Membership myMembership] { get { @@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library return null; } } - public new System.Collections.Generic.IList Items - { - get { return base.Items; } - } - public UserMembership GetItem(Membership myMembership) + public new System.Collections.Generic.IList Items => base.Items; + public UserMembership GetItem(Membership myMembership) { foreach (UserMembership membership in this) if (membership.UGID == myMembership.UGID) @@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library public UserMembership Add(Group myGroup) // One to Many { UserMembership membership = UserMembership.New(myGroup); - this.Add(membership); + Add(membership); return membership; } public void Remove(Membership myMembership) @@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library return true; return false; } - public override bool IsValid + public override bool IsValid => IsValidList(new List()); + public bool IsValidList(List list) { - get { return IsValidList(new List()); } - } - public bool IsValidList(List list) - { - // run through all the child objects - // and if any are invalid then the - // collection is invalid - foreach (UserMembership child in this) - if (!child.IsValidList(list)) - { - //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); - return false; - } - return true; - } + // run through all the child objects + // and if any are invalid then the + // collection is invalid + foreach (UserMembership child in this) + if (!child.IsValidList(list)) + { + //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); + return false; + } + return true; + } #endregion #region ValidationRules public IVEHasBrokenRules HasBrokenRules @@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + return hasBrokenRules?.BrokenRules; } } - #endregion - #region Factory Methods - internal static UserMemberships New() - { - return new UserMemberships(); - } - internal static UserMemberships Get(SafeDataReader dr) - { - return new UserMemberships(dr); - } - public static UserMemberships GetByUID(int uid) + #endregion + #region Factory Methods + internal static UserMemberships New() => new UserMemberships(); + internal static UserMemberships Get(SafeDataReader dr) => new UserMemberships(dr); + public static UserMemberships GetByUID(int uid) { try { @@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on UserMemberships.GetByUID", ex); } } - private UserMemberships() - { - MarkAsChild(); - } - internal UserMemberships(SafeDataReader dr) + private UserMemberships() => MarkAsChild(); + internal UserMemberships(SafeDataReader dr) { MarkAsChild(); Fetch(dr); @@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~UserMemberships() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~UserMemberships() { _CountFinalized++; } @@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library // called to load data from the database private void Fetch(SafeDataReader dr) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; while (dr.Read()) - this.Add(UserMembership.Get(dr)); - this.RaiseListChangedEvents = true; + Add(UserMembership.Get(dr)); + RaiseListChangedEvents = true; } [Serializable()] private class UIDCriteria { - public UIDCriteria(int uid) - { - _UID = uid; - } - private int _UID; + public UIDCriteria(int uid) => _UID = uid; + private int _UID; public int UID { get { return _UID; } @@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library } private void DataPortal_Fetch(UIDCriteria criteria) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserMemberships.DataPortal_FetchUID", GetHashCode()); try { @@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { - while (dr.Read()) this.Add(new UserMembership(dr)); + while (dr.Read()) Add(new UserMembership(dr)); } } } @@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsErrorEnabled) _MyLog.Error("UserMemberships.DataPortal_FetchUID", ex); throw new DbCslaException("UserMemberships.DataPortal_Fetch", ex); } - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } internal void Update(User user) { - this.RaiseListChangedEvents = false; + RaiseListChangedEvents = false; try { // update (thus deleting) any deleted child objects @@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library } finally { - this.RaiseListChangedEvents = true; + RaiseListChangedEvents = true; } } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); // Iterate the list - for (int i = 0; i < this.Items.Count; i++) + for (int i = 0; i < Items.Count; i++) { // Create a property descriptor for the item and add to the property descriptor collection UserMembershipsPropertyDescriptor pd = new UserMembershipsPropertyDescriptor(this, i); @@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library /// public partial class UserMembershipsPropertyDescriptor : vlnListPropertyDescriptor { - private UserMembership Item { get { return (UserMembership)_Item; } } public UserMembershipsPropertyDescriptor(UserMemberships collection, int index) : base(collection, index) { ;} } #endregion @@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is UserMemberships) + if (destType == typeof(string) && value is UserMemberships memberships) { // Return department and department role separated by comma. - return ((UserMemberships)value).Items.Count.ToString() + " Memberships"; + return $"{memberships.Items.Count} Memberships"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/Version.cs b/PROMS/VEPROMS.CSLA.Library/Generated/Version.cs index daaac392..cd6dd195 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/Version.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/Version.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshVersions.Add(this); } - private void ClearRefreshList() - { - _RefreshVersions = new List(); - } + private void ClearRefreshList() => _RefreshVersions = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Version version) { @@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(version)) _CacheList.Remove(version); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -92,15 +89,9 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private static int _nextVersionID = -1; - public static int NextVersionID - { - get { return _nextVersionID--; } - } + public static int NextVersionID => _nextVersionID--; private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -277,37 +268,22 @@ namespace VEPROMS.CSLA.Library if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); - return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)) || (_MyStage == null ? false : _MyStage.IsDirtyList(list)); - } - public override bool IsValid - { - get { return IsValidList(new List()); } + return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list)) || (_MyStage != null && _MyStage.IsDirtyList(list)); } + public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) - return (IsNew && !IsDirty) ? true : base.IsValid; + return (IsNew && !IsDirty) || base.IsValid; list.Add(this); - return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)) && (_MyStage == null ? true : _MyStage.IsValidList(list)); + return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list)) && (_MyStage == null || _MyStage.IsValidList(list)); } - // CSLATODO: Replace base Version.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current Version - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check Version.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Version - protected override object GetIdValue() - { - return MyVersionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyVersionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -337,8 +313,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -377,35 +353,11 @@ namespace VEPROMS.CSLA.Library } return true; } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(VersionID, ""); - //AuthorizationRules.AllowRead(RevisionID, ""); - //AuthorizationRules.AllowRead(StageID, ""); - //AuthorizationRules.AllowRead(PDF, ""); - //AuthorizationRules.AllowRead(SummaryPDF, ""); - //AuthorizationRules.AllowRead(DTS, ""); - //AuthorizationRules.AllowRead(UserID, ""); - //AuthorizationRules.AllowWrite(RevisionID, ""); - //AuthorizationRules.AllowWrite(StageID, ""); - //AuthorizationRules.AllowWrite(PDF, ""); - //AuthorizationRules.AllowWrite(SummaryPDF, ""); - //AuthorizationRules.AllowWrite(DTS, ""); - //AuthorizationRules.AllowWrite(UserID, ""); _VersionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -413,42 +365,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _VersionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _VersionUnique = 0; - protected static int VersionUnique - { get { return ++_VersionUnique; } } - private int _MyVersionUnique = VersionUnique; - public int MyVersionUnique // Absolutely Unique ID - Editable - { get { return _MyVersionUnique; } } + protected static int VersionUnique => ++_VersionUnique; + private readonly int _MyVersionUnique = VersionUnique; + // Absolutely Unique ID - Editable + public int MyVersionUnique => _MyVersionUnique; protected Version() {/* require use of factory methods */ AddToCache(this); @@ -457,15 +381,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Version() { _CountFinalized++; @@ -490,8 +410,6 @@ namespace VEPROMS.CSLA.Library } public static Version New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Version"); try { return DataPortal.Create(); @@ -539,8 +457,6 @@ namespace VEPROMS.CSLA.Library } public static Version Get(int versionID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a Version"); try { Version tmp = GetCachedByPrimaryKey(versionID); @@ -561,19 +477,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on Version.Get", ex); } } - public static Version Get(SafeDataReader dr) - { - if (dr.Read()) return new Version(dr); - return null; - } - internal Version(SafeDataReader dr) - { - ReadData(dr); - } + public static Version Get(SafeDataReader dr) => dr.Read() ? new Version(dr) : null; + internal Version(SafeDataReader dr) => ReadData(dr); public static void Delete(int versionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Version"); try { DataPortal.Delete(new PKCriteria(versionID)); @@ -585,12 +492,6 @@ namespace VEPROMS.CSLA.Library } public override Version Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a Version"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a Version"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a Version"); try { BuildRefreshList(); @@ -610,13 +511,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - public PKCriteria(int versionID) - { - _VersionID = versionID; - } + private readonly int _VersionID; + public int VersionID => _VersionID; + public PKCriteria(int versionID) => _VersionID = versionID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -687,7 +584,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Version.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -712,41 +609,49 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - if (_MyRevision != null) _MyRevision.Update(); - if (_MyStage != null) _MyStage.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + _MyRevision?.Update(); + _MyStage?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addVersion"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@RevisionID", RevisionID); - cm.Parameters.AddWithValue("@StageID", StageID); - cm.Parameters.AddWithValue("@PDF", _PDF); - cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF); - cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - // Output Calculated Columns - SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); - param_VersionID.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_VersionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _VersionID = (int)cm.Parameters["@newVersionID"].Value; - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addVersion"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@RevisionID", RevisionID); + cm.Parameters.AddWithValue("@StageID", StageID); + cm.Parameters.AddWithValue("@PDF", _PDF); + cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF); + cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + // Output Calculated Columns + SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_VersionID); + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _VersionID = (int)cm.Parameters["@newVersionID"].Value; + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.SQLInsert", GetHashCode()); @@ -758,7 +663,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Version.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, ref int versionID, Revision myRevision, Stage myStage, byte[] pdf, byte[] summaryPDF, string approvedXML, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.Add", 0); @@ -778,11 +683,15 @@ namespace VEPROMS.CSLA.Library if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns - SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); - param_VersionID.Direction = ParameterDirection.Output; + SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_VersionID); - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -797,7 +706,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Version.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -820,43 +729,49 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.SQLUpdate", GetHashCode()); try { - if (_MyRevision != null) _MyRevision.Update(); - if (_MyStage != null) _MyStage.Update(); - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + _MyRevision?.Update(); + _MyStage?.Update(); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateVersion"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@VersionID", _VersionID); - cm.Parameters.AddWithValue("@RevisionID", RevisionID); - cm.Parameters.AddWithValue("@StageID", StageID); - cm.Parameters.AddWithValue("@PDF", _PDF); - cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF); - cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML); - if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); - cm.Parameters.AddWithValue("@UserID", _UserID); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateVersion"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@VersionID", _VersionID); + cm.Parameters.AddWithValue("@RevisionID", RevisionID); + cm.Parameters.AddWithValue("@StageID", StageID); + cm.Parameters.AddWithValue("@PDF", _PDF); + cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF); + cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML); + if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); + cm.Parameters.AddWithValue("@UserID", _UserID); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -869,18 +784,22 @@ namespace VEPROMS.CSLA.Library } internal void Update() { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, _MyStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); - else - _LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, _StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, _MyStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); + else + _LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, _StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, ref int versionID, int revisionID, int stageID, byte[] pdf, byte[] summaryPDF, string approvedXML, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.Update", 0); @@ -902,8 +821,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -917,12 +838,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Version.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_VersionID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.DataPortal_Delete", GetHashCode()); @@ -947,7 +868,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Version.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int versionID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.Remove", 0); @@ -988,16 +909,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _VersionID; + private readonly int _VersionID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int versionID) - { - _VersionID = versionID; - } + public bool Exists => _exists; + public ExistsCommand(int versionID) => _VersionID = versionID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.DataPortal_Execute", GetHashCode()); @@ -1005,7 +920,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -1013,7 +928,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsVersion"; cm.Parameters.AddWithValue("@VersionID", _VersionID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -1027,7 +942,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - VersionExtension _VersionExtension = new VersionExtension(); + readonly VersionExtension _VersionExtension = new VersionExtension(); [Serializable()] partial class VersionExtension : extensionBase { @@ -1064,49 +979,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is Version) + if (destType == typeof(string) && value is Version myversion) { // Return the ToString value - return ((Version)value).ToString(); + return myversion.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create VersionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class Version -// { -// partial class VersionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfo.cs index a9c4979f..d295e35c 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class VersionInfo : ReadOnlyBase, IDisposable { public event VersionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(VersionInfo versionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(versionInfo)) _CacheList.Remove(versionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected Version _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _VersionID; [System.ComponentModel.DataObjectField(true, true)] public int VersionID @@ -196,32 +180,19 @@ namespace VEPROMS.CSLA.Library return _UserID; } } - // CSLATODO: Replace base VersionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current VersionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check VersionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current VersionInfo - protected override object GetIdValue() - { - return MyVersionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyVersionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _VersionInfoUnique = 0; - private static int VersionInfoUnique - { get { return ++_VersionInfoUnique; } } - private int _MyVersionInfoUnique = VersionInfoUnique; - public int MyVersionInfoUnique // Absolutely Unique ID - Info - { get { return _MyVersionInfoUnique; } } + private static int VersionInfoUnique => ++_VersionInfoUnique; + private readonly int _MyVersionInfoUnique = VersionInfoUnique; + // Absolutely Unique ID - Info + public int MyVersionInfoUnique => _MyVersionInfoUnique; protected VersionInfo() {/* require use of factory methods */ AddToCache(this); @@ -230,15 +201,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~VersionInfo() { _CountFinalized++; @@ -255,10 +222,7 @@ namespace VEPROMS.CSLA.Library if (listVersionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(VersionID.ToString()); // remove the list } - public virtual Version Get() - { - return _Editable = Version.Get(_VersionID); - } + public virtual Version Get() => _Editable = Version.Get(_VersionID); public static void Refresh(Version tmp) { string key = tmp.VersionID.ToString(); @@ -271,18 +235,18 @@ namespace VEPROMS.CSLA.Library { if (_RevisionID != tmp.RevisionID) { - if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for old value + MyRevision?.RefreshRevisionVersions(); // Update List for old value _RevisionID = tmp.RevisionID; // Update the value } _MyRevision = null; // Reset list so that the next line gets a new list - if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for new value + MyRevision?.RefreshRevisionVersions(); // Update List for new value if (_StageID != tmp.StageID) { - if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for old value + MyStage?.RefreshStageVersions(); // Update List for old value _StageID = tmp.StageID; // Update the value } _MyStage = null; // Reset list so that the next line gets a new list - if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for new value + MyStage?.RefreshStageVersions(); // Update List for new value _PDF = tmp.PDF; _SummaryPDF = tmp.SummaryPDF; _DTS = tmp.DTS; @@ -302,11 +266,11 @@ namespace VEPROMS.CSLA.Library { if (_StageID != tmp.StageID) { - if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for old value + MyStage?.RefreshStageVersions(); // Update List for old value _StageID = tmp.StageID; // Update the value } _MyStage = null; // Reset list so that the next line gets a new list - if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for new value + MyStage?.RefreshStageVersions(); // Update List for new value _PDF = tmp.PDF; _SummaryPDF = tmp.SummaryPDF; _DTS = tmp.DTS; @@ -326,11 +290,11 @@ namespace VEPROMS.CSLA.Library { if (_RevisionID != tmp.RevisionID) { - if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for old value + MyRevision?.RefreshRevisionVersions(); // Update List for old value _RevisionID = tmp.RevisionID; // Update the value } _MyRevision = null; // Reset list so that the next line gets a new list - if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for new value + MyRevision?.RefreshRevisionVersions(); // Update List for new value _PDF = tmp.PDF; _SummaryPDF = tmp.SummaryPDF; _DTS = tmp.DTS; @@ -340,8 +304,6 @@ namespace VEPROMS.CSLA.Library } public static VersionInfo Get(int versionID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a Version"); try { VersionInfo tmp = GetCachedByPrimaryKey(versionID); @@ -380,13 +342,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _VersionID; - public int VersionID - { get { return _VersionID; } } - public PKCriteria(int versionID) - { - _VersionID = versionID; - } + private readonly int _VersionID; + public int VersionID => _VersionID; + public PKCriteria(int versionID) => _VersionID = versionID; } private void ReadData(SafeDataReader dr) { @@ -448,7 +406,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - VersionInfoExtension _VersionInfoExtension = new VersionInfoExtension(); + readonly VersionInfoExtension _VersionInfoExtension = new VersionInfoExtension(); [Serializable()] partial class VersionInfoExtension : extensionBase { } [Serializable()] @@ -464,10 +422,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is VersionInfo) + if (destType == typeof(string) && value is VersionInfo info) { // Return the ToString value - return ((VersionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfoList.cs b/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfoList.cs index 9ce02122..4355e724 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfoList.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/VersionInfoList.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Business Methods - internal new IList Items - { get { return base.Items; } } - public void AddEvents() + #endregion + #region Business Methods + internal new IList Items => base.Items; + public void AddEvents() { foreach (VersionInfo tmp in this) { @@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } - ~VersionInfoList() + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; + ~VersionInfoList() { _CountFinalized++; } @@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on VersionInfoList.Get", ex); } } - /// - /// Reset the list of all VersionInfo. - /// - public static void Reset() - { - _VersionInfoList = null; - } - // CSLATODO: Add alternative gets - - //public static VersionInfoList Get() - //{ - // try - // { - // return DataPortal.Fetch(new FilteredCriteria()); - // } - // catch (Exception ex) - // { - // throw new DbCslaException("Error on VersionInfoList.Get", ex); - // } - //} - public static VersionInfoList GetByRevisionID(int revisionID) + /// + /// Reset the list of all VersionInfo. + /// + public static void Reset() => _VersionInfoList = null; + public static VersionInfoList GetByRevisionID(int revisionID) { try { @@ -180,11 +158,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class RevisionIDCriteria { - public RevisionIDCriteria(int revisionID) - { - _RevisionID = revisionID; - } - private int _RevisionID; + public RevisionIDCriteria(int revisionID) => _RevisionID = revisionID; + private int _RevisionID; public int RevisionID { get { return _RevisionID; } @@ -224,11 +199,8 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class StageIDCriteria { - public StageIDCriteria(int stageID) - { - _StageID = stageID; - } - private int _StageID; + public StageIDCriteria(int stageID) => _StageID = stageID; + private int _StageID; public int StageID { get { return _StageID; } @@ -265,41 +237,30 @@ namespace VEPROMS.CSLA.Library } this.RaiseListChangedEvents = true; } - #endregion - #region ICustomTypeDescriptor impl - public String GetClassName() - { return TypeDescriptor.GetClassName(this, true); } - public AttributeCollection GetAttributes() - { return TypeDescriptor.GetAttributes(this, true); } - public String GetComponentName() - { return TypeDescriptor.GetComponentName(this, true); } - public TypeConverter GetConverter() - { return TypeDescriptor.GetConverter(this, true); } - public EventDescriptor GetDefaultEvent() - { return TypeDescriptor.GetDefaultEvent(this, true); } - public PropertyDescriptor GetDefaultProperty() - { return TypeDescriptor.GetDefaultProperty(this, true); } - public object GetEditor(Type editorBaseType) - { return TypeDescriptor.GetEditor(this, editorBaseType, true); } - public EventDescriptorCollection GetEvents(Attribute[] attributes) - { return TypeDescriptor.GetEvents(this, attributes, true); } - public EventDescriptorCollection GetEvents() - { return TypeDescriptor.GetEvents(this, true); } - public object GetPropertyOwner(PropertyDescriptor pd) - { return this; } - /// - /// Called to get the properties of this type. Returns properties with certain - /// attributes. this restriction is not implemented here. - /// - /// - /// - public PropertyDescriptorCollection GetProperties(Attribute[] attributes) - { return GetProperties(); } - /// - /// Called to get the properties of this type. - /// - /// - public PropertyDescriptorCollection GetProperties() + #endregion + #region ICustomTypeDescriptor impl + public string GetClassName() => TypeDescriptor.GetClassName(this, true); + public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true); + public string GetComponentName() => TypeDescriptor.GetComponentName(this, true); + public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true); + public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true); + public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true); + public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true); + public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true); + public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true); + public object GetPropertyOwner(PropertyDescriptor pd) => this; + /// + /// Called to get the properties of this type. Returns properties with certain + /// attributes. this restriction is not implemented here. + /// + /// + /// + public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties(); + /// + /// Called to get the properties of this type. + /// + /// + public PropertyDescriptorCollection GetProperties() { // Create a collection object to hold property descriptors PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); @@ -321,7 +282,6 @@ namespace VEPROMS.CSLA.Library /// public partial class VersionInfoListPropertyDescriptor : vlnListPropertyDescriptor { - private VersionInfo Item { get { return (VersionInfo)_Item; } } public VersionInfoListPropertyDescriptor(VersionInfoList collection, int index) : base(collection, index) { ;} } #endregion @@ -330,10 +290,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is VersionInfoList) + if (destType == typeof(string) && value is VersionInfoList list) { // Return department and department role separated by comma. - return ((VersionInfoList)value).Items.Count.ToString() + " Versions"; + return $"{list.Items.Count} Versions"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ZContent.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ZContent.cs index 5c857f94..d6a297b4 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ZContent.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ZContent.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshZContents.Add(this); } - private void ClearRefreshList() - { - _RefreshZContents = new List(); - } + private void ClearRefreshList() => _RefreshZContents = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ZContent zContent) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(zContent)) _CacheList.Remove(zContent); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,10 +87,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -138,40 +132,18 @@ namespace VEPROMS.CSLA.Library } } private byte[] _LastChanged = new byte[8];//timestamp - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base ZContent.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ZContent - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check ZContent.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ZContent - protected override object GetIdValue() - { - return MyZContentUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyZContentUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -199,8 +171,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -219,25 +191,11 @@ namespace VEPROMS.CSLA.Library _ZContentExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields - //AuthorizationRules.AllowRead(ContentID, ""); - //AuthorizationRules.AllowRead(OldStepSequence, ""); - //AuthorizationRules.AllowWrite(OldStepSequence, ""); _ZContentExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() @@ -245,42 +203,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ZContentExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ZContentUnique = 0; - protected static int ZContentUnique - { get { return ++_ZContentUnique; } } - private int _MyZContentUnique = ZContentUnique; - public int MyZContentUnique // Absolutely Unique ID - Editable - { get { return _MyZContentUnique; } } + protected static int ZContentUnique => ++_ZContentUnique; + private readonly int _MyZContentUnique = ZContentUnique; + // Absolutely Unique ID - Editable + public int MyZContentUnique => _MyZContentUnique; protected ZContent() {/* require use of factory methods */ AddToCache(this); @@ -289,15 +219,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ZContent() { _CountFinalized++; @@ -322,8 +248,6 @@ namespace VEPROMS.CSLA.Library } public static ZContent New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ZContent"); try { return DataPortal.Create(); @@ -366,8 +290,6 @@ namespace VEPROMS.CSLA.Library } public static ZContent Get(int contentID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ZContent"); try { ZContent tmp = GetCachedByPrimaryKey(contentID); @@ -393,14 +315,9 @@ namespace VEPROMS.CSLA.Library if (dr.Read()) return new ZContent(dr); return null; } - internal ZContent(SafeDataReader dr) - { - ReadData(dr); - } + internal ZContent(SafeDataReader dr) => ReadData(dr); public static void Delete(int contentID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ZContent"); try { DataPortal.Delete(new PKCriteria(contentID)); @@ -412,12 +329,6 @@ namespace VEPROMS.CSLA.Library } public override ZContent Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ZContent"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ZContent"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ZContent"); try { BuildRefreshList(); @@ -437,13 +348,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -508,7 +415,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZContent.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -533,30 +440,36 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addZContent"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addZContent"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.SQLInsert", GetHashCode()); @@ -568,7 +481,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZContent.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Content myContent, string oldStepSequence) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.Add", 0); @@ -583,8 +496,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@ContentID", myContent.ContentID); cm.Parameters.AddWithValue("@OldStepSequence", oldStepSequence); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -598,7 +513,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZContent.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -621,35 +536,41 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateZContent"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@ContentID", ContentID); - cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateZContent"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@ContentID", ContentID); + cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -662,18 +583,22 @@ namespace VEPROMS.CSLA.Library } internal void Update(Content content) { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = ZContent.Add(cn, content, _OldStepSequence); - else - _LastChanged = ZContent.Update(cn, content.ContentID, _OldStepSequence, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = ZContent.Add(cn, content, _OldStepSequence); + else + _LastChanged = ZContent.Update(cn, content.ContentID, _OldStepSequence, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int contentID, string oldStepSequence, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.Update", 0); @@ -689,8 +614,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@OldStepSequence", oldStepSequence); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -704,12 +631,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZContent.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ContentID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.DataPortal_Delete", GetHashCode()); @@ -734,7 +661,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZContent.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int contentID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.Remove", 0); @@ -775,16 +702,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _ContentID; + private readonly int _ContentID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int contentID) - { - _ContentID = contentID; - } + public bool Exists => _exists; + public ExistsCommand(int contentID) => _ContentID = contentID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.DataPortal_Execute", GetHashCode()); @@ -792,7 +713,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -800,7 +721,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsZContent"; cm.Parameters.AddWithValue("@ContentID", _ContentID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -814,7 +735,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ZContentExtension _ZContentExtension = new ZContentExtension(); + readonly ZContentExtension _ZContentExtension = new ZContentExtension(); [Serializable()] partial class ZContentExtension : extensionBase { @@ -851,49 +772,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ZContent) + if (destType == typeof(string) && value is ZContent mycontent) { // Return the ToString value - return ((ZContent)value).ToString(); + return mycontent.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ZContentExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ZContent -// { -// partial class ZContentExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ZContentInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ZContentInfo.cs index d6997a1a..3583346e 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ZContentInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ZContentInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ZContentInfo : ReadOnlyBase, IDisposable { public event ZContentInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ZContentInfo zContentInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(zContentInfo)) _CacheList.Remove(zContentInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -70,21 +67,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ZContent _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _ContentID; [System.ComponentModel.DataObjectField(true, true)] public int ContentID @@ -116,32 +100,19 @@ namespace VEPROMS.CSLA.Library return _OldStepSequence; } } - // CSLATODO: Replace base ZContentInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ZContentInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ZContentInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ZContentInfo - protected override object GetIdValue() - { - return MyZContentInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyZContentInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ZContentInfoUnique = 0; - private static int ZContentInfoUnique - { get { return ++_ZContentInfoUnique; } } - private int _MyZContentInfoUnique = ZContentInfoUnique; - public int MyZContentInfoUnique // Absolutely Unique ID - Info - { get { return _MyZContentInfoUnique; } } + private static int ZContentInfoUnique => ++_ZContentInfoUnique; + private readonly int _MyZContentInfoUnique = ZContentInfoUnique; + // Absolutely Unique ID - Info + public int MyZContentInfoUnique => _MyZContentInfoUnique; protected ZContentInfo() {/* require use of factory methods */ AddToCache(this); @@ -150,15 +121,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ZContentInfo() { _CountFinalized++; @@ -175,10 +142,7 @@ namespace VEPROMS.CSLA.Library if (listZContentInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list } - public virtual ZContent Get() - { - return _Editable = ZContent.Get(_ContentID); - } + public virtual ZContent Get() => _Editable = ZContent.Get(_ContentID); public static void Refresh(ZContent tmp) { string key = tmp.ContentID.ToString(); @@ -191,20 +155,10 @@ namespace VEPROMS.CSLA.Library { _OldStepSequence = tmp.OldStepSequence; _ZContentInfoExtension.Refresh(this); - //RHM Removed 20090724 - Duplicates function of code above. - // - Dispose caused error when a new step was added. - // - Resequence of transitions did not work properly. - // if(_MyContent != null) - // { - // _MyContent.Dispose();// Dispose related value - // _MyContent = null;// Reset related value - // } OnChange();// raise an event } public static ZContentInfo Get(int contentID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ZContent"); try { ZContentInfo tmp = GetCachedByPrimaryKey(contentID); @@ -243,13 +197,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _ContentID; - public int ContentID - { get { return _ContentID; } } - public PKCriteria(int contentID) - { - _ContentID = contentID; - } + private readonly int _ContentID; + public int ContentID => _ContentID; + public PKCriteria(int contentID) => _ContentID = contentID; } private void ReadData(SafeDataReader dr) { @@ -305,7 +255,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ZContentInfoExtension _ZContentInfoExtension = new ZContentInfoExtension(); + readonly ZContentInfoExtension _ZContentInfoExtension = new ZContentInfoExtension(); [Serializable()] partial class ZContentInfoExtension : extensionBase { } [Serializable()] @@ -321,10 +271,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ZContentInfo) + if (destType == typeof(string) && value is ZContentInfo info) { // Return the ToString value - return ((ZContentInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ZTransition.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ZTransition.cs index f62de163..c4ebf909 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ZTransition.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ZTransition.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; @@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library if (IsDirty) refreshZTransitions.Add(this); } - private void ClearRefreshList() - { - _RefreshZTransitions = new List(); - } + private void ClearRefreshList() => _RefreshZTransitions = new List(); private void BuildRefreshList() { ClearRefreshList(); @@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library } #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ZTransition zTransition) { @@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(zTransition)) _CacheList.Remove(zTransition); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -90,10 +87,7 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -136,40 +130,18 @@ namespace VEPROMS.CSLA.Library } } private byte[] _LastChanged = new byte[8];//timestamp - public override bool IsDirty - { - get { return base.IsDirty; } - } - public bool IsDirtyList(List list) - { - return base.IsDirty; - } - public override bool IsValid - { - get { return (IsNew && !IsDirty) ? true : base.IsValid; } - } - public bool IsValidList(List list) - { - return (IsNew && !IsDirty) ? true : base.IsValid; - } - // CSLATODO: Replace base ZTransition.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ZTransition - //public override string ToString() - //{ - // return base.ToString(); - //} + public override bool IsDirty => base.IsDirty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsDirtyList(List list) => base.IsDirty; + public override bool IsValid => (IsNew && !IsDirty) || base.IsValid; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] + public bool IsValidList(List list) => (IsNew && !IsDirty) || base.IsValid; // CSLATODO: Check ZTransition.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ZTransition - protected override object GetIdValue() - { - return MyZTransitionUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyZTransitionUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] @@ -197,8 +169,8 @@ namespace VEPROMS.CSLA.Library get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; - if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; - return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); + if (Equals(hasBrokenRules)) return BrokenRulesCollection; + return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() @@ -217,17 +189,6 @@ namespace VEPROMS.CSLA.Library _ZTransitionExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } - // Sample data comparison validation rule - //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) - //{ - // if (_started > _ended) - // { - // e.Description = "Start date can't be after end date"; - // return false; - // } - // else - // return true; - //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() @@ -243,42 +204,14 @@ namespace VEPROMS.CSLA.Library //CSLATODO: Who can read/write which fields _ZTransitionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } - public static bool CanAddObject() - { - // CSLATODO: Can Add Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } - public static bool CanGetObject() - { - // CSLATODO: CanGet Authorization - return true; - } - public static bool CanDeleteObject() - { - // CSLATODO: CanDelete Authorization - //bool result = false; - //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; - //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; - //return result; - return true; - } - public static bool CanEditObject() - { - // CSLATODO: CanEdit Authorization - //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); - return true; - } #endregion #region Factory Methods - public int CurrentEditLevel - { get { return EditLevel; } } + public int CurrentEditLevel => EditLevel; private static int _ZTransitionUnique = 0; - protected static int ZTransitionUnique - { get { return ++_ZTransitionUnique; } } - private int _MyZTransitionUnique = ZTransitionUnique; - public int MyZTransitionUnique // Absolutely Unique ID - Editable - { get { return _MyZTransitionUnique; } } + protected static int ZTransitionUnique => ++_ZTransitionUnique; + private readonly int _MyZTransitionUnique = ZTransitionUnique; + // Absolutely Unique ID - Editable + public int MyZTransitionUnique => _MyZTransitionUnique; protected ZTransition() {/* require use of factory methods */ AddToCache(this); @@ -287,15 +220,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ZTransition() { _CountFinalized++; @@ -320,8 +249,6 @@ namespace VEPROMS.CSLA.Library } public static ZTransition New() { - if (!CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ZTransition"); try { return DataPortal.Create(); @@ -364,8 +291,6 @@ namespace VEPROMS.CSLA.Library } public static ZTransition Get(int transitionID) { - if (!CanGetObject()) - throw new System.Security.SecurityException("User not authorized to view a ZTransition"); try { ZTransition tmp = GetCachedByPrimaryKey(transitionID); @@ -386,19 +311,10 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("Error on ZTransition.Get", ex); } } - public static ZTransition Get(SafeDataReader dr) - { - if (dr.Read()) return new ZTransition(dr); - return null; - } - internal ZTransition(SafeDataReader dr) - { - ReadData(dr); - } + public static ZTransition Get(SafeDataReader dr) => dr.Read() ? new ZTransition(dr) : null; + internal ZTransition(SafeDataReader dr) => ReadData(dr); public static void Delete(int transitionID) { - if (!CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ZTransition"); try { DataPortal.Delete(new PKCriteria(transitionID)); @@ -410,12 +326,6 @@ namespace VEPROMS.CSLA.Library } public override ZTransition Save() { - if (IsDeleted && !CanDeleteObject()) - throw new System.Security.SecurityException("User not authorized to remove a ZTransition"); - else if (IsNew && !CanAddObject()) - throw new System.Security.SecurityException("User not authorized to add a ZTransition"); - else if (!CanEditObject()) - throw new System.Security.SecurityException("User not authorized to update a ZTransition"); try { BuildRefreshList(); @@ -435,13 +345,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _TransitionID; - public int TransitionID - { get { return _TransitionID; } } - public PKCriteria(int transitionID) - { - _TransitionID = transitionID; - } + private readonly int _TransitionID; + public int TransitionID => _TransitionID; + public PKCriteria(int transitionID) => _TransitionID = transitionID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] @@ -506,7 +412,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZTransition.DataPortal_Fetch", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Insert() { try @@ -531,30 +437,36 @@ namespace VEPROMS.CSLA.Library if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.DataPortal_Insert", GetHashCode()); } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLInsert() { - if (!this.IsDirty) return; + if (!IsDirty) return; try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - using (SqlCommand cm = cn.CreateCommand()) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "addZTransition"; - // Input All Fields - Except Calculated Columns - cm.Parameters.AddWithValue("@TransitionID", TransitionID); - cm.Parameters.AddWithValue("@Oldto", _Oldto); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "addZTransition"; + // Input All Fields - Except Calculated Columns + cm.Parameters.AddWithValue("@TransitionID", TransitionID); + cm.Parameters.AddWithValue("@Oldto", _Oldto); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } + MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.SQLInsert", GetHashCode()); @@ -566,7 +478,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZTransition.SQLInsert", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Add(SqlConnection cn, Transition myTransition, string oldto) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.Add", 0); @@ -581,8 +493,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@TransitionID", myTransition.TransitionID); cm.Parameters.AddWithValue("@Oldto", oldto); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -596,7 +510,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZTransition.Add", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do @@ -619,35 +533,41 @@ namespace VEPROMS.CSLA.Library if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } - [Transactional(TransactionalTypes.TransactionScope)] + internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.SQLUpdate", GetHashCode()); try { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (base.IsDirty) + using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - using (SqlCommand cm = cn.CreateCommand()) + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (base.IsDirty) { - cm.CommandType = CommandType.StoredProcedure; - cm.CommandTimeout = Database.SQLTimeout; - cm.CommandText = "updateZTransition"; - // All Fields including Calculated Fields - cm.Parameters.AddWithValue("@TransitionID", TransitionID); - cm.Parameters.AddWithValue("@Oldto", _Oldto); - cm.Parameters.AddWithValue("@LastChanged", _LastChanged); - // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; - cm.Parameters.Add(param_LastChanged); - // CSLATODO: Define any additional output parameters - cm.ExecuteNonQuery(); - // Save all values being returned from the Procedure - _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + using (SqlCommand cm = cn.CreateCommand()) + { + cm.CommandType = CommandType.StoredProcedure; + cm.CommandTimeout = Database.SQLTimeout; + cm.CommandText = "updateZTransition"; + // All Fields including Calculated Fields + cm.Parameters.AddWithValue("@TransitionID", TransitionID); + cm.Parameters.AddWithValue("@Oldto", _Oldto); + cm.Parameters.AddWithValue("@LastChanged", _LastChanged); + // Output Calculated Columns + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; + cm.Parameters.Add(param_LastChanged); + // CSLATODO: Define any additional output parameters + cm.ExecuteNonQuery(); + // Save all values being returned from the Procedure + _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; + } } } + MarkOld(); // use the open connection to update child objects } @@ -660,18 +580,22 @@ namespace VEPROMS.CSLA.Library } internal void Update(Transition transition) { - if (!this.IsDirty) return; + if (!IsDirty) return; if (base.IsDirty) { - SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; - if (IsNew) - _LastChanged = ZTransition.Add(cn, transition, _Oldto); - else - _LastChanged = ZTransition.Update(cn, transition.TransitionID, _Oldto, ref _LastChanged); + using (SqlConnection cn = Database.VEPROMS_SqlConnection) + { + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); + if (IsNew) + _LastChanged = ZTransition.Add(cn, transition, _Oldto); + else + _LastChanged = ZTransition.Update(cn, transition.TransitionID, _Oldto, ref _LastChanged); + } + MarkOld(); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static byte[] Update(SqlConnection cn, int transitionID, string oldto, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.Update", 0); @@ -687,8 +611,10 @@ namespace VEPROMS.CSLA.Library cm.Parameters.AddWithValue("@Oldto", oldto); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns - SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); - param_LastChanged.Direction = ParameterDirection.Output; + SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) + { + Direction = ParameterDirection.Output + }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); @@ -702,12 +628,12 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZTransition.Update", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_TransitionID)); } - [Transactional(TransactionalTypes.TransactionScope)] + private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.DataPortal_Delete", GetHashCode()); @@ -732,7 +658,7 @@ namespace VEPROMS.CSLA.Library throw new DbCslaException("ZTransition.DataPortal_Delete", ex); } } - [Transactional(TransactionalTypes.TransactionScope)] + public static void Remove(SqlConnection cn, int transitionID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.Remove", 0); @@ -773,16 +699,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] private class ExistsCommand : CommandBase { - private int _TransitionID; + private readonly int _TransitionID; private bool _exists; - public bool Exists - { - get { return _exists; } - } - public ExistsCommand(int transitionID) - { - _TransitionID = transitionID; - } + public bool Exists => _exists; + public ExistsCommand(int transitionID) => _TransitionID = transitionID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.DataPortal_Execute", GetHashCode()); @@ -790,7 +710,7 @@ namespace VEPROMS.CSLA.Library { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { - cn.Open(); + if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; @@ -798,7 +718,7 @@ namespace VEPROMS.CSLA.Library cm.CommandText = "existsZTransition"; cm.Parameters.AddWithValue("@TransitionID", _TransitionID); int count = (int)cm.ExecuteScalar(); - _exists = (count > 0); + _exists = count > 0; } } } @@ -812,7 +732,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Default Code #region extension - ZTransitionExtension _ZTransitionExtension = new ZTransitionExtension(); + readonly ZTransitionExtension _ZTransitionExtension = new ZTransitionExtension(); [Serializable()] partial class ZTransitionExtension : extensionBase { @@ -849,49 +769,13 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ZTransition) + if (destType == typeof(string) && value is ZTransition mytransition) { // Return the ToString value - return ((ZTransition)value).ToString(); + return mytransition.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace - - -//// The following is a sample Extension File. You can use it to create ZTransitionExt.cs -//using System; -//using System.Collections.Generic; -//using System.Text; -//using Csla; - -//namespace VEPROMS.CSLA.Library -//{ -// public partial class ZTransition -// { -// partial class ZTransitionExtension : extensionBase -// { -// // CSLATODO: Override automatic defaults -// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowRead(Dbid, ""); -// } -// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) -// { -// //rules.AllowInstanceRead(Dbid, ""); -// } -// public new void AddValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddRule( -// Csla.Validation.CommonRules.StringMaxLength, -// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); -// } -// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) -// { -// rules.AddInstanceRule(/* Instance Validation Rule */); -// } -// } -// } -//} diff --git a/PROMS/VEPROMS.CSLA.Library/Generated/ZTransitionInfo.cs b/PROMS/VEPROMS.CSLA.Library/Generated/ZTransitionInfo.cs index c0e92d69..ba8b6dbf 100644 --- a/PROMS/VEPROMS.CSLA.Library/Generated/ZTransitionInfo.cs +++ b/PROMS/VEPROMS.CSLA.Library/Generated/ZTransitionInfo.cs @@ -13,8 +13,6 @@ using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; -using System.Configuration; -using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace VEPROMS.CSLA.Library @@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library public partial class ZTransitionInfo : ReadOnlyBase, IDisposable { public event ZTransitionInfoEvent Changed; - private void OnChange() - { - if (Changed != null) Changed(this); - } + private void OnChange() => Changed?.Invoke(this); #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Collection + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(ZTransitionInfo zTransitionInfo) { @@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library { while (_CacheList.Contains(zTransitionInfo)) _CacheList.Remove(zTransitionInfo); // In RemoveFromCache } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { @@ -70,21 +67,8 @@ namespace VEPROMS.CSLA.Library #endregion #region Business Methods private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get { return _ErrorMessage; } - } + public string ErrorMessage => _ErrorMessage; protected ZTransition _Editable; - private IVEHasBrokenRules HasBrokenRules - { - get - { - IVEHasBrokenRules hasBrokenRules = null; - if (_Editable != null) - hasBrokenRules = _Editable.HasBrokenRules; - return hasBrokenRules; - } - } private int _TransitionID; [System.ComponentModel.DataObjectField(true, true)] public int TransitionID @@ -116,32 +100,19 @@ namespace VEPROMS.CSLA.Library return _Oldto; } } - // CSLATODO: Replace base ZTransitionInfo.ToString function as necessary - /// - /// Overrides Base ToString - /// - /// A string representation of current ZTransitionInfo - //public override string ToString() - //{ - // return base.ToString(); - //} // CSLATODO: Check ZTransitionInfo.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current ZTransitionInfo - protected override object GetIdValue() - { - return MyZTransitionInfoUnique; // Absolutely Unique ID - } + protected override object GetIdValue() => MyZTransitionInfoUnique; // Absolutely Unique ID #endregion #region Factory Methods private static int _ZTransitionInfoUnique = 0; - private static int ZTransitionInfoUnique - { get { return ++_ZTransitionInfoUnique; } } - private int _MyZTransitionInfoUnique = ZTransitionInfoUnique; - public int MyZTransitionInfoUnique // Absolutely Unique ID - Info - { get { return _MyZTransitionInfoUnique; } } + private static int ZTransitionInfoUnique => ++_ZTransitionInfoUnique; + private readonly int _MyZTransitionInfoUnique = ZTransitionInfoUnique; + // Absolutely Unique ID - Info + public int MyZTransitionInfoUnique => _MyZTransitionInfoUnique; protected ZTransitionInfo() {/* require use of factory methods */ AddToCache(this); @@ -150,15 +121,11 @@ namespace VEPROMS.CSLA.Library private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; - private static int IncrementCountCreated - { get { return ++_CountCreated; } } - private int _CountWhenCreated = IncrementCountCreated; - public static int CountCreated - { get { return _CountCreated; } } - public static int CountNotDisposed - { get { return _CountCreated - _CountDisposed; } } - public static int CountNotFinalized - { get { return _CountCreated - _CountFinalized; } } + private static int IncrementCountCreated => ++_CountCreated; + private readonly int _CountWhenCreated = IncrementCountCreated; + public static int CountCreated => _CountCreated; + public static int CountNotDisposed => _CountCreated - _CountDisposed; + public static int CountNotFinalized => _CountCreated - _CountFinalized; ~ZTransitionInfo() { _CountFinalized++; @@ -175,10 +142,7 @@ namespace VEPROMS.CSLA.Library if (listZTransitionInfo.Count == 0) // If there are no items left in the list _CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list } - public virtual ZTransition Get() - { - return _Editable = ZTransition.Get(_TransitionID); - } + public virtual ZTransition Get() => _Editable = ZTransition.Get(_TransitionID); public static void Refresh(ZTransition tmp) { string key = tmp.TransitionID.ToString(); @@ -195,8 +159,6 @@ namespace VEPROMS.CSLA.Library } public static ZTransitionInfo Get(int transitionID) { - //if (!CanGetObject()) - // throw new System.Security.SecurityException("User not authorized to view a ZTransition"); try { ZTransitionInfo tmp = GetCachedByPrimaryKey(transitionID); @@ -235,13 +197,9 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class PKCriteria { - private int _TransitionID; - public int TransitionID - { get { return _TransitionID; } } - public PKCriteria(int transitionID) - { - _TransitionID = transitionID; - } + private readonly int _TransitionID; + public int TransitionID => _TransitionID; + public PKCriteria(int transitionID) => _TransitionID = transitionID; } private void ReadData(SafeDataReader dr) { @@ -297,7 +255,7 @@ namespace VEPROMS.CSLA.Library #endregion // Standard Refresh #region extension - ZTransitionInfoExtension _ZTransitionInfoExtension = new ZTransitionInfoExtension(); + readonly ZTransitionInfoExtension _ZTransitionInfoExtension = new ZTransitionInfoExtension(); [Serializable()] partial class ZTransitionInfoExtension : extensionBase { } [Serializable()] @@ -313,10 +271,10 @@ namespace VEPROMS.CSLA.Library { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { - if (destType == typeof(string) && value is ZTransitionInfo) + if (destType == typeof(string) && value is ZTransitionInfo info) { // Return the ToString value - return ((ZTransitionInfo)value).ToString(); + return info.ToString(); } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/VEPROMS.CSLA.Library/GlobalSuppressions.cs b/PROMS/VEPROMS.CSLA.Library/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/VEPROMS.CSLA.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/VEPROMS.CSLA.Library/Minimal/AnnotationstypeSections.cs b/PROMS/VEPROMS.CSLA.Library/Minimal/AnnotationstypeSections.cs index c3af558b..c7b3637b 100644 --- a/PROMS/VEPROMS.CSLA.Library/Minimal/AnnotationstypeSections.cs +++ b/PROMS/VEPROMS.CSLA.Library/Minimal/AnnotationstypeSections.cs @@ -1,21 +1,9 @@ using System; -using System.Collections.Generic; -using System.Collections; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; -using System.Text.RegularExpressions; using Csla; -using Csla.Data; -using System.Configuration; -using System.IO; -using System.ComponentModel; -//namespace VEPROMS.CSLA.Library; - // C2025-027 this new file is used to support (data retrival) for selecting Annotation types to display on the Annotation screen. This is related to Annotation type filtering through V->Options. namespace VEPROMS.CSLA.Library @@ -70,8 +58,8 @@ namespace VEPROMS.CSLA.Library return dt; } - catch (Exception ex) - { + catch (Exception) + { //B2025-004 //if it fails loading previously open tabs, simply treat it as if no tabs were open //instead of crashing @@ -101,8 +89,8 @@ namespace VEPROMS.CSLA.Library return dt; } - catch (Exception ex) - { + catch (Exception) + { //B2025-004 //if it fails loading previously open tabs, simply treat it as if no tabs were open //instead of crashing @@ -132,7 +120,7 @@ namespace VEPROMS.CSLA.Library return dt; } - catch (Exception ex) + catch (Exception) { //B2025-004 //if it fails loading previously open tabs, simply treat it as if no tabs were open diff --git a/PROMS/VEPROMS.CSLA.Library/Minimal/ChangeBarAuditHistory.cs b/PROMS/VEPROMS.CSLA.Library/Minimal/ChangeBarAuditHistory.cs index cf1be7b0..e16b86f8 100644 --- a/PROMS/VEPROMS.CSLA.Library/Minimal/ChangeBarAuditHistory.cs +++ b/PROMS/VEPROMS.CSLA.Library/Minimal/ChangeBarAuditHistory.cs @@ -1,5 +1,4 @@ using System; -using Csla.Data; using System.Data; using System.Data.SqlClient; diff --git a/PROMS/VEPROMS.CSLA.Library/Minimal/GeneralReports.cs b/PROMS/VEPROMS.CSLA.Library/Minimal/GeneralReports.cs index 0eddc936..48a4c2cc 100644 --- a/PROMS/VEPROMS.CSLA.Library/Minimal/GeneralReports.cs +++ b/PROMS/VEPROMS.CSLA.Library/Minimal/GeneralReports.cs @@ -1,5 +1,4 @@ using System; -using Csla.Data; using System.Data; using System.Data.SqlClient; diff --git a/PROMS/VEPROMS.CSLA.Library/Minimal/Maintenance.cs b/PROMS/VEPROMS.CSLA.Library/Minimal/Maintenance.cs index e1c2cb0b..960899c4 100644 --- a/PROMS/VEPROMS.CSLA.Library/Minimal/Maintenance.cs +++ b/PROMS/VEPROMS.CSLA.Library/Minimal/Maintenance.cs @@ -1,5 +1,4 @@ using System; -using Csla.Data; using System.Data; using System.Data.SqlClient; diff --git a/PROMS/VEPROMS.CSLA.Library/Minimal/RevisionData.cs b/PROMS/VEPROMS.CSLA.Library/Minimal/RevisionData.cs index df2fb5cc..aec844cd 100644 --- a/PROMS/VEPROMS.CSLA.Library/Minimal/RevisionData.cs +++ b/PROMS/VEPROMS.CSLA.Library/Minimal/RevisionData.cs @@ -1,5 +1,4 @@ -using Csla.Data; -using System; +using System; using System.Data; using System.Data.SqlClient; using System.Linq; diff --git a/PROMS/VEPROMS.CSLA.Library/Minimal/UserReports.cs b/PROMS/VEPROMS.CSLA.Library/Minimal/UserReports.cs index 32f1cef3..f0e33720 100644 --- a/PROMS/VEPROMS.CSLA.Library/Minimal/UserReports.cs +++ b/PROMS/VEPROMS.CSLA.Library/Minimal/UserReports.cs @@ -1,5 +1,4 @@ using System; -using Csla.Data; using System.Data; using System.Data.SqlClient; diff --git a/PROMS/VEPROMS.CSLA.Library/VEObjects/VEDrillDown.cs b/PROMS/VEPROMS.CSLA.Library/VEObjects/VEDrillDown.cs index 1dee42e0..cb6457dd 100644 --- a/PROMS/VEPROMS.CSLA.Library/VEObjects/VEDrillDown.cs +++ b/PROMS/VEPROMS.CSLA.Library/VEObjects/VEDrillDown.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace VEPROMS.CSLA.Library @@ -9,7 +6,6 @@ namespace VEPROMS.CSLA.Library public interface IVEDrillDownReadOnly { System.Collections.IList GetChildren(); // Returns a list of Business Objects - //bool ChildrenAreLoaded { get; }; // Have the Business Objects been Loaded bool HasChildren { get; } // Identifies if Children are available IVEDrillDownReadOnly ActiveParent { get; } FormatInfo ActiveFormat { get; } @@ -25,17 +21,6 @@ namespace VEPROMS.CSLA.Library bool IsProcedure { get; } bool IsSection { get; } bool IsStep { get; } - //IVEDrillDown Get(); - //bool HasStandardSteps(); - // Ideas Authorization - //bool CanLock(); - //bool CanUnlock(); - //bool CanOpen(); - //bool CanEdit(); - //bool CanAdmin(); - // Ideas Security - //bool Lock(string msg); - //bool Unlock(); } [TypeConverter(typeof(ExpandableObjectConverter))] public interface IVEDrillDown : IVEHasBrokenRules diff --git a/PROMS/VEPROMS.CSLA.Library/VEObjects/VETreeNode.cs b/PROMS/VEPROMS.CSLA.Library/VEObjects/VETreeNode.cs index 4ae00cc6..5090c8e3 100644 --- a/PROMS/VEPROMS.CSLA.Library/VEObjects/VETreeNode.cs +++ b/PROMS/VEPROMS.CSLA.Library/VEObjects/VETreeNode.cs @@ -1,11 +1,6 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Windows.Forms; -using Csla; using System.Collections; -using System.ComponentModel; -using System.Drawing; using System.Reflection; namespace VEPROMS.CSLA.Library @@ -14,35 +9,19 @@ namespace VEPROMS.CSLA.Library public class VETreeNodeEventArgs : EventArgs { public VETreeNodeEventArgs() { ; } - public VETreeNodeEventArgs(string info) + public VETreeNodeEventArgs(string info) => Info = info; + public VETreeNodeEventArgs(int value) => Value = value; + public VETreeNodeEventArgs(string info, int value) { - _Info = info; + Info = info; + Value = value; } - public VETreeNodeEventArgs(int value) - { - _Value = value; - } - public VETreeNodeEventArgs(string info, int value) - { - _Info = info; - _Value = value; - } - private int _Value; - public int Value - { - get { return _Value; } - set { _Value = value; } - } - private string _Info; + public int Value { get; set; } - public string Info - { - get { return _Info; } - set { _Info = value; } - } - - } + public string Info { get; set; } + + } public class VETreeNode : TreeNode { #region Events @@ -51,25 +30,13 @@ namespace VEPROMS.CSLA.Library public event VETreeNodeEvent LoadingChildrenMax; public event VETreeNodeEvent LoadingChildrenValue; public event VETreeNodeEvent LoadingChildrenDone; - private void OnLoadingChildrenSQL(object sender, VETreeNodeEventArgs args) - { - if (LoadingChildrenSQL != null) LoadingChildrenSQL(sender, args); - } - private void OnLoadingChildrenMax(object sender, VETreeNodeEventArgs args) - { - if (LoadingChildrenMax != null) LoadingChildrenMax(sender, args); - } - private void OnLoadingChildrenValue(object sender, VETreeNodeEventArgs args) - { - if (LoadingChildrenValue != null) LoadingChildrenValue(sender, args); - } - private void OnLoadingChildrenDone(object sender, VETreeNodeEventArgs args) - { - if (LoadingChildrenDone != null) LoadingChildrenDone(sender, args); - } - #endregion - #region Business Methods - protected IVEDrillDownReadOnly _VEObject; + private void OnLoadingChildrenSQL(object sender, VETreeNodeEventArgs args) => LoadingChildrenSQL?.Invoke(sender, args); + private void OnLoadingChildrenMax(object sender, VETreeNodeEventArgs args) => LoadingChildrenMax?.Invoke(sender, args); + private void OnLoadingChildrenValue(object sender, VETreeNodeEventArgs args) => LoadingChildrenValue?.Invoke(sender, args); + private void OnLoadingChildrenDone(object sender, VETreeNodeEventArgs args) => LoadingChildrenDone?.Invoke(sender, args); + #endregion + #region Business Methods + protected IVEDrillDownReadOnly _VEObject; public IVEDrillDownReadOnly VEObject { get { return _VEObject; } @@ -80,11 +47,6 @@ namespace VEPROMS.CSLA.Library ResetNode("Dummy Set_VEObject"); } } - //public void Refresh() - //{ - // if (_VEObject != null) - // Text = _VEObject.ToString(); - //} // Only load the Children Once protected bool _ChildrenLoaded = false; public bool ChildrenLoaded @@ -104,16 +66,11 @@ namespace VEPROMS.CSLA.Library get { return _InChildWindow; } set { _InChildWindow = value; } } - // Reset Node - //public void CloseNode() - //{ - // ResetNode(); - //} private void SetProperty(string name) { PropertyInfo propertyInfoObj = _VEObject.GetType().GetProperty(name); if (propertyInfoObj == null) return; - PropertyInfo propertyInfoThis = this.GetType().GetProperty(name); + PropertyInfo propertyInfoThis = GetType().GetProperty(name); if (propertyInfoThis == null) return; try { @@ -129,7 +86,7 @@ namespace VEPROMS.CSLA.Library if (_VEObject!=null && _VEObject.HasChildren && _ChildrenLoaded == false && CheckForParts()) { _ChildrenLoaded = false;// Reset the children loaded flag - this.Nodes.Add(dummy);// Add a Dummy Node so that the item will appear to be expanable. + Nodes.Add(dummy);// Add a Dummy Node so that the item will appear to be expanable. } else { @@ -167,38 +124,8 @@ namespace VEPROMS.CSLA.Library tn.ResetNode("Dummy GetFolder"); return tn; } -// public abstract void LoadChildren(); - //private long _Start; - //private Dictionary _Timings=new Dictionary(); - //private void tReset() - //{ - // _Timings = new Dictionary(); - // _Start = DateTime.Now.Ticks; - //} - //private void tNext(string msg) - //{ - // long tEnd = DateTime.Now.Ticks; - // long tDiff = tEnd - _Start; - // if (_Timings.ContainsKey(msg)) tDiff += _Timings[msg]; - // _Timings[msg] = tDiff; - // _Start = DateTime.Now.Ticks; - //} - //private void tShowResults() - //{ - // Console.WriteLine("Timings"); - // long total=0; - // foreach (string msg in _Timings.Keys) - // { - // total += _Timings[msg]; - // Console.WriteLine("{0}\t\"{1}\"", TimeSpan.FromTicks(_Timings[msg]).TotalMilliseconds, msg); - // } - // Console.WriteLine("{0}\t\"Total\"", TimeSpan.FromTicks(total).TotalMilliseconds); - //} - public virtual void LoadChildren() - { - LoadChildren(true); - } - private bool _allParts = true; + public virtual void LoadChildren() => LoadChildren(true); + private bool _allParts = true; private bool _excludeTablesFigsEqu = false; // used for inserting Step Text transitions (BNPP) public virtual void LoadChildren(bool allParts, bool excldTablesFigEq = false) { @@ -207,33 +134,23 @@ namespace VEPROMS.CSLA.Library _excludeTablesFigsEqu = excldTablesFigEq; if (!_ChildrenLoaded) { - this.Nodes.Clear(); - //tReset(); + Nodes.Clear(); DateTime tStart = DateTime.Now; - //TVAddChildren(_VEObject, this); OnLoadingChildrenSQL(this, new VETreeNodeEventArgs()); IList ol; - ItemInfo item = _VEObject as ItemInfo; - if (item != null) item.RefreshItemParts(); - if (_VEObject.GetType() == typeof(StepInfo) || _VEObject.GetType() == typeof(SectionInfo) || _VEObject.GetType() == typeof(ItemInfo)) + if (_VEObject is ItemInfo item) item.RefreshItemParts(); + if (_VEObject.GetType() == typeof(StepInfo) || _VEObject.GetType() == typeof(SectionInfo) || _VEObject.GetType() == typeof(ItemInfo)) ol = ((ItemInfo)_VEObject).GetChildren(allParts); else ol = _VEObject.GetChildren(); - //tNext("GetChildren"); if (ol != null) { OnLoadingChildrenMax(this, new VETreeNodeEventArgs(ol.Count)); - //this.TreeView.BeginUpdate(); - if (this.TreeView != null) this.TreeView.BeginUpdate(); + if (TreeView != null) TreeView.BeginUpdate(); else _MyLog.WarnFormat("TreeView.BeginUpdate - Null"); ExpandChildren(ol); - //} - //tNext("Set Nodes"); - //this.TreeView.EndUpdate(); - if (this.TreeView != null) this.TreeView.EndUpdate(); + if (TreeView != null) TreeView.EndUpdate(); else _MyLog.WarnFormat("TreeView.EndUpdate - Null"); - //tNext("End Update"); - //tShowResults(); } _ChildrenLoaded = true; OnLoadingChildrenDone(this, new VETreeNodeEventArgs(TimeSpan.FromTicks(DateTime.Now.Ticks - tStart.Ticks).TotalSeconds.ToString())); @@ -247,7 +164,6 @@ namespace VEPROMS.CSLA.Library foreach (IVEDrillDownReadOnly o in ol) { OnLoadingChildrenValue(this, new VETreeNodeEventArgs(++icnt)); - //tNext("Cycle"); try { bool skipIt = false; @@ -277,18 +193,14 @@ namespace VEPROMS.CSLA.Library tmp.ExpandChildren(o.GetChildren()); tmp._ChildrenLoaded = true; } - // OLD: RHM 20100115 : I don't think that the following lines are necessary since the "new VETreeNode(o)" - // above includes a similar function. - //else - // tmp.Nodes.Add(string.Format("dummy: {0}", o.GetType().Name));// Add a Dummy Node so that the item will appear to be expanable. } else tmp._ChildrenLoaded = true;// Reset the children loaded flag if (lastWasSection) - this.Nodes.Insert(0, tmp); + Nodes.Insert(0, tmp); // B2024-019 don't show Tables, Figures, or Equations in step tree when inserting Text Transitions else if (!_excludeTablesFigsEqu || !isTableFigEqu) - this.Nodes.Add(tmp); + Nodes.Add(tmp); // if last thing was section & this is step, do insert - i.e. so that steps go before sections. lastWasSection = (o is PartInfo && (o as PartInfo).PartType == E_FromType.Section); } @@ -302,16 +214,15 @@ namespace VEPROMS.CSLA.Library private void TVAddChildren(IVEDrillDownReadOnly veobj, VETreeNode tn) { OnLoadingChildrenSQL(tn, new VETreeNodeEventArgs()); - IList ol; - ItemInfo item = veobj as ItemInfo; - if (veobj.GetType() == typeof(StepInfo) || veobj.GetType() == typeof(SectionInfo) || veobj.GetType() == typeof(ItemInfo)) + IList ol; + if (veobj.GetType() == typeof(StepInfo) || veobj.GetType() == typeof(SectionInfo) || veobj.GetType() == typeof(ItemInfo)) ol = ((ItemInfo)veobj).GetChildren(true); else ol = veobj.GetChildren(); if (ol != null) { OnLoadingChildrenMax(this, new VETreeNodeEventArgs(ol.Count)); - this.TreeView.BeginUpdate(); + TreeView.BeginUpdate(); int icnt = 0; foreach (IVEDrillDownReadOnly o in ol) { @@ -333,46 +244,36 @@ namespace VEPROMS.CSLA.Library Console.WriteLine("{0}\r\n{1}", ex.Message, ex.InnerException); } } - - //} - this.TreeView.EndUpdate(); + TreeView.EndUpdate(); } } void myItemInfo_Deleted(object sender) { - VETreeNode parnode = Parent as VETreeNode; - if (parnode == null) return; - PartInfo pi = parnode.VEObject as PartInfo; - Remove(); - // get rid of 'Steps', 'RNOs', i.e. grouping nodes, if there are no children. - if (pi != null && parnode.Nodes.Count == 0) + if (!(Parent is VETreeNode parnode)) return; + Remove(); + // get rid of 'Steps', 'RNOs', i.e. grouping nodes, if there are no children. + if (parnode.VEObject is PartInfo && parnode.Nodes.Count == 0) { - VETreeNode grndparnode = parnode.Parent as VETreeNode; - parnode.Remove(); - // if only 'Steps' node is left, move steps 'up' a level. - if (grndparnode != null && grndparnode.Nodes.Count == 1) + parnode.Remove(); + // if only 'Steps' node is left, move steps 'up' a level. + if (parnode.Parent is VETreeNode grndparnode && grndparnode.Nodes.Count == 1) { VETreeNode sibnode = grndparnode.Nodes[0] as VETreeNode; - PartInfo pisib = sibnode.VEObject as PartInfo; - if (pisib != null && (pisib.ToString() == "Steps")) - { - if (!sibnode.ChildrenLoaded) sibnode.LoadChildren(); - while (sibnode.Nodes.Count > 0) - { - VETreeNode tmp = sibnode.Nodes[0] as VETreeNode; - tmp.Remove(); - grndparnode.Nodes.Add(tmp); - } - sibnode.Remove(); - } - } + if (sibnode.VEObject is PartInfo pisib && (pisib.ToString() == "Steps")) + { + if (!sibnode.ChildrenLoaded) sibnode.LoadChildren(); + while (sibnode.Nodes.Count > 0) + { + VETreeNode tmp = sibnode.Nodes[0] as VETreeNode; + tmp.Remove(); + grndparnode.Nodes.Add(tmp); + } + sibnode.Remove(); + } + } } } - //public IVEReadOnlyItem GetCsla() - //{ - // return _VEObject; - //} #endregion #region Factory Methods // Constructors @@ -383,25 +284,24 @@ namespace VEPROMS.CSLA.Library _allParts = allParts; _VEObject = o;// Save the BusinessObject ResetNode("Dummy VETreeNode(IVEDrillDownReadOnly o)"); - ItemInfo myItemInfo = o as ItemInfo; - if (myItemInfo != null) - { - myItemInfo.Deleted -= new ItemInfoEvent(myItemInfo_Deleted); - myItemInfo.Deleted += new ItemInfoEvent(myItemInfo_Deleted); - myItemInfo.ChildrenDeleted -= new ItemInfoEvent(myItemInfo_ChildrenDeleted); - myItemInfo.ChildrenDeleted += new ItemInfoEvent(myItemInfo_ChildrenDeleted); - myItemInfo.MyContent.Changed -= new ContentInfoEvent(NodeText_Changed); - myItemInfo.MyContent.Changed += new ContentInfoEvent(NodeText_Changed); - myItemInfo.OrdinalChanged -= new ItemInfoEvent(NodeText_Changed); - myItemInfo.OrdinalChanged += new ItemInfoEvent(NodeText_Changed); - myItemInfo.NewSiblingAfter -= new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); - myItemInfo.NewSiblingAfter += new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); - myItemInfo.NewSiblingBefore -= new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); - myItemInfo.NewSiblingBefore += new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); - myItemInfo.NewChild -= new ItemInfoInsertEvent(myItemInfo_NewChild); - myItemInfo.NewChild += new ItemInfoInsertEvent(myItemInfo_NewChild); - } - } + if (o is ItemInfo myItemInfo) + { + myItemInfo.Deleted -= new ItemInfoEvent(myItemInfo_Deleted); + myItemInfo.Deleted += new ItemInfoEvent(myItemInfo_Deleted); + myItemInfo.ChildrenDeleted -= new ItemInfoEvent(myItemInfo_ChildrenDeleted); + myItemInfo.ChildrenDeleted += new ItemInfoEvent(myItemInfo_ChildrenDeleted); + myItemInfo.MyContent.Changed -= new ContentInfoEvent(NodeText_Changed); + myItemInfo.MyContent.Changed += new ContentInfoEvent(NodeText_Changed); + myItemInfo.OrdinalChanged -= new ItemInfoEvent(NodeText_Changed); + myItemInfo.OrdinalChanged += new ItemInfoEvent(NodeText_Changed); + myItemInfo.NewSiblingAfter -= new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); + myItemInfo.NewSiblingAfter += new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); + myItemInfo.NewSiblingBefore -= new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); + myItemInfo.NewSiblingBefore += new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); + myItemInfo.NewChild -= new ItemInfoInsertEvent(myItemInfo_NewChild); + myItemInfo.NewChild += new ItemInfoInsertEvent(myItemInfo_NewChild); + } + } void NodeText_Changed(object sender) { Text = _VEObject.ToString(); @@ -422,7 +322,7 @@ namespace VEPROMS.CSLA.Library if (myItemInfo.Sections != null && myItemInfo.Sections.Count > 0 && myItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) { // see if change in children tree nodes. - this.Nodes.Clear(); + Nodes.Clear(); _ChildrenLoaded = false; LoadChildren(true); } @@ -433,25 +333,24 @@ namespace VEPROMS.CSLA.Library { _VEObject = o;// Save the BusinessObject ResetNode("Dummy VETreeNode(IVEDrillDownReadOnly o)"); - ItemInfo myItemInfo = o as ItemInfo; - if (myItemInfo != null) - { - myItemInfo.Deleted -= new ItemInfoEvent(myItemInfo_Deleted); - myItemInfo.Deleted += new ItemInfoEvent(myItemInfo_Deleted); - myItemInfo.ChildrenDeleted -= new ItemInfoEvent(myItemInfo_ChildrenDeleted); - myItemInfo.ChildrenDeleted += new ItemInfoEvent(myItemInfo_ChildrenDeleted); - myItemInfo.MyContent.Changed -= new ContentInfoEvent(NodeText_Changed); - myItemInfo.MyContent.Changed += new ContentInfoEvent(NodeText_Changed); - myItemInfo.OrdinalChanged -= new ItemInfoEvent(NodeText_Changed); - myItemInfo.OrdinalChanged += new ItemInfoEvent(NodeText_Changed); - myItemInfo.NewSiblingAfter -= new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); - myItemInfo.NewSiblingAfter += new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); - myItemInfo.NewSiblingBefore -= new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); - myItemInfo.NewSiblingBefore += new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); - myItemInfo.NewChild -= new ItemInfoInsertEvent(myItemInfo_NewChild); - myItemInfo.NewChild += new ItemInfoInsertEvent(myItemInfo_NewChild); - } - } + if (o is ItemInfo myItemInfo) + { + myItemInfo.Deleted -= new ItemInfoEvent(myItemInfo_Deleted); + myItemInfo.Deleted += new ItemInfoEvent(myItemInfo_Deleted); + myItemInfo.ChildrenDeleted -= new ItemInfoEvent(myItemInfo_ChildrenDeleted); + myItemInfo.ChildrenDeleted += new ItemInfoEvent(myItemInfo_ChildrenDeleted); + myItemInfo.MyContent.Changed -= new ContentInfoEvent(NodeText_Changed); + myItemInfo.MyContent.Changed += new ContentInfoEvent(NodeText_Changed); + myItemInfo.OrdinalChanged -= new ItemInfoEvent(NodeText_Changed); + myItemInfo.OrdinalChanged += new ItemInfoEvent(NodeText_Changed); + myItemInfo.NewSiblingAfter -= new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); + myItemInfo.NewSiblingAfter += new ItemInfoInsertEvent(myItemInfo_NewSiblingAfter); + myItemInfo.NewSiblingBefore -= new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); + myItemInfo.NewSiblingBefore += new ItemInfoInsertEvent(myItemInfo_NewSiblingBefore); + myItemInfo.NewChild -= new ItemInfoInsertEvent(myItemInfo_NewChild); + myItemInfo.NewChild += new ItemInfoInsertEvent(myItemInfo_NewChild); + } + } void myItemInfo_ChildrenDeleted(object sender) { @@ -469,8 +368,7 @@ namespace VEPROMS.CSLA.Library { int nextItemID = args.ItemInserted.NextItem.ItemID; VETreeNode nextNode = FindChildOrGrandChild(nextItemID); - if(nextNode != null) - nextNode.myItemInfo_NewSiblingBefore(sender, args); + nextNode?.myItemInfo_NewSiblingBefore(sender, args); return; } if (args.ItemInserted.MyPrevious != null) // insert after @@ -486,317 +384,65 @@ namespace VEPROMS.CSLA.Library Nodes.Clear(); _ChildrenLoaded = false; ResetNode("Dummy myItemInfo_NewChild"); - ItemInfo item = VEObject as ItemInfo; - if (isExpanded && item != null && item.MyContent.ContentPartCount > 1) // || args.ItemInserted.NextItem != null || args.ItemInserted.MyPrevious != null)) - Expand(); - else - Collapse(); - } + if (isExpanded && VEObject is ItemInfo item && item.MyContent.ContentPartCount > 1) // || args.ItemInserted.NextItem != null || args.ItemInserted.MyPrevious != null)) + Expand(); + else + Collapse(); + } private VETreeNode FindChildOrGrandChild(int itemID) { foreach (TreeNode childNode in Nodes) { - VETreeNode child = childNode as VETreeNode; - if (child != null) - { - ItemInfo item = child.VEObject as ItemInfo; - if (item != null && item.ItemID == itemID) - return child; - } - } + if (childNode is VETreeNode child) + { + if (child.VEObject is ItemInfo item && item.ItemID == itemID) + return child; + } + } foreach (TreeNode childNode in Nodes) { - VETreeNode child = childNode as VETreeNode; - if (child != null && child.VEObject is PartInfo) - foreach (VETreeNode grandchild in child.Nodes) - { - ItemInfo item = grandchild.VEObject as ItemInfo; - if (item != null && item.ItemID == itemID) - return grandchild; - } - } + if (childNode is VETreeNode child && child.VEObject is PartInfo) + foreach (VETreeNode grandchild in child.Nodes) + { + if (grandchild.VEObject is ItemInfo item && item.ItemID == itemID) + return grandchild; + } + } return null; } void myItemInfo_NewSiblingBefore(object sender, ItemInfoInsertEventArgs args) { - if (this.Parent != null) // Only do this if the node has a parent - RHM 20100106 + if (Parent != null) // Only do this if the node has a parent - RHM 20100106 { - ItemInfo ii = args.ItemInserted as ItemInfo; - if (ii == null) - this.Parent.Nodes.Insert(Index, (new VETreeNode(args.ItemInserted))); - else // B2020-142: Can't get properties of restored item (no treeview context menu would be correct after restore) - { - if (ii.IsProcedure) this.Parent.Nodes.Insert(Index, (new VETreeNode(ProcedureInfo.Get(ii.ItemID)))); - if (ii.IsSection) this.Parent.Nodes.Insert(Index, (new VETreeNode(SectionInfo.Get(ii.ItemID)))); - if (ii.IsStep) this.Parent.Nodes.Insert(Index, (new VETreeNode(StepInfo.Get(ii.ItemID)))); - } - } + if (!(args.ItemInserted is ItemInfo ii)) + Parent.Nodes.Insert(Index, (new VETreeNode(args.ItemInserted))); + else // B2020-142: Can't get properties of restored item (no treeview context menu would be correct after restore) + { + if (ii.IsProcedure) Parent.Nodes.Insert(Index, (new VETreeNode(ProcedureInfo.Get(ii.ItemID)))); + if (ii.IsSection) Parent.Nodes.Insert(Index, (new VETreeNode(SectionInfo.Get(ii.ItemID)))); + if (ii.IsStep) Parent.Nodes.Insert(Index, (new VETreeNode(StepInfo.Get(ii.ItemID)))); + } + } } void myItemInfo_NewSiblingAfter(object sender, ItemInfoInsertEventArgs args) { - if (this.Parent != null) // Only do this if the node has a parent - RHM 20100106 + if (Parent != null) // Only do this if the node has a parent - RHM 20100106 { - ItemInfo ii = args.ItemInserted as ItemInfo; - if (ii == null) - this.Parent.Nodes.Insert(Index + 1, (new VETreeNode(args.ItemInserted))); - else // B2020-142: Can't get properties of restored item (no treeview context menu would be correct after restore) - { - if (ii.IsProcedure) this.Parent.Nodes.Insert(Index + 1, (new VETreeNode(ProcedureInfo.Get(ii.ItemID)))); - if (ii.IsSection) this.Parent.Nodes.Insert(Index + 1, (new VETreeNode(SectionInfo.Get(ii.ItemID)))); - if (ii.IsStep) this.Parent.Nodes.Insert(Index + 1, (new VETreeNode(StepInfo.Get(ii.ItemID)))); - } - } + if (!(args.ItemInserted is ItemInfo ii)) + Parent.Nodes.Insert(Index + 1, (new VETreeNode(args.ItemInserted))); + else // B2020-142: Can't get properties of restored item (no treeview context menu would be correct after restore) + { + if (ii.IsProcedure) Parent.Nodes.Insert(Index + 1, (new VETreeNode(ProcedureInfo.Get(ii.ItemID)))); + if (ii.IsSection) Parent.Nodes.Insert(Index + 1, (new VETreeNode(SectionInfo.Get(ii.ItemID)))); + if (ii.IsStep) Parent.Nodes.Insert(Index + 1, (new VETreeNode(StepInfo.Get(ii.ItemID)))); + } + } } public VETreeNode(string s) : base(s) { _VEObject = null;// Save the BusinessObject - //ResetNode(); } #endregion } - //public class VETreeNodeBase : VETreeNode - //where T : VETreeNode, new() - //{ - // #region Factory Methods - // private static int _ICount = 0; - // public VETreeNodeBase(string s) : base(s) { ;} - // public VETreeNodeBase(IVEReadOnlyItem o) : base(o) { ;} - // protected VETreeNodeBase() : base() { - // } - // private DateTime tNext(DateTime tStart, string msg) - // { - // DateTime tEnd = DateTime.Now; - // TimeSpan ts = new TimeSpan(tEnd.Ticks-tStart.Ticks); - // Console.WriteLine("{0} - {1}", ts.TotalMilliseconds, msg); - // return tEnd; - // } - // public override void LoadChildren() - // { - // if (!_ChildrenLoaded) - // { - // this.Nodes.Clear(); - // "".TrimEnd("\r\n".ToCharArray()); - // IList ol = _VEObject.GetChildren(); - // if (ol != null) - // { - // this.TreeView.BeginUpdate(); - // DateTime tStart = DateTime.Now; - // T[] tmpa = new T[ol.Count]; - // tStart = tNext(tStart, "Allocate Array"); - // for (int i = 0; i < ol.Count; i++) tmpa[i] = new T(); - // tStart = tNext(tStart, "Allocate Nodes"); - // int ii = 0; - // foreach (IVEReadOnlyItem o in ol) - // { - // try - // { - // tmpa[ii++].VEObject = o; - // } - // catch (Exception ex) - // { - // Console.WriteLine("{0}\r\n{1}", ex.Message, ex.InnerException); - // } - // } - // tStart = tNext(tStart, "Set Nodes"); - // for (int i = 0; i < ol.Count; i++) tmpa[i].ResetNode(); - // tStart = tNext(tStart, "Reset Nodes"); - // this.Nodes.AddRange(tmpa); - // tStart = tNext(tStart, "Add Range"); - // //foreach (IVEReadOnlyItem o in ol) - // //{ - // // try - // // { - // // T tmp = new T(); - // // tmp.VEObject = o; - // // this.Nodes.Add(tmp); - // // } - // // catch (Exception ex) - // // { - // // Console.WriteLine("{0}\r\n{1}", ex.Message, ex.InnerException); - // // } - // //} - // this.TreeView.EndUpdate(); - // } - // _ChildrenLoaded = true; - // } - // } - //#endregion - //} - /* - public class VEFolder : VETreeNodeBase - { - public static VEFolder GetFolder(int folderID) - { - return new VEFolder(FolderInfo.Get(folderID)); - } - //public static VEFolder LoadTree() - //{ - // VEFolder root = null; - // FolderInfoList fil = FolderInfoList.Get(); - // Dictionary dicMissing = new Dictionary(); - // Dictionary dicExists = new Dictionary(); - // foreach (FolderInfo fi in fil) - // { - // VEFolder ftp = null; - // if (dicExists.ContainsKey(fi.ParentID)) - // { - // ftp = dicExists[fi.ParentID]; - // } - // else - // { - // if (fi.ParentID != fi.FolderID) - // { - // ftp = new VEFolder(fi.ParentID.ToString()); - // dicMissing.Add(fi.ParentID, ftp); - // dicExists.Add(fi.ParentID, ftp); - // } - // } - // VEFolder ft = null; - // if (dicMissing.ContainsKey(fi.FolderID)) - // { - // ft = dicMissing[fi.FolderID]; - // ft.VEObject = fi; - // dicMissing.Remove(fi.FolderID); - // } - // else - // { - // ft = new VEFolder(fi); - // dicExists.Add(fi.FolderID, ft); - // } - // if (fi.ParentID == fi.FolderID) - // root = ft; - // else - // ftp.Nodes.Add(ft); - // } - // //root.FindTree = dicExists; - // return root; - //} - private VEFolder(string s) : base(s) { ;} - public VEFolder(IVEReadOnlyItem o) : base(o) { ;} - } - public class VEVersion : VETreeNodeBase { } - public class VEProcedure : VETreeNodeBase - { - //public override void LoadChildren() - //{ - // if (!_ChildrenLoaded) - // { - // this.Nodes.Clear(); - // Dictionary dicSect = new Dictionary(); - // SectionInfoList ol = (SectionInfoList)_VEObject.GetChildren(); - // if (ol != null) - // { - // foreach (SectionInfo o in ol) - // { - // try - // { - // VESection tmp = new VESection(); - // tmp.VEObject = o; - // if (dicSect.ContainsKey(o.PPath)) - // dicSect[o.PPath].Nodes.Add(tmp); - // else - // this.Nodes.Add(tmp); - // dicSect[o.Path] = tmp; - // } - // catch (Exception ex) - // { - // Console.WriteLine("{0}\r\n{1}", ex.Message, ex.InnerException); - // } - // } - // } - // _ChildrenLoaded = true; - // } - //} - } - public class VESection : VETreeNodeBase { } - public class VEStep : VETreeNodeBase { } - */ - //public class VETree : VETreeNodeBase - //{ - // public VETree() { ;} - // public static VETree GetFolder(int folderID) - // { - // return new VETree(FolderInfo.Get(folderID)); - // } - // //private VEFolder(string s) : base(s) { ;} - // public VETree(IVEReadOnlyItem o) : base(o) { ;} - //} - //public class VETree : VETreeNode - //{ - // public VETree() { ;} - // public static VETree GetFolder(int folderID) - // { - // VETree tn = new VETree(FolderInfo.Get(folderID)); - // tn.ResetNode(); - // return tn; - // } - // //private VEFolder(string s) : base(s) { ;} - // public VETree(IVEReadOnlyItem o) : base(o) { ;} - // private DateTime tNext(DateTime tStart, string msg) - // { - // DateTime tEnd = DateTime.Now; - // TimeSpan ts = new TimeSpan(tEnd.Ticks - tStart.Ticks); - // Console.WriteLine("{0} - {1}", ts.TotalMilliseconds, msg); - // return tEnd; - // } - // public override void LoadChildren() - // { - // if (!_ChildrenLoaded) - // { - // this.Nodes.Clear(); - // "".TrimEnd("\r\n".ToCharArray()); - // IList ol = _VEObject.GetChildren(); - // if (ol != null) - // { - // this.TreeView.BeginUpdate(); - // DateTime tStart = DateTime.Now; - // //VETree[] tmpa = new VETree[ol.Count]; - // //tStart = tNext(tStart, "Allocate Array"); - // ////for (int i = 0; i < ol.Count; i++) tmpa[i] = new VETree(); - // ////tStart = tNext(tStart, "Allocate Nodes"); - // //int ii = 0; - // //foreach (IVEReadOnlyItem o in ol) - // //{ - // // try - // // { - // // tmpa[ii++] = new VETree(o); - // // //tmpa[ii++].VEObject = o; - // // } - // // catch (Exception ex) - // // { - // // Console.WriteLine("{0}\r\n{1}", ex.Message, ex.InnerException); - // // } - // //} - // //tStart = tNext(tStart, "Set Nodes"); - // //for (int i = 0; i < ol.Count; i++) tmpa[i].ResetNode(); - // //tStart = tNext(tStart, "Reset Nodes"); - // //this.Nodes.AddRange(tmpa); - // //tStart = tNext(tStart, "Add Range"); - // this.TreeView.DrawMode = TreeViewDrawMode.OwnerDrawAll; - // foreach (IVEReadOnlyItem o in ol) - // { - // try - // { - // VETree tmp = new VETree(o); - // //tmp.VEObject = o; - // this.Nodes.Add(tmp); - // } - // catch (Exception ex) - // { - // Console.WriteLine("{0}\r\n{1}", ex.Message, ex.InnerException); - // } - // } - // tStart = tNext(tStart, "Set Nodes"); - // this.TreeView.DrawMode = TreeViewDrawMode.Normal; - // tStart = tNext(tStart, "DrawMode"); - // this.TreeView.EndUpdate(); - // tStart = tNext(tStart, "End Update"); - // this.TreeView.Refresh(); - // tStart = tNext(tStart, "Refresh"); - // } - // _ChildrenLoaded = true; - // } - // } - //} } diff --git a/PROMS/VEPROMS.CSLA.Library/VEPROMS.CSLA.Library.csproj b/PROMS/VEPROMS.CSLA.Library/VEPROMS.CSLA.Library.csproj index db431669..39afc380 100644 --- a/PROMS/VEPROMS.CSLA.Library/VEPROMS.CSLA.Library.csproj +++ b/PROMS/VEPROMS.CSLA.Library/VEPROMS.CSLA.Library.csproj @@ -148,7 +148,6 @@ - @@ -388,6 +387,7 @@ + diff --git a/PROMS/VEPROMS.CSLA.Library/frmRofstLoadStatus.cs b/PROMS/VEPROMS.CSLA.Library/frmRofstLoadStatus.cs index cc9b1e41..89631aac 100644 --- a/PROMS/VEPROMS.CSLA.Library/frmRofstLoadStatus.cs +++ b/PROMS/VEPROMS.CSLA.Library/frmRofstLoadStatus.cs @@ -1,41 +1,26 @@ 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.Base.Library; -using JR.Utils.GUI.Forms; using System.Threading; namespace VEPROMS.CSLA.Library { public partial class frmRofstLoadStatus : Form { - #region Fields + #region Fields - #endregion + #endregion - #region Properties + #region Properties - public string Title - { - get { return lblTitle.Text; } - } + public string Title => lblTitle.Text; - public string DisplayText - { - get { return statusProgressBar.Text; } - } + public string DisplayText => statusProgressBar.Text; - #endregion + #endregion - #region Constructor + #region Constructor - public frmRofstLoadStatus() + public frmRofstLoadStatus() { // B2022-107: Display Progress Bar Messages/Statuses when a new ROFST binary file is loaded into the database // Initialize Base Component @@ -64,14 +49,14 @@ namespace VEPROMS.CSLA.Library lblTitle.Text = title; - this.Refresh(); + Refresh(); Application.DoEvents(); // Check if Finalizing Status/Progress Bar if (curVal >= 100) { Thread.Sleep(3000); - this.Close(); + Close(); } } diff --git a/PROMS/VG/IVGOutput.cs b/PROMS/VG/IVGOutput.cs index 2e5ec04a..1035e0f9 100644 --- a/PROMS/VG/IVGOutput.cs +++ b/PROMS/VG/IVGOutput.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text.factories; -using Microsoft.Win32; using Volian.Base.Library; namespace VG @@ -25,141 +20,25 @@ namespace VG } public partial class VGOut_Graphics: IVGOutput { - private int _DebugStatus = 0; - public int DebugStatus - { - get { return _DebugStatus; } - set { _DebugStatus = value; } - } - private Graphics _VGOutput; - //public Graphics VGOutput - //{ get { return _VGOutput; } } - public VGOut_Graphics(Graphics vgOutput) - { _VGOutput = vgOutput; } - public float Scale - { get { return 1; } } - //{ get { return _VGOutput.Transform.Elements[0]; } } - public void DrawLine(Pen pn, float startx, float starty, float endx, float endy) - { _VGOutput.DrawLine(pn, startx, starty, endx, endy); } - public void DrawRectangle(Pen pn, RectangleF rectf) + public int DebugStatus { get; set; } = 0; + private readonly Graphics _VGOutput; + public VGOut_Graphics(Graphics vgOutput) => _VGOutput = vgOutput; + public float Scale => 1; + public void DrawLine(Pen pn, float startx, float starty, float endx, float endy) => _VGOutput.DrawLine(pn, startx, starty, endx, endy); + public void DrawRectangle(Pen pn, RectangleF rectf) { _VGOutput.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; _VGOutput.FillRectangle(DebugStatus == 1 ? Brushes.Transparent : Brushes.White, rectf.X, rectf.Y, rectf.Width, rectf.Height); _VGOutput.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; _VGOutput.DrawRectangle(pn, rectf.X, rectf.Y, rectf.Width, rectf.Height); } - public void DrawEllipse(Pen pn, float cx, float cy, float dx, float dy) - { _VGOutput.DrawEllipse(pn, cx, cy, dx, dy); } - public void DrawImage(Bitmap bm, RectangleF rectf) - { _VGOutput.DrawImage(bm, rectf); } - public void DrawString(string text, Font myFont, Brush brush, RectangleF rectf) - { _VGOutput.DrawString(text, myFont, brush, rectf, StringFormat.GenericTypographic); } - public void DrawArc(Pen pn, RectangleF rectf, float startAngle, float sweepAngle) - { _VGOutput.DrawArc(pn, rectf, startAngle, sweepAngle); } - public SizeF MeasureString(string text, Font myFont) - { return _VGOutput.MeasureString(text, myFont, new PointF(0, 0), StringFormat.GenericTypographic); } - public void Save(string fileName) + public void DrawEllipse(Pen pn, float cx, float cy, float dx, float dy) => _VGOutput.DrawEllipse(pn, cx, cy, dx, dy); + public void DrawImage(Bitmap bm, RectangleF rectf) => _VGOutput.DrawImage(bm, rectf); + public void DrawString(string text, Font myFont, Brush brush, RectangleF rectf) => _VGOutput.DrawString(text, myFont, brush, rectf, StringFormat.GenericTypographic); + public void DrawArc(Pen pn, RectangleF rectf, float startAngle, float sweepAngle) => _VGOutput.DrawArc(pn, rectf, startAngle, sweepAngle); + public SizeF MeasureString(string text, Font myFont) => _VGOutput.MeasureString(text, myFont, new PointF(0, 0), StringFormat.GenericTypographic); + public void Save(string fileName) { ;/* Don't do anything*/ } - public float FontSizeAdjust - { get { return .71f * 96f / _VGOutput.DpiX; } } // Changed to adjust for Screen DPI Setting - } - public partial class VGOut_ITextSharp : IVGOutput - { - private int _DebugStatus = 0; - public int DebugStatus - { - get { return _DebugStatus; } - set { _DebugStatus = value; } - } - private PdfContentByte _VGOutput; - //public Graphics VGOutput - //{ get { return _VGOutput; } } - public VGOut_ITextSharp(PdfContentByte vgOutput) - { _VGOutput = vgOutput; } - public float Scale - { get { return 1; } } - public void DrawLine(Pen pn, float startx, float starty, float endx, float endy) - { - _VGOutput.SaveState(); - SetStrokeData(pn); - _VGOutput.MoveTo(startx, ScaleY(starty)); - _VGOutput.LineTo(endx, ScaleY(endy)); - _VGOutput.Stroke(); - _VGOutput.RestoreState(); - } - private void SetStrokeData(Pen pn) - { - _VGOutput.SetLineWidth(pn.Width); - _VGOutput.SetColorStroke(new iTextSharp.text.Color(pn.Color.R, pn.Color.G, pn.Color.B, pn.Color.A)); - } - public void DrawRectangle(Pen pn, RectangleF rectf) - { - _VGOutput.SaveState(); - SetStrokeData(pn); - _VGOutput.Rectangle(rectf.X, ScaleY(rectf.Y), rectf.Width, -rectf.Height); - _VGOutput.Stroke(); - _VGOutput.RestoreState(); - } - public void DrawEllipse(Pen pn, float cx, float cy, float dx, float dy) - { - _VGOutput.SaveState(); - SetStrokeData(pn); - _VGOutput.Ellipse(cx, ScaleY(cy), dx, -dy); - _VGOutput.Stroke(); - _VGOutput.RestoreState(); - } - public void DrawImage(Bitmap bm, RectangleF rectf) - { - _VGOutput.SaveState(); - // TODO: Determine how I can create an iTextSharp.text.Image - //_VGOutput.AddImage(new iTextSharp.text.Image( - _VGOutput.RestoreState(); - } - public void DrawString(string text, Font myFont, Brush brush, RectangleF rectf) - { - _VGOutput.SaveState(); - _VGOutput.BeginText(); - iTextSharp.text.Font itFont = GetFont(myFont.Name); - iTextSharp.text.pdf.BaseFont baseFont = itFont.BaseFont; - // _VGOutput.DrawString(text, myFont, brush, rectf, StringFormat.GenericTypographic); - _VGOutput.MoveText(rectf.X, ScaleY(rectf.Y) - myFont.SizeInPoints); - _VGOutput.SetFontAndSize(baseFont, myFont.SizeInPoints); - _VGOutput.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); - _VGOutput.ShowTextKerned(text); - _VGOutput.EndText(); - _VGOutput.RestoreState(); - } - public void DrawArc(Pen pn, RectangleF rectf, float startAngle, float sweepAngle) - { - _VGOutput.SaveState(); - SetStrokeData(pn); - _VGOutput.Arc(rectf.X, ScaleY(rectf.Y), rectf.X + rectf.Width, ScaleY(rectf.Y + rectf.Height), -startAngle, -sweepAngle); - _VGOutput.Stroke(); - _VGOutput.RestoreState(); - } - public SizeF MeasureString(string text, Font myFont) - { - iTextSharp.text.Font itFont = GetFont(myFont.Name); - iTextSharp.text.pdf.BaseFont baseFont = itFont.BaseFont; - return new SizeF(baseFont.GetWidthPoint(text,myFont.SizeInPoints) - , baseFont.GetAscentPoint(text, myFont.SizeInPoints) + baseFont.GetDescentPoint(text, myFont.SizeInPoints)); - } - public void Save(string fileName) - { ;/* Don't do anything*/ } - public float FontSizeAdjust - { get { return 1; } } // Changed to adjust for Screen DPI Setting - public static iTextSharp.text.Font GetFont(string fontName) - { - /// - /// B2019-116 Volian.Base.Library This is a generic class for dealing with iTextSharp Fonts - /// Code moved and consolidated from Volian.Print.Library Volian PDF.Library and VG - /// - VlnItextFont.RegisterFont(fontName); - return iTextSharp.text.FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); - } - private float ScaleY(float y) - { - return _VGOutput.PdfWriter.PageSize.Height - y; - } - } + public float FontSizeAdjust => .71f * 96f / _VGOutput.DpiX; // Changed to adjust for Screen DPI Setting + } } diff --git a/PROMS/VG/VG.cs b/PROMS/VG/VG.cs index 856efbd1..7e047535 100644 --- a/PROMS/VG/VG.cs +++ b/PROMS/VG/VG.cs @@ -20,64 +20,34 @@ namespace VG // Temporary page class to store portrait/landscape, Left Margin, Vertical offset, etc public class Page { - private bool _Portrait = true; - public bool Portrait + public bool Portrait { get; set; } = true; + public float LeftMargin { get; set; } = 0; + public float TopMargin { get; set; } = 0; + public float RightMargin { get; set; } = 0; + public float BottomMargin { get; set; } = 0; + public Page(bool portrait, float leftMargin, float topMargin, float rightMargin, float bottomMargin) { - get { return _Portrait; } - set { _Portrait = value; } - } - private float _LeftMargin = 0; - public float LeftMargin - { - get { return _LeftMargin; } - set { _LeftMargin = value; } - } - private float _TopMargin = 0; - public float TopMargin - { - get { return _TopMargin; } - set { _TopMargin = value; } - } - private float _RightMargin = 0; - public float RightMargin - { - get { return _RightMargin; } - set { _RightMargin = value; } - } - private float _BottomMargin = 0; - public float BottomMargin - { - get { return _BottomMargin; } - set { _BottomMargin = value; } - } - public Page(bool portrait, float leftMargin, float topMargin, float rightMargin, float bottomMargin) - { - _Portrait = portrait; - _LeftMargin = leftMargin; - _TopMargin = topMargin; - _RightMargin = rightMargin; - _BottomMargin = bottomMargin; + Portrait = portrait; + LeftMargin = leftMargin; + TopMargin = topMargin; + RightMargin = rightMargin; + BottomMargin = bottomMargin; } public Page(bool portrait, float leftMargin, float topMargin) { - _Portrait = portrait; - _LeftMargin = leftMargin; - _TopMargin = topMargin; + Portrait = portrait; + LeftMargin = leftMargin; + TopMargin = topMargin; } } public class VG { - private static Brush _BlackBrush = Brushes.Black; - public static Brush BlackBrush - { - get { return _BlackBrush; } - set { _BlackBrush = value; } - } - private static Color _BlackColor = Color.Black; + public static Brush BlackBrush { get; set; } = Brushes.Black; + private static Color _BlackColor = Color.Black; public static Color BlackColor { get { return _BlackColor; } - set { _BlackColor = value; _BlackBrush = new SolidBrush(value); } + set { _BlackColor = value; BlackBrush = new SolidBrush(value); } } // Values of vector graphics items are stored as twips (1440 twips in an inch) public int cx; @@ -105,16 +75,12 @@ namespace VG MoveAbsolute = ima; pg = ipg; } - public float ToPoints(float twip) - { - float r = ((float)twip) * 0.05f; - return r; - } - public void UpdatePageInfo(Page pa) + public float ToPoints(float twip) => (float)(((float)twip) * 0.05f); + public void UpdatePageInfo(Page pa) { pg.LeftMargin = pa.LeftMargin; - pg.Portrait = pa.Portrait; // RHM 20081003 - This had been pg.portrait=pg.portrait - pg.TopMargin = pa.TopMargin; // RHM 20081003 - This had been pg.VertOffset=pg.VertOffset + pg.Portrait = pa.Portrait; + pg.TopMargin = pa.TopMargin; } public string AddRTFBUI(string origStr, string bold, string underline, string italics) { @@ -145,7 +111,6 @@ namespace VG int B1 = (int)(colorFraction * color.B); int B2 = (int)((1 - colorFraction) * Color.White.B); pn = new Pen(Color.FromArgb(R1 + R2, G1 + G2, B1 + B2), scaleWid); - //pn = new Pen(color, wid*wid); } else pn = new Pen(color, scaleWid); @@ -217,74 +182,14 @@ namespace VG vgOutput.DrawRectangle(pn, rc); } } - public class VG_Image : VG - { - private int Scale; - private string FileName; - // Image is defined as starting point, scale factor (defaults to 1) & image file name - public VG_Image(int sx, int sy, int iscale, string fname) - { - cx = sx; - cy = sy; - Scale = 1; - FileName = fname; - } - public VG_Image(XmlElement svg, Page ipg) - { - cx = System.Convert.ToInt32(svg.GetAttribute("x")); - cy = System.Convert.ToInt32(svg.GetAttribute("y")); - Scale = 1; - if (svg.HasAttribute("scale")) Scale = System.Convert.ToInt32(svg.GetAttribute("scale")); - FileName = svg.GetAttribute("bname"); - pg = ipg; - } - public void Draw(IVGOutput vgOutput) - { - Pen pn = new Pen(VG.BlackBrush, lnwid); - Bitmap bm = new Bitmap(FileName); - RectangleF rc = new RectangleF(); - rc.Height = ToPoints((bm.Height * Scale) * 4.8f); - rc.Width = ToPoints((bm.Width * Scale) * 4.8f); - rc.X = ToPoints(pg.LeftMargin + cx); - rc.Y = ToPoints(pg.TopMargin + cy); - // TODO: grfx.DrawImage(bm, rc, ContentAlignment.MiddleCenter, ImageSizeModeEnum.Scale); - } - } - public class VG_Ellipse : VG - { - // Ellipse (circle) is defined by a bounding rectangle specified by a coordinate pair, a width, and a height - public VG_Ellipse(int sx, int sy, int ex, int ey, int w, Page ipg) - { - cx = sx; - cy = sy; - dx = ex; - dy = ey; - lnwid = w; - pg = ipg; - } - public VG_Ellipse(XmlElement svg, Page ipg) - { - cx = System.Convert.ToInt32(svg.GetAttribute("cx")); - cy = System.Convert.ToInt32(svg.GetAttribute("cy")); - dx = System.Convert.ToInt32(svg.GetAttribute("rx")); - dy = System.Convert.ToInt32(svg.GetAttribute("ry")); - lnwid = System.Convert.ToInt32(svg.GetAttribute("stroke-width")); - pg = ipg; - } - public void Draw(IVGOutput vgOutput) - { - Pen pn = new Pen(VG.BlackBrush, ToPoints(lnwid)); - vgOutput.DrawEllipse(pn, ToPoints(pg.LeftMargin + cx), ToPoints(pg.TopMargin + cy), ToPoints(dx), ToPoints(dy)); - } - } public class VG_Text : VG { - private string FontName; - private int FontSize; - private string Bold; - private string Underline; - private string Italics; - private string Text; + private readonly string FontName; + private readonly int FontSize; + private readonly string Bold; + private readonly string Underline; + private readonly string Italics; + private readonly string Text; // Text is defined by a starting location, attributes & the string public VG_Text(int sx, int sy, int fs, string txt, string fn, string ibold, string iunder, string iitalics, Page ipg) { @@ -297,48 +202,28 @@ namespace VG Underline = iunder; Italics = iitalics; pg = ipg; - // TODO: The following were in the 16-bit code - we may need to use these, wait and see - // strokeWidth = stroke; - // strokeWidthBold = strokebold; - // ULOffset = UnderlineOffset; - // ULWidth = UnderlineWidth; - } - public VG_Text(XmlElement svg, Page ipg) - { - cx = System.Convert.ToInt32(svg.GetAttribute("x")); - cy = System.Convert.ToInt32(svg.GetAttribute("y")); - FontSize = System.Convert.ToInt32(svg.GetAttribute("font-size")); - Bold = svg.GetAttribute("font-weight"); - Underline = svg.GetAttribute("text-decoration"); - Italics = svg.GetAttribute("font-style"); - FontName = svg.GetAttribute("font-family"); - Text = svg.InnerText; - pg = ipg; } public void Draw(IVGOutput vgOutput) { // TODO: Font myfont = new Font(FontName, (FontSize*9)/10); Font myfont = new Font(FontName, FontSize * vgOutput.FontSizeAdjust); // TODO: Trying 80% - RectangleF rc = new RectangleF(); - // the returned value from c1 grfx code is already in points, - // so need to convert the size. - rc.Size = vgOutput.MeasureString(Text, myfont); // TODO: 500 or pagewidth, or what - //rc.Size = grfx.MeasureString(Text, myfont, 500); // TODO: 500 or pagewidth, or what - rc.X = ToPoints(pg.LeftMargin + cx); - rc.Y = ToPoints(pg.TopMargin + cy) - FontSize; - rc.Height *= 1.0000001F; // Small factor to make text visible. - // add bold, underline & italics for entire object. - // TODO: string rtfout = AddRTFBUI(Text, Bold, Underline, Italics); - //using(Pen pn = new Pen(Color.DarkBlue, .1F)) - // grfx.DrawRectangle(pn, rc.X,rc.Y,rc.Width,rc.Height); + RectangleF rc = new RectangleF + { + // the returned value from c1 grfx code is already in points, + // so need to convert the size. + Size = vgOutput.MeasureString(Text, myfont), // TODO: 500 or pagewidth, or what + //rc.Size = grfx.MeasureString(Text, myfont, 500); // TODO: 500 or pagewidth, or what + X = ToPoints(pg.LeftMargin + cx), + Y = ToPoints(pg.TopMargin + cy) - FontSize + }; + rc.Height *= 1.0000001F; // Small factor to make text visible. vgOutput.DrawString(Text, myfont, VG.BlackBrush, rc); - //grfx.DrawString(Text, myfont, VG.BlackBrush, rc); } } public class VG_Arc : VG { - public Single sweepAngle; - public Single startAngle; + public float sweepAngle; + public float startAngle; public float stX, stY; public float rWid, rHgt; // Arc is defined by a bounding rectangle specified by a coordinate pair, a width, and a height @@ -365,9 +250,7 @@ namespace VG rHgt = -hight; } startAngle = stAngle; - // startAngle = 90; sweepAngle = swpAngle; - // sweepAngle = -45; lnwid = w; pg = ipg; } @@ -391,18 +274,6 @@ namespace VG float starty = pg.Portrait ? (stY + pg.TopMargin) : (pg.LeftMargin - stX); RectangleF rc = new RectangleF(ToPoints(startx), ToPoints(starty), ToPoints(rWid), ToPoints(rHgt)); //Console.WriteLine("{0},'{1}',{2},{3},{4},{5},{6},{7}", iColor, pn.Color, rc.X, rc.Y, rc.Width, rc.Height, startAngle, sweepAngle); - //if (iColor == 7 || iColor == 8) return; - //if (iColor == 6) return; - //if (iColor == 4 || iColor == 6) - //{ - // using (Pen lightPen = new Pen(myColors[iColor % myColors.Length], .01F)) - //{ - // vgOutput.DrawEllipse(lightPen, rc.X, rc.Y, rc.Width, rc.Height); - // float xc = rc.X + (rc.Width / 2); - // float yc = rc.Y + (rc.Height / 2); - // vgOutput.DrawEllipse(lightPen, xc - .5F, yc - .5F, 1F, 1F); - //} - //} if (sweepAngle > 0) vgOutput.DrawArc(pn, rc, startAngle, sweepAngle); else diff --git a/PROMS/Volian.Base.Library/BigNum.cs b/PROMS/Volian.Base.Library/BigNum.cs index 1567917a..eb133fce 100644 --- a/PROMS/Volian.Base.Library/BigNum.cs +++ b/PROMS/Volian.Base.Library/BigNum.cs @@ -6,7 +6,6 @@ using System.Xml.Serialization; namespace Volian.Base.Library { [Serializable()] - //[XmlRoot("BigNum")] public class BigNum { #region fields @@ -22,19 +21,10 @@ namespace Volian.Base.Library public BigNum() { } - public BigNum(int value) - { - SetFlag(value); - } - public BigNum(string values) - { - SetFlags(values); - } - public BigNum(ICollection values) - { - SetFlags(values); - } - public override string ToString() + public BigNum(int value) => SetFlag(value); + public BigNum(string values) => SetFlags(values); + public BigNum(ICollection values) => SetFlags(values); + public override string ToString() { return FlagList; } @@ -58,10 +48,6 @@ namespace Volian.Base.Library } #endregion #region methods - //public override string ToString() - //{ - // return GenericSerializer.StringSerialize(this); - //} public bool Includes(BigNum other) { List mine = GetFlags(); @@ -82,12 +68,6 @@ namespace Volian.Base.Library public List GetFlags() { List myints = new List(); - //if (MyValue.Count == 0)//1 && MyValue.ContainsKey(0) && MyValue[0] == 0) - //{ - // myints.Add(-1); - //} - //else - //{ foreach (uint key in MyValue.Keys) { ulong y = MyValue[key]; @@ -97,18 +77,10 @@ namespace Volian.Base.Library myints.Add((int)(i + (key * 64))); } } - //} return myints; } public void SetFlag(int flag) { - //if (flag == -1) - //{ - // MyValue = new SortedDictionary(); - // //MyValue.Add(0, 0); - //} - //else - //{ uint offset = (uint)(flag / 64); ulong x = one << (flag % 64); if (MyValue.ContainsKey(offset)) @@ -122,15 +94,10 @@ namespace Volian.Base.Library foreach (int f in flags) SetFlag(f); } - public static BigNum MakeBigNum(string numbers) - { - if (numbers == "-1") - return null; - return new BigNum(numbers); - } - #endregion - #region properties - [XmlAttribute] + public static BigNum MakeBigNum(string numbers) => numbers == "-1" ? null : new BigNum(numbers); + #endregion + #region properties + [XmlAttribute] public string FlagList { get diff --git a/PROMS/Volian.Base.Library/ByteArrayCompare.cs b/PROMS/Volian.Base.Library/ByteArrayCompare.cs index bd833e4a..e85ba376 100644 --- a/PROMS/Volian.Base.Library/ByteArrayCompare.cs +++ b/PROMS/Volian.Base.Library/ByteArrayCompare.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Volian.Base.Library +namespace Volian.Base.Library { public static class ByteArrayCompare { diff --git a/PROMS/Volian.Base.Library/DebugPrint.cs b/PROMS/Volian.Base.Library/DebugPrint.cs index 5d6f3258..bb204c84 100644 --- a/PROMS/Volian.Base.Library/DebugPrint.cs +++ b/PROMS/Volian.Base.Library/DebugPrint.cs @@ -1,17 +1,12 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Text; namespace Volian.Base.Library { public class DebugPrint:IDisposable { - public void Dispose() - { - Close(); - } - private StreamWriter _MyStreamWriter = null; + public void Dispose() => Close(); + private StreamWriter _MyStreamWriter = null; public StreamWriter MyStreamWriter { get { return _MyStreamWriter; } @@ -25,11 +20,8 @@ namespace Volian.Base.Library _MyStreamWriter = value; } } - public bool IsOpen - { - get { return MyStreamWriter != null; } - } - private string _FileName = null; + public bool IsOpen => MyStreamWriter != null; + private string _FileName = null; public string FileName { get { return _FileName; } @@ -40,22 +32,15 @@ namespace Volian.Base.Library MyFileInfo = new FileInfo(value); } } - private FileInfo _MyFileInfo; - public FileInfo MyFileInfo - { - get { return _MyFileInfo; } - set { _MyFileInfo = value; } - } - public void Open(string fileName) + + public FileInfo MyFileInfo { get; set; } + public void Open(string fileName) { FileName = fileName; MyStreamWriter = MyFileInfo.CreateText(); } - public void Close() - { - MyStreamWriter = null; - } - public void Write(string format, params object[] args) + public void Close() => MyStreamWriter = null; + public void Write(string format, params object[] args) { if (IsOpen) MyStreamWriter.Write(format, args); } @@ -73,116 +58,80 @@ namespace Volian.Base.Library } public static class DebugPagination { - private static int _TotalPages = 0; - public static int TotalPages - { - get { return _TotalPages; } - set { _TotalPages = value; } - } - private static DebugPrint _MyDebugPrint = new DebugPrint(); - public static void Open(string fileName) - { _MyDebugPrint.Open(fileName); } - public static void Close() + public static int TotalPages { get; set; } = 0; + private static readonly DebugPrint _MyDebugPrint = new DebugPrint(); + public static void Open(string fileName) => _MyDebugPrint.Open(fileName); + public static void Close() { WriteLine("{0} Total Pages", TotalPages); _MyDebugPrint.Close(); } - public static void Write(string format, params object[] args) - { _MyDebugPrint.Write(format, args); } - public static void WriteLine(string format, params object[] args) - { _MyDebugPrint.WriteLine(format, args); } - public static void Show() - { _MyDebugPrint.Show(); } - public static bool IsOpen - { get { return _MyDebugPrint.IsOpen; } } - } + public static void Write(string format, params object[] args) => _MyDebugPrint.Write(format, args); + public static void WriteLine(string format, params object[] args) => _MyDebugPrint.WriteLine(format, args); + public static void Show() => _MyDebugPrint.Show(); + public static bool IsOpen => _MyDebugPrint.IsOpen; + } public static class DebugText { - private static DebugPrint _MyDebugPrint = new DebugPrint(); - public static void Open(string fileName) - { _MyDebugPrint.Open(fileName); } - public static void Close() - { _MyDebugPrint.Close(); } - public static void Write(string format, params object[] args) - { _MyDebugPrint.Write(format, args); } - public static void WriteLine(string format, params object[] args) - { _MyDebugPrint.WriteLine(format, args); } - public static void Show() - { _MyDebugPrint.Show(); } - public static bool IsOpen - { get { return _MyDebugPrint.IsOpen; } } - } + private static readonly DebugPrint _MyDebugPrint = new DebugPrint(); + public static void Open(string fileName) => _MyDebugPrint.Open(fileName); + public static void Close() => _MyDebugPrint.Close(); + public static void Write(string format, params object[] args) => _MyDebugPrint.Write(format, args); + public static void WriteLine(string format, params object[] args) => _MyDebugPrint.WriteLine(format, args); + public static void Show() => _MyDebugPrint.Show(); + public static bool IsOpen => _MyDebugPrint.IsOpen; + } public static class DebugProfile { private static DebugPrint _MyDebugPrint = new DebugPrint(); - public static void Open(string fileName) - { _MyDebugPrint.Open(fileName); } - public static void Close() + public static void Open(string fileName) => _MyDebugPrint.Open(fileName); + public static void Close() { _MyDebugPrint.Close(); _MyDebugPrint = null; } - public static void Write(string format, params object[] args) - { _MyDebugPrint.Write(format, args); } - public static void WriteLine(string format, params object[] args) - { _MyDebugPrint.WriteLine(format, args); } - public static void Show() - { _MyDebugPrint.Show(); } - public static bool IsOpen - { get { return _MyDebugPrint.IsOpen; } } - } + public static void Write(string format, params object[] args) => _MyDebugPrint.Write(format, args); + public static void WriteLine(string format, params object[] args) => _MyDebugPrint.WriteLine(format, args); + public static void Show() => _MyDebugPrint.Show(); + public static bool IsOpen => _MyDebugPrint.IsOpen; + } public static class DebugDBTrack { private static DebugPrint _MyDebugPrint = new DebugPrint(); - public static void Open(string fileName) - { _MyDebugPrint.Open(fileName); } - public static void Close() + public static void Open(string fileName) => _MyDebugPrint.Open(fileName); + public static void Close() { _MyDebugPrint.Close(); _MyDebugPrint = null; } - public static void Write(string format, params object[] args) - { _MyDebugPrint.Write(format, args); } - public static void WriteLine(string format, params object[] args) - { _MyDebugPrint.WriteLine(format, args); } - public static void Show() - { _MyDebugPrint.Show(); } - public static bool IsOpen - { get { return _MyDebugPrint.IsOpen; } } - } + public static void Write(string format, params object[] args) => _MyDebugPrint.Write(format, args); + public static void WriteLine(string format, params object[] args) => _MyDebugPrint.WriteLine(format, args); + public static void Show() => _MyDebugPrint.Show(); + public static bool IsOpen => _MyDebugPrint.IsOpen; + } // C2018-004 create meta file for baseline compares - public static class BaselineMetaFile - { - private static DebugPrint _MyDebugPrint = new DebugPrint(); - private static DebugPrint _MyDebugPrint_Truncated = new DebugPrint(); - public static void Open(string fileName) - { _MyDebugPrint.Open(fileName); - _MyDebugPrint_Truncated.Open(fileName.Replace(".txt", "_Truncated.txt")); - } - public static void Close() - { - _MyDebugPrint.Close(); - _MyDebugPrint_Truncated.Close(); - } - public static void WriteLine(string format, params object[] args) + public static class BaselineMetaFile { + private static readonly DebugPrint _MyDebugPrint = new DebugPrint(); + private static readonly DebugPrint _MyDebugPrint_Truncated = new DebugPrint(); + public static void Open(string fileName) + { + _MyDebugPrint.Open(fileName); + _MyDebugPrint_Truncated.Open(fileName.Replace(".txt", "_Truncated.txt")); + } + public static void Close() + { + _MyDebugPrint.Close(); + _MyDebugPrint_Truncated.Close(); + } + public static void WriteLine(string format, params object[] args) + { _MyDebugPrint_Truncated.WriteLine(format, args); _MyDebugPrint.WriteLine(format, args); - } - public static void WriteLineTruncate(string format, params object[] args) - { - _MyDebugPrint_Truncated.WriteLine(format, args); - - } - public static void WriteLineLegacy(string format, params object[] args) - { - _MyDebugPrint.WriteLine(format, args); - } - public static void Show() - { _MyDebugPrint.Show(); - _MyDebugPrint_Truncated.Show(); - } - public static bool IsOpen - { get { return _MyDebugPrint.IsOpen; } } - private static bool _IncludeWordSecText = true; - public static bool IncludeWordSecText - { - get { return BaselineMetaFile._IncludeWordSecText; } - set { BaselineMetaFile._IncludeWordSecText = value; } } - } + public static void WriteLineTruncate(string format, params object[] args) => _MyDebugPrint_Truncated.WriteLine(format, args); + public static void WriteLineLegacy(string format, params object[] args) => _MyDebugPrint.WriteLine(format, args); + public static void Show() + { + _MyDebugPrint.Show(); + _MyDebugPrint_Truncated.Show(); + } + public static bool IsOpen => _MyDebugPrint.IsOpen; + + public static bool IncludeWordSecText { get; set; } = true; + } } diff --git a/PROMS/Volian.Base.Library/ExeInfo.cs b/PROMS/Volian.Base.Library/ExeInfo.cs index 5d0e6eeb..ad4cd42c 100644 --- a/PROMS/Volian.Base.Library/ExeInfo.cs +++ b/PROMS/Volian.Base.Library/ExeInfo.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.IO; using System.Linq; @@ -10,21 +8,17 @@ namespace Volian.Base.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - public static string GetROEditorPath() - { - string roapp = PROMSExecutableFolderPath() + @"\ROEDITOR.EXE"; - return roapp; - } + #endregion + public static string GetROEditorPath() => $@"{PROMSExecutableFolderPath()}\ROEDITOR.EXE"; - // returns the path to the executable folder - public static string PROMSExecutableFolderPath() + // returns the path to the executable folder + public static string PROMSExecutableFolderPath() { string pathPROMSexe = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); if (pathPROMSexe[7] == ':') // either a local drive or a mapped network drive pathPROMSexe = pathPROMSexe.Substring(6); else - pathPROMSexe = @"\" + pathPROMSexe.Substring(5); // non-mapped network drive - need to add extra back slash in front + pathPROMSexe = $@"\{pathPROMSexe.Substring(5)}"; // non-mapped network drive - need to add extra back slash in front return pathPROMSexe; } @@ -34,7 +28,7 @@ namespace Volian.Base.Library try { // Build the path to the PROMSFixes.sql file located in the PROMS exe folder - string pathPROMSFixes = PROMSExecutableFolderPath() + @"\PROMSFixes.sql"; + string pathPROMSFixes = $@"{PROMSExecutableFolderPath()}\PROMSFixes.sql"; // open the PROMSFixes.sql file and grab the line of text containing the PROMSFixes RevDate // using Linq to open and read the PROMSFixes file diff --git a/PROMS/Volian.Base.Library/FlagEnumEditor.cs b/PROMS/Volian.Base.Library/FlagEnumEditor.cs index 0caf5736..4aef313b 100644 --- a/PROMS/Volian.Base.Library/FlagEnumEditor.cs +++ b/PROMS/Volian.Base.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,6 @@ namespace Volian.Base.Library public class FlagCheckedListBox : CheckedListBox { - private System.ComponentModel.Container components = null; public FlagCheckedListBox() { @@ -21,16 +17,6 @@ namespace Volian.Base.Library InitializeComponent(); } - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (components != null) - components.Dispose(); - } - base.Dispose(disposing); - } - #region Component Designer generated code private void InitializeComponent() { @@ -124,7 +110,7 @@ namespace Volian.Base.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; @@ -207,27 +193,15 @@ namespace Volian.Base.Library caption = c; } - public override string ToString() - { - return caption; - } + public override string ToString() => caption; - // Returns true if the value corresponds to a single bit being set - public bool IsFlag - { - get - { - return ((value & (value - 1)) == 0); - } - } + // Returns true if the value corresponds to a single bit being set + public bool IsFlag => (value & (value - 1)) == 0; - // Returns true if this value is a member of the composite bit value - public bool IsMemberFlag(FlagCheckedListBoxItem composite) - { - return (IsFlag && ((value & composite.value) == value)); - } + // Returns true if this value is a member of the composite bit value + public bool IsMemberFlag(FlagCheckedListBoxItem composite) => IsFlag && ((value & composite.value) == value); - public uint value; + public uint value; public string caption; } @@ -236,13 +210,15 @@ namespace Volian.Base.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) { @@ -266,12 +242,9 @@ namespace Volian.Base.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.Base.Library/FrmPopupStatusMessage.cs b/PROMS/Volian.Base.Library/FrmPopupStatusMessage.cs index 4894102e..0fd70ca0 100644 --- a/PROMS/Volian.Base.Library/FrmPopupStatusMessage.cs +++ b/PROMS/Volian.Base.Library/FrmPopupStatusMessage.cs @@ -1,12 +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; +using System.Windows.Forms; namespace Volian.Base.Library { diff --git a/PROMS/Volian.Base.Library/GenericSerializer.cs b/PROMS/Volian.Base.Library/GenericSerializer.cs index 107b293d..8678da13 100644 --- a/PROMS/Volian.Base.Library/GenericSerializer.cs +++ b/PROMS/Volian.Base.Library/GenericSerializer.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; @@ -17,7 +16,6 @@ namespace Volian.Base.Library using (MemoryStream ms = new MemoryStream()) { xs.Serialize(new NonXsiTextWriter(ms, Encoding.Unicode), t); - //xs.Serialize(ms, t); ms.Position = 0; StreamReader sr = new StreamReader(ms); strOutput = sr.ReadToEnd(); @@ -38,26 +36,6 @@ namespace Volian.Base.Library } return t; } - //public static void WriteFile(T t, string fileName) - //{ - // string strOutput = string.Empty; - // XmlSerializer xs = new XmlSerializer(typeof(T)); - // using (FileStream fs = new FileStream(fileName, FileMode.Create)) - // { - // xs.Serialize(new NonXsiTextWriter(fs, Encoding.UTF8), t); - // fs.Close(); - // } - //} - //public static T ReadFile(string fileName) - //{ - // T t; - // XmlSerializer xs = new XmlSerializer(typeof(T)); - // using (FileStream fs = new FileStream(fileName, FileMode.Open)) - // { - // t = (T)xs.Deserialize(fs); - // } - // return t; - //} } public class NonXsiTextWriter : XmlTextWriter { @@ -79,8 +57,6 @@ namespace Volian.Base.Library } if (localName == "xlink_href") base.WriteStartAttribute(prefix, "xlink:href", ns); - //else if (localName == "encoding") - // _skip = true; else base.WriteStartAttribute(prefix, localName, ns); } diff --git a/PROMS/Volian.Base.Library/GlobalSuppressions.cs b/PROMS/Volian.Base.Library/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/Volian.Base.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.Base.Library/PropGridCollEditor.cs b/PROMS/Volian.Base.Library/PropGridCollEditor.cs index d582b2a4..0f7fe125 100644 --- a/PROMS/Volian.Base.Library/PropGridCollEditor.cs +++ b/PROMS/Volian.Base.Library/PropGridCollEditor.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Text; -using System.ComponentModel; using System.ComponentModel.Design; using System.Windows.Forms; using System.Reflection; @@ -17,10 +13,10 @@ namespace Volian.Base.Library // PropertyValueChanged event args... public delegate void MyPropertyValueChangedEventHandler(object sender, PropertyValueChangedEventArgs e); public static event MyPropertyValueChangedEventHandler MyPropertyValueChanged; - private bool AllowAddDel = false; // flags whether the Add/Delete buttons should be displayed: + private readonly bool AllowAddDel = false; // flags whether the Add/Delete buttons should be displayed: // Inherit the default constructor from the standard // Collection Editor... - private Type _origType; + private readonly Type _origType; public PropGridCollEditor(Type type) : base(type) { @@ -29,11 +25,8 @@ namespace Volian.Base.Library if (type.Name == "ReplaceStrData") AllowAddDel = true; // Defaults to not having the 'Add' & 'Remove' buttons. } - protected override Type CreateCollectionItemType() - { - return base.CreateCollectionItemType(); - } - private Button resetbtn = null; + protected override Type CreateCollectionItemType() => base.CreateCollectionItemType(); + private Button resetbtn = null; // Override this method in order to access the containing user controls // from the default Collection Editor form or to add new ones... protected override CollectionForm CreateCollectionForm() @@ -49,30 +42,31 @@ namespace Volian.Base.Library if (!AllowAddDel) { - // add a reset button and put next to ok button: - resetbtn = new Button(); - resetbtn.Text = "Reset"; - resetbtn.Location = new System.Drawing.Point(okbtn.Location.X - 20, okbtn.Location.Y); - resetbtn.Width = 250; - resetbtn.Visible = true; - resetbtn.Enabled = false; // only enabled on data change - resetbtn.Click += resetbtn_Click; + // add a reset button and put next to ok button: + resetbtn = new Button + { + Text = "Reset", + Location = new System.Drawing.Point(okbtn.Location.X - 20, okbtn.Location.Y), + Width = 250, + Visible = true, + Enabled = false // only enabled on data change + }; + resetbtn.Click += resetbtn_Click; okbtn.Parent.Controls.Add(resetbtn); } SetMembersLabel(collectionForm); - TableLayoutPanel tlpLayout = frmCollectionEditorForm.Controls[0] as TableLayoutPanel; - if (tlpLayout != null) - { - // Get a reference to the inner PropertyGrid and hook an event handler to it. - if (tlpLayout.Controls[5] is PropertyGrid) - { - propertyGrid = tlpLayout.Controls[5] as PropertyGrid; - propertyGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(propertyGrid_PropertyValueChanged); - propertyGrid.SelectedGridItemChanged += PG_SelectedGridItemChanged; - } - } + if (frmCollectionEditorForm.Controls[0] is TableLayoutPanel tlpLayout) + { + // Get a reference to the inner PropertyGrid and hook an event handler to it. + if (tlpLayout.Controls[5] is PropertyGrid) + { + propertyGrid = tlpLayout.Controls[5] as PropertyGrid; + propertyGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(propertyGrid_PropertyValueChanged); + propertyGrid.SelectedGridItemChanged += PG_SelectedGridItemChanged; + } + } - return collectionForm; + return collectionForm; } // when the reset button is clicked the data will be reset to the data from the original format file. Note that if @@ -93,28 +87,15 @@ namespace Volian.Base.Library else if (SelectedGridField.Contains("Active CheckOff")) ResetValue(propertyGrid.SelectedGridItem.Parent.Parent.Value, "Active"); } - private void ShowReflection(Object data) - { - if (data == null) return; - //Object data = new A(); - FieldInfo[] fields = data.GetType().GetFields(BindingFlags.Public | - BindingFlags.NonPublic | - BindingFlags.Instance); - String str = ""; - foreach (FieldInfo f in fields) - { - str += f.Name + " = " + f.GetValue(data) + "\r\n"; - } - Console.WriteLine("reflection = {0}", str); - } - PropertyGrid propertyGrid = null; + + PropertyGrid propertyGrid = null; private string SelectedGridField = ""; // The following method is used to enable and set text on the 'Reset' button. When a grid item is selected, if it has // UCF data, then put the original value as part of the button text & enable it: void PG_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e) { if (resetbtn == null) return; - if (propertyGrid != null) Console.WriteLine(LabelPath(propertyGrid.SelectedGridItem)); // PG.SelectedGridItem.Label + " : " + PG.SelectedGridItem.Value; + if (propertyGrid != null) Console.WriteLine(LabelPath(propertyGrid.SelectedGridItem)); // see if data has changed, and if so, enable the Reset button. bool enabled = false; resetbtn.Text = "Reset"; @@ -124,7 +105,7 @@ namespace Volian.Base.Library string origForButton = OrigValue(propertyGrid.SelectedGridItem.Parent.Value, "WindowsFont"); if (origForButton != null) { - resetbtn.Text = "Reset to " + origForButton; + resetbtn.Text = $"Reset to {origForButton}"; enabled = true; } } @@ -133,7 +114,7 @@ namespace Volian.Base.Library string origForButton = OrigValue(propertyGrid.SelectedGridItem.Parent.Value, "LeftMargin"); if (origForButton != null) { - resetbtn.Text = "Reset to " + origForButton; + resetbtn.Text = $"Reset to {origForButton}"; enabled = true; } } @@ -142,7 +123,7 @@ namespace Volian.Base.Library string origForButton = OrigValue(propertyGrid.SelectedGridItem.Parent.Value, "PageLength"); if (origForButton != null) { - resetbtn.Text = "Reset to " + origForButton; + resetbtn.Text = $"Reset to {origForButton}"; enabled = true; } } @@ -151,7 +132,7 @@ namespace Volian.Base.Library string origForButton = OrigValue(propertyGrid.SelectedGridItem.Parent.Parent.Value, "Active"); if (origForButton != null) { - resetbtn.Text = "Reset to " + origForButton; + resetbtn.Text = $"Reset to {origForButton}"; enabled = true; } } @@ -160,7 +141,7 @@ namespace Volian.Base.Library string origForButton = OrigValue(propertyGrid.SelectedGridItem.Parent.Parent.Value, "Active"); if (origForButton != null) { - resetbtn.Text = "Reset to " + origForButton; + resetbtn.Text = $"Reset to {origForButton}"; enabled = true; } } @@ -182,8 +163,8 @@ namespace Volian.Base.Library // field to compare the 2 to see if a change was made, i.e. UCF data exists. foreach (FieldInfo f in fields) { - if (f.Name == "_" + fieldName) fldVal = f; - if (f.Name == "_Orig" + fieldName) fldOrig = f; + if (f.Name == $"_{fieldName}") fldVal = f; + if (f.Name == $"_Orig{fieldName}") fldOrig = f; } if (fldVal != null && fldOrig != null) { @@ -200,8 +181,8 @@ namespace Volian.Base.Library if (orig != newv) return retval; else return null; } - catch (Exception ex) - { + catch (Exception) + { return null; } } @@ -218,8 +199,8 @@ namespace Volian.Base.Library BindingFlags.Instance); foreach (FieldInfo f in fields) { - if (f.Name == "_" + fieldName) fldVal = f; - if (f.Name == "_Orig" + fieldName) fldOrig = f; + if (f.Name == $"_{fieldName}") fldVal = f; + if (f.Name == $"_Orig{fieldName}") fldOrig = f; } if (fldVal != null && fldOrig != null) { @@ -227,14 +208,11 @@ namespace Volian.Base.Library propertyGrid.Refresh(); } } - // Remove this on release, and any uses of it. - private string LabelPath(GridItem gi) - { - return (gi.Parent == null ? "" : LabelPath(gi.Parent) + ":" + gi.Label); - } + // Remove this on release, and any uses of it. + private string LabelPath(GridItem gi) => gi.Parent == null ? "" : $"{LabelPath(gi.Parent)}:{gi.Label}"; - // set the 'members' label to better reflect what is displayed: - private bool SetMembersLabel(Control myControl) + // set the 'members' label to better reflect what is displayed: + private bool SetMembersLabel(Control myControl) { if (myControl is Label && myControl.Text.ToUpper().Contains("MEMBER")) { @@ -291,11 +269,8 @@ namespace Volian.Base.Library void propertyGrid_PropertyValueChanged(object sender, PropertyValueChangedEventArgs e) { - // Fire our customized collection event... - if (PropGridCollEditor.MyPropertyValueChanged != null) - { - PropGridCollEditor.MyPropertyValueChanged(this, e); - } - } + // Fire our customized collection event... + PropGridCollEditor.MyPropertyValueChanged?.Invoke(this, e); + } } } diff --git a/PROMS/Volian.Base.Library/RTBAPI.cs b/PROMS/Volian.Base.Library/RTBAPI.cs index c88aecf9..3efccb5e 100644 --- a/PROMS/Volian.Base.Library/RTBAPI.cs +++ b/PROMS/Volian.Base.Library/RTBAPI.cs @@ -1,11 +1,8 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Windows.Forms; using System.Drawing; using System.Runtime.InteropServices; using System.ComponentModel; -using Volian.Base.Library; namespace Volian.Base.Library { @@ -451,11 +448,6 @@ namespace Volian.Base.Library } #endregion #region Structures - //struct CharRange - //{ - // public int cpMin; - // public int cpMax; - //} [StructLayout(LayoutKind.Sequential, Pack = 4, CharSet = CharSet.Auto)] public struct CharFormat2 { @@ -483,17 +475,11 @@ namespace Volian.Base.Library } public class CharFormatTwo { - public CharFormatTwo(CharFormat2 cf) - { - _CharFormat2 = cf; - } - private CharFormat2 _CharFormat2; - [Browsable(false)] - public CharFormat2 CharFormat2 - { - get { return _CharFormat2; } - } - [Browsable(false)] + public CharFormatTwo(CharFormat2 cf) => _CharFormat2 = cf; + private CharFormat2 _CharFormat2; + [Browsable(false)] + public CharFormat2 CharFormat2 => _CharFormat2; + [Browsable(false)] public int cbSize { get { return _CharFormat2.cbSize; } @@ -521,15 +507,9 @@ namespace Volian.Base.Library get { return _CharFormat2.yOffset; } set { _CharFormat2.yOffset = value; } } - private Color Int2Color(int color) - { - return Color.FromArgb(color % 256, (color / 256) % 256, color / (256 * 256)); - } - private int Color2Int(Color color) - { - return color.R + (color.G * 256) + (color.B * 256 * 256); - } - public Color crTextColor + private Color Int2Color(int color) => Color.FromArgb(color % 256, (color / 256) % 256, color / (256 * 256)); + private int Color2Int(Color color) => color.R + (color.G * 256) + (color.B * 256 * 256); + public Color crTextColor { get { return Int2Color(_CharFormat2.crTextColor); } set { _CharFormat2.crTextColor = Color2Int(value); } @@ -637,15 +617,9 @@ namespace Volian.Base.Library public class ParaFormatTwo { private ParaFormat2 _ParaFormat2; - public ParaFormatTwo(ParaFormat2 pf) - { - _ParaFormat2 = pf; - } - public ParaFormat2 ParaFormat2 - { - get { return _ParaFormat2; } - } - public int cbSize + public ParaFormatTwo(ParaFormat2 pf) => _ParaFormat2 = pf; + public ParaFormat2 ParaFormat2 => _ParaFormat2; + public int cbSize { get { return _ParaFormat2.cbSize; } set { _ParaFormat2.cbSize = value; } @@ -767,19 +741,11 @@ namespace Volian.Base.Library set { _ParaFormat2.wBorders = value; } } } - #endregion - #region Static Methods - public static bool HasVertScroll(Control ctl) - { - int dwstyle = GetWindowLong(ctl.Handle, GWL_STYLE); - return (dwstyle & WS_VSCROLL) != 0; - } - public static bool HasHorzScroll(Control ctl) - { - int dwstyle = GetWindowLong(ctl.Handle, GWL_STYLE); - return (dwstyle & WS_HSCROLL) != 0; - } - public static void SetScrollLocation(RichTextBox richTextBox, Point point) + #endregion + #region Static Methods + public static bool HasVertScroll(Control ctl) => (GetWindowLong(ctl.Handle, GWL_STYLE) & WS_VSCROLL) != 0; + public static bool HasHorzScroll(Control ctl) => (GetWindowLong(ctl.Handle, GWL_STYLE) & WS_HSCROLL) != 0; + public static void SetScrollLocation(RichTextBox richTextBox, Point point) { if (SendMessage(new HandleRef(richTextBox, richTextBox.Handle), Messages.EM_SETSCROLLPOS, 0, ref point) == 0) throw new Win32Exception(); @@ -815,7 +781,6 @@ namespace Volian.Base.Library ParaFormat2 pf2 = pft.ParaFormat2; if (SendMessage(new HandleRef(richTextBox, richTextBox.Handle), Messages.EM_SETPARAFORMAT, 0, ref pf2) == 0) { - //if(Marshal.GetLastWin32Error()!=0) throw new Win32Exception(); } } @@ -849,15 +814,6 @@ namespace Volian.Base.Library } } - public static void SetHighlightColor(RichTextBox richTextBox, RTBSelection selection, Color color) - { - CharFormatTwo cft = GetCharFormat(richTextBox, selection); - cft.crBackColor = color; - cft.dwEffects = 0; - cft.dwMask = 0; - cft.dwMask |= CharFormatMasks.CFM_BACKCOLOR; - SetCharFormat(richTextBox, selection, cft); - } public static void SetSpaceBefore(RichTextBox richTextBox, int spaceBefore) { ParaFormatTwo pft = GetParaFormat(richTextBox); @@ -875,236 +831,6 @@ namespace Volian.Base.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); - pft.bLineSpacingRule = type; - pft.dwMask = 0; - pft.dwMask |= ParaFormatMasks.PFM_LINESPACING; - 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.dyLineSpacing = Convert.ToInt32(.5 + richTextBox.Font.GetHeight(dpi)) * 1440 / dpi; - SetParaFormat(richTextBox, pft); - } - public static E_FontStyle GetFontStyle(RichTextBox richTextBox) - { - E_FontStyle fs = E_FontStyle.FS_NONE; - CharFormatTwo cft = GetCharFormat(richTextBox, RTBSelection.SCF_SELECTION); - if (((cft.dwMask & CharFormatMasks.CFM_BOLD) == CharFormatMasks.CFM_BOLD) && - ((cft.dwEffects & CharFormatEffects.CFE_BOLD) == CharFormatEffects.CFE_BOLD)) fs |= E_FontStyle.FS_BOLD; - if (((cft.dwMask & CharFormatMasks.CFM_UNDERLINE) == CharFormatMasks.CFM_UNDERLINE) && - ((cft.dwEffects & CharFormatEffects.CFE_UNDERLINE) == CharFormatEffects.CFE_UNDERLINE)) fs |= E_FontStyle.FS_UNDERLINE; - if (((cft.dwMask & CharFormatMasks.CFM_ITALIC) == CharFormatMasks.CFM_ITALIC) && - ((cft.dwEffects & CharFormatEffects.CFE_ITALIC) == CharFormatEffects.CFE_ITALIC)) fs |= E_FontStyle.FS_ITALIC; - if (richTextBox.SelectionCharOffset == -2) fs |= E_FontStyle.FS_SUBSCRIPT; - if (richTextBox.SelectionCharOffset == 2) fs |= E_FontStyle.FS_SUPERSCRIPT; - return fs; - } - public static void SetFontStyle(RichTextBox richTextBox, E_FontStyle fs) - { - CharFormatTwo cft = GetCharFormat(richTextBox, RTBSelection.SCF_SELECTION); - if ((fs & E_FontStyle.FS_BOLD) == E_FontStyle.FS_BOLD) - { - cft.dwEffects |= CharFormatEffects.CFE_BOLD; - cft.dwMask |= CharFormatMasks.CFM_BOLD; - } - if ((fs & E_FontStyle.FS_UNDERLINE) == E_FontStyle.FS_UNDERLINE) - { - cft.dwEffects |= CharFormatEffects.CFE_UNDERLINE; - cft.dwMask |= CharFormatMasks.CFM_UNDERLINE; - } - if ((fs & E_FontStyle.FS_ITALIC) == E_FontStyle.FS_ITALIC) - { - cft.dwEffects |= CharFormatEffects.CFE_ITALIC; - cft.dwMask |= CharFormatMasks.CFM_ITALIC; - } - if ((fs & E_FontStyle.FS_SUBSCRIPT) == E_FontStyle.FS_SUBSCRIPT) - { - richTextBox.SelectionCharOffset = -2; - } - if ((fs & E_FontStyle.FS_SUPERSCRIPT) == E_FontStyle.FS_SUPERSCRIPT) - { - richTextBox.SelectionCharOffset = 2; - } - 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) - { - if (bSet) - richTextBox.SelectionCharOffset = -2; - else - richTextBox.SelectionCharOffset = 0; - } - public static void ToggleSuperscript(bool bSet, RichTextBox richTextBox, RTBSelection selection) - { - if (bSet) - richTextBox.SelectionCharOffset = 2; - else - richTextBox.SelectionCharOffset = 0; - } - public static bool IsBold(RichTextBox richTextBox) - { - CharFormatTwo cft = GetCharFormat(richTextBox, RTBSelection.SCF_SELECTION); - return (((cft.dwMask & CharFormatMasks.CFM_BOLD) == CharFormatMasks.CFM_BOLD) && - ((cft.dwEffects & CharFormatEffects.CFE_BOLD) == CharFormatEffects.CFE_BOLD)); - } - public static void ToggleBold(bool bSet, RichTextBox richTextBox, RTBSelection selection) - { - CharFormatTwo cft = GetCharFormat(richTextBox, selection); - if (bSet) - { - cft.dwEffects = CharFormatEffects.CFE_BOLD; - cft.dwMask = CharFormatMasks.CFM_BOLD; - } - else - { - cft.dwEffects = CharFormatEffects.CFE_NONE; - cft.dwMask = CharFormatMasks.CFM_BOLD; - } - SetCharFormat(richTextBox, selection, cft); - } - public static bool IsUnderline(RichTextBox richTextBox) - { - CharFormatTwo cft = GetCharFormat(richTextBox, RTBSelection.SCF_SELECTION); - return (((cft.dwMask & CharFormatMasks.CFM_UNDERLINE) == CharFormatMasks.CFM_UNDERLINE) && - ((cft.dwEffects & CharFormatEffects.CFE_UNDERLINE) == CharFormatEffects.CFE_UNDERLINE)); - } - public static void ToggleUnderline(bool bSet, RichTextBox richTextBox, RTBSelection selection) - { - CharFormatTwo cft = GetCharFormat(richTextBox, selection); - if (bSet) - { - cft.dwEffects = CharFormatEffects.CFE_UNDERLINE; - cft.dwMask = CharFormatMasks.CFM_UNDERLINE; - } - else - { - cft.dwEffects = CharFormatEffects.CFE_NONE; - cft.dwMask = CharFormatMasks.CFM_UNDERLINE; - } - SetCharFormat(richTextBox, selection, cft); - } - public static bool IsItalic(RichTextBox richTextBox) - { - CharFormatTwo cft = GetCharFormat(richTextBox, RTBSelection.SCF_SELECTION); - return (((cft.dwMask & CharFormatMasks.CFM_ITALIC) == CharFormatMasks.CFM_ITALIC) && - ((cft.dwEffects & CharFormatEffects.CFE_ITALIC) == CharFormatEffects.CFE_ITALIC)); - } - public static void ToggleItalic(bool bSet, RichTextBox richTextBox, RTBSelection selection) - { - CharFormatTwo cft = GetCharFormat(richTextBox, selection); - if (bSet) - { - cft.dwEffects = CharFormatEffects.CFE_ITALIC; - cft.dwMask = CharFormatMasks.CFM_ITALIC; - } - else - { - cft.dwEffects = CharFormatEffects.CFE_NONE; - cft.dwMask = CharFormatMasks.CFM_ITALIC; - } - 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.Base.Library/RtfTools.cs b/PROMS/Volian.Base.Library/RtfTools.cs index 5a2feeb9..9c2fe30f 100644 --- a/PROMS/Volian.Base.Library/RtfTools.cs +++ b/PROMS/Volian.Base.Library/RtfTools.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Text.RegularExpressions; namespace Volian.Base.Library diff --git a/PROMS/Volian.Base.Library/TmpFile.cs b/PROMS/Volian.Base.Library/TmpFile.cs index 821d75ce..a6e1b997 100644 --- a/PROMS/Volian.Base.Library/TmpFile.cs +++ b/PROMS/Volian.Base.Library/TmpFile.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.IO; using System.Text.RegularExpressions; @@ -8,19 +6,9 @@ namespace Volian.Base.Library { public static class TmpFile { - public static string CreateFileName(string procNumber, string sectNumber, string sectTitle) - { - return FixFileName(procNumber + "_" + ((sectNumber ?? "") != "" ? sectNumber : sectTitle)); - } - public static string CreateFileName(string procNumber) - { - return FixFileName(procNumber); - } - public static string FixFileName(string name) - { - return Regex.Replace(name, "[ .,/]", "_") + ".pdf"; - } - public static void RemoveAllTmps() + public static string CreateFileName(string procNumber) => FixFileName(procNumber); + public static string FixFileName(string name) => $"{Regex.Replace(name, "[ .,/]", "_")}.pdf"; + public static void RemoveAllTmps() { RemoveTmpPDFs(); RemoveTmpDocs(); @@ -41,7 +29,7 @@ namespace Volian.Base.Library if (fi.LastAccessTime.Ticks < (DateTime.Now.Ticks - TimeSpan.TicksPerHour)) fi.Delete(); } - catch (Exception ex) + catch (Exception) { continue; // if an error, go onto next file. } @@ -70,7 +58,7 @@ namespace Volian.Base.Library if(fi.LastWriteTimeUtc < DateTime.Now.AddDays(-2.0)) fi.Delete(); } - catch (Exception ex) + catch (Exception) { continue; // if an error, go onto next file. } @@ -90,7 +78,7 @@ namespace Volian.Base.Library // it may be open from another process. fi.Delete(); } - catch (Exception ex) + catch (Exception) { continue; // if an error, go onto next file. } diff --git a/PROMS/Volian.Base.Library/ValidFileName.cs b/PROMS/Volian.Base.Library/ValidFileName.cs index 62b25e99..d477d3d1 100644 --- a/PROMS/Volian.Base.Library/ValidFileName.cs +++ b/PROMS/Volian.Base.Library/ValidFileName.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Linq; using System.Text; -using System.Threading.Tasks; namespace Volian.Base.Library { diff --git a/PROMS/Volian.Base.Library/VlnItextSharpFont.cs b/PROMS/Volian.Base.Library/VlnItextSharpFont.cs index 9efcb2cb..87cf60c0 100644 --- a/PROMS/Volian.Base.Library/VlnItextSharpFont.cs +++ b/PROMS/Volian.Base.Library/VlnItextSharpFont.cs @@ -1,11 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using iTextSharp.text.factories; using Microsoft.Win32; -using System.Text.RegularExpressions; using System.IO; using iTextSharp.text; @@ -53,7 +47,7 @@ namespace Volian.Base.Library _MyLog.WarnFormat("PROMS Font Folder = {0}", _PromsFontDir); // C2019-028 Add info in the error log } } - int profileDepth1 = ProfileTimer.Push(">>>> RegisterDirectory " + _PromsFontDir); + int profileDepth1 = ProfileTimer.Push($">>>> RegisterDirectory {_PromsFontDir}"); //_MyLog.DebugFormat("Register this Font Folder = {0}", _PromsFontDir); // debug iTextSharp.text.FontFactory.RegisterDirectory(_PromsFontDir); ProfileTimer.Pop(profileDepth1); @@ -70,7 +64,7 @@ namespace Volian.Base.Library _MyLog.WarnFormat("Problem with Font {0} in {1}", fontName, _PromsFontDir); if (_PromsFontDir != FontFind.FontDir) { - int profileDepth2 = ProfileTimer.Push(">>>> RegisterDirectory " + FontFind.FontDir); + int profileDepth2 = ProfileTimer.Push($">>>> RegisterDirectory {FontFind.FontDir}"); //_MyLog.DebugFormat("Register this Font Folder = {0}", FontFind.FontDir); // debug iTextSharp.text.FontFactory.RegisterDirectory(FontFind.FontDir); ProfileTimer.Pop(profileDepth2); @@ -109,14 +103,13 @@ namespace Volian.Base.Library } ProfileTimer.Pop(profileDepth); } - private static RegistryKey _FontKey = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows NT").OpenSubKey("CurrentVersion").OpenSubKey("Fonts"); - public static RegistryKey FontKey - { get { return _FontKey; } } - /// - /// Try to register a particular font, if it fails register the entire font folder - /// - /// FontName - Used to find a font file. - public static void RegisterFont(string fontName) + private static readonly RegistryKey _FontKey = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows NT").OpenSubKey("CurrentVersion").OpenSubKey("Fonts"); + public static RegistryKey FontKey => _FontKey; + /// + /// Try to register a particular font, if it fails register the entire font folder + /// + /// FontName - Used to find a font file. + public static void RegisterFont(string fontName) { if (!FontFactory.IsRegistered(fontName)) { @@ -128,7 +121,7 @@ namespace Volian.Base.Library try // B2019-118 Add error handling for FontFacory.Register (Windows Registry contains a node that // points to a file that no longer exists { - FontFactory.Register(fontFile.Contains("\\") ? fontFile : FontFind.FontDir + "\\" + fontFile); + FontFactory.Register(fontFile.Contains("\\") ? fontFile : $"{FontFind.FontDir}\\{fontFile}"); } catch (Exception ex) // catch any exception and add the error to the error log. { diff --git a/PROMS/Volian.Base.Library/VlnSettings.cs b/PROMS/Volian.Base.Library/VlnSettings.cs index 25d4aeaa..9e7a2352 100644 --- a/PROMS/Volian.Base.Library/VlnSettings.cs +++ b/PROMS/Volian.Base.Library/VlnSettings.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.IO; using System.Configuration; using System.Reflection; @@ -17,25 +15,11 @@ namespace Volian.Base.Library // // For DataLoader, this is set via the Debug checkbox on the form. private static bool WasLoaded = false; - private static bool _DoUpdateRO = true; - public static bool DoUpdateRO - { - get { return VlnSettings._DoUpdateRO; } - set { VlnSettings._DoUpdateRO = value; } - } - private static bool _DebugPagination = false; - public static bool DebugPagination - { - get { return VlnSettings._DebugPagination; } - set { VlnSettings._DebugPagination = value; } - } - private static bool _DebugText = false; - public static bool DebugText - { - get { return VlnSettings._DebugText; } - set { VlnSettings._DebugText = value; } - } - private static bool _DebugMode = false; + + public static bool DoUpdateRO { get; set; } = true; + public static bool DebugPagination { get; set; } = false; + public static bool DebugText { get; set; } = false; + private static bool _DebugMode = false; public static bool DebugMode { get @@ -135,8 +119,7 @@ namespace Volian.Base.Library { if (parameter.ToUpper().StartsWith("/" + commandName.ToUpper() + "=")) { - float result = def; - if (float.TryParse(parameter.Substring(commandName.Length + 2), out result)) + if (float.TryParse(parameter.Substring(commandName.Length + 2), out float result)) return result; else return def; @@ -182,7 +165,7 @@ namespace Volian.Base.Library // This will create a Temp\VE-PROMS folder in the LocalSettings Folder. //XP - C:\Documents and Settings\{user}\Local Settings\Application Data\Temp\VEPROMS //Vista - C:\Users\{user}\AppData\Local\Temp\VEPROMS - _TemporaryFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Temp"; + _TemporaryFolder = $@"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\Temp"; if (!Directory.Exists(TemporaryFolder)) Directory.CreateDirectory(TemporaryFolder); _TemporaryFolder += @"\VEPROMS"; if (!Directory.Exists(TemporaryFolder)) Directory.CreateDirectory(TemporaryFolder); @@ -190,26 +173,11 @@ namespace Volian.Base.Library return _TemporaryFolder; } } - private static string _UserID=Environment.UserName.ToUpper(); - public static string UserID - { - get { return VlnSettings._UserID; } - set { VlnSettings._UserID = value; } - } - private static bool _StepTypeToolTip = false; - public static bool StepTypeToolTip - { - get { return VlnSettings._StepTypeToolTip; } - set { VlnSettings._StepTypeToolTip = value; } - } - // C2029-025 Show or hide replace words. Can highlight replace words in editor. - private static bool _cbShwRplWrdsColor = false; - public static bool cbShwRplWrdsColor - { - get { return VlnSettings._cbShwRplWrdsColor; } - set { VlnSettings._cbShwRplWrdsColor = value; } - } - private static string _ReleaseMode = null; + + public static string UserID { get; set; } = Environment.UserName.ToUpper(); + public static bool StepTypeToolTip { get; set; } = false; + public static bool cbShwRplWrdsColor { get; set; } = false; + private static string _ReleaseMode = null; public static string ReleaseMode { get diff --git a/PROMS/Volian.Base.Library/VlnTimer.cs b/PROMS/Volian.Base.Library/VlnTimer.cs index bfdd5e19..5b840098 100644 --- a/PROMS/Volian.Base.Library/VlnTimer.cs +++ b/PROMS/Volian.Base.Library/VlnTimer.cs @@ -1,26 +1,15 @@ using System; using System.Collections.Generic; -using System.Text; namespace Volian.Base.Library { public class VlnTimer { - private DateTime _LastTime = DateTime.Now; - public DateTime LastTime + public DateTime LastTime { get; set; } = DateTime.Now; + public string LastProcess { get; set; } = "Initialize"; + public string ActiveProcess { - get { return _LastTime; } - set { _LastTime = value; } - } - private string _LastProcess = "Initialize"; - public string LastProcess - { - get { return _LastProcess; } - set { _LastProcess = value; } - } - public string ActiveProcess - { - get { return _LastProcess; } + get { return LastProcess; } set { DateTime tNow = DateTime.Now; @@ -33,13 +22,9 @@ namespace Volian.Base.Library LastProcess = value; } } - Dictionary _ElapsedTimes = new Dictionary(); - public Dictionary ElapsedTimes - { - get { return _ElapsedTimes; } - set { _ElapsedTimes = value; } - } - public void ShowElapsedTimes() + + public Dictionary ElapsedTimes { get; set; } = new Dictionary(); + public void ShowElapsedTimes() { ActiveProcess = "fini"; Console.WriteLine("'Process'\t'Elapsed'"); @@ -54,27 +39,16 @@ namespace Volian.Base.Library } public static class ProfileTimer { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private static Stack _MyStack = new Stack(); +#pragma warning disable S6669 + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); +#pragma warning restore S6669 - public static Stack MyStack - { - get { return _MyStack; } - set { _MyStack = value; } - } - private static DateTime _StartTime = DateTime.Now; - public static DateTime StartTime - { - get { return _StartTime; } - set { _StartTime = value; } - } - delegate int DoPushTrack(string start); + public static Stack MyStack { get; set; } = new Stack(); + public static DateTime StartTime { get; set; } = DateTime.Now; + delegate int DoPushTrack(string start); private static DoPushTrack myDoPush = new DoPushTrack(IgnorePush); - public static int Push(string start) - { - return DoPush(start); - } - private static int DoPush(string start) + public static int Push(string start) => DoPush(start); + private static int DoPush(string start) { MyStack.Push(Start); Start = start; @@ -87,39 +61,23 @@ namespace Volian.Base.Library } delegate int DoPopTrack(int depth); private static DoPopTrack myDoPop = new DoPopTrack(IgnorePop); - public static int Pop(int depth) - { - return DoPop(depth); - } - private static int DoPop(int depth) + public static int Pop(int depth) => DoPop(depth); + private static int DoPop(int depth) { if (MyStack.Count != depth) _MyLog.WarnFormat("Profile Stack Issues\r\n {0}, Depth is {1}, Depth should be {2}", Start,MyStack.Count,depth); Start = MyStack.Pop(); return MyStack.Count; } - private static int IgnorePop(int depth) - { - return 0; - } - public static int Depth - { - get - { - return MyStack.Count; - } - } - private static Dictionary _TimerTable = new Dictionary(); - public static Dictionary TimerTable - { - get { return ProfileTimer._TimerTable; } - set { ProfileTimer._TimerTable = value; } - } - delegate void DoTrack(string module); + private static int IgnorePop(int depth) => 0; + public static int Depth => MyStack.Count; + + public static Dictionary TimerTable { get; set; } = new Dictionary(); + delegate void DoTrack(string module); private static DoTrack myDoTrack = new DoTrack(IgnoreModule); public static void TurnOnTracking(string filename) { - DebugProfile.Open(VlnSettings.TemporaryFolder + "\\" + filename); + DebugProfile.Open($"{VlnSettings.TemporaryFolder}\\{filename}"); myDoTrack = new DoTrack(TrackModule); myDoPush = new DoPushTrack(DoPush); myDoPop = new DoPopTrack(DoPop); @@ -145,13 +103,10 @@ namespace Volian.Base.Library //Console.WriteLine("{0},'{1}'", TimeSpan.FromTicks(dtNext.Ticks - LastTime.Ticks).TotalSeconds, Description); AddTimerInfo(_Start, dtNext.Ticks - LastTime.Ticks); _Start = module; - _LastTime = dtNext; + LastTime = dtNext; } - private static void IgnoreModule(string module) - { - _Start = module; - } - private static void AddTimerInfo(string description, long ticks) + private static void IgnoreModule(string module) => _Start = module; + private static void AddTimerInfo(string description, long ticks) { if (TimerTable.ContainsKey(description)) TimerTable[description] += ticks; @@ -205,16 +160,12 @@ namespace Volian.Base.Library } public static void Reset() { - _TimerTable = new Dictionary(); + TimerTable = new Dictionary(); _Start = "Start"; - _LastTime = DateTime.Now; - _MyStack = new Stack(); + LastTime = DateTime.Now; + MyStack = new Stack(); } - private static DateTime _LastTime = DateTime.Now; - public static DateTime LastTime - { - get { return _LastTime; } - set { _LastTime = value; } - } - } + + public static DateTime LastTime { get; set; } = DateTime.Now; + } } diff --git a/PROMS/Volian.Base.Library/Volian.Base.Library.csproj b/PROMS/Volian.Base.Library/Volian.Base.Library.csproj index 91c1a431..a643b023 100644 --- a/PROMS/Volian.Base.Library/Volian.Base.Library.csproj +++ b/PROMS/Volian.Base.Library/Volian.Base.Library.csproj @@ -105,6 +105,7 @@ FrmPopupStatusMessage.cs + diff --git a/PROMS/Volian.Base.Library/VolianTimer.cs b/PROMS/Volian.Base.Library/VolianTimer.cs index 636aa63c..da5389af 100644 --- a/PROMS/Volian.Base.Library/VolianTimer.cs +++ b/PROMS/Volian.Base.Library/VolianTimer.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace Volian.Base.Library { @@ -12,57 +10,40 @@ namespace Volian.Base.Library /// public class VolianTimer { - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - static List _Timers = new List(); - /// - /// User defined name - should be as specific as possible - /// Include Method Name, File Name and Line Number - /// - private string _Name; - public string Name - { - get { return _Name; } - set { _Name = value; } - } - /// - /// Set on open - /// - private DateTime _Start; - public DateTime Start - { - get { return _Start; } - set { _Start = value; } - } - /// - /// Calculate on Close - /// - private long _Ticks; - public long Ticks - { - get { return _Ticks; } - set { _Ticks = value; } - } - /// - /// Number of times open/close has been run - /// - private int _Count; - public int Count - { - get { return _Count; } - set { _Count = value; } - } - /// - /// Constructor - /// - public VolianTimer() +#pragma warning disable S6669 + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); +#pragma warning restore S6669 + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + static List _Timers = new List(); + + public string Name { get; set; } + public DateTime Start { get; set; } + public long Ticks { get; set; } + public int Count { get; set; } + /// + /// Constructor + /// + public VolianTimer() { Count = 0; Ticks = 0; } - /// - /// Command Line Parameter /Timing turns timing on - /// - private static bool? _TimingsOn = null; + /// + /// Constructor with Module and line number + /// + /// Method Name, File Name + /// Code Line Number + public VolianTimer(string module, int line) + { + Count = 0; + Ticks = 0; + Name = string.Format("{0}:{1}", module, line); + if (TimingsOn) _Timers.Add(this); + } + /// + /// Command Line Parameter /Timing turns timing on + /// + private static bool? _TimingsOn = null; public static bool TimingsOn { get @@ -73,18 +54,6 @@ namespace Volian.Base.Library } } /// - /// Constructor with Module and line number - /// - /// Method Name, File Name - /// Code Line Number - public VolianTimer(string module, int line) - { - Count = 0; - Ticks = 0; - Name = string.Format("{0}:{1}", module, line); - if(TimingsOn) _Timers.Add(this); - } - /// /// Start Timer /// public void Open() diff --git a/PROMS/Volian.Base.Library/vlnFont.cs b/PROMS/Volian.Base.Library/vlnFont.cs index 4c97b6c6..8677ddb6 100644 --- a/PROMS/Volian.Base.Library/vlnFont.cs +++ b/PROMS/Volian.Base.Library/vlnFont.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Drawing; +using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; @@ -11,7 +7,7 @@ namespace Volian.Base.Library public static class vlnFont { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private static InstalledFontCollection _MyFontCollection = new InstalledFontCollection(); + private static readonly InstalledFontCollection _MyFontCollection = new InstalledFontCollection(); private static string _ProportionalSymbolFont = null; // C2017-036 Look for suitable proportional font that will support the symbol characters used in PROMS // Microsoft removed Arial Unicode MS starting with Word16 (office 365 containing that version of Word) diff --git a/PROMS/Volian.Base.Library/vlnStackTrace.cs b/PROMS/Volian.Base.Library/vlnStackTrace.cs index 84ce7a99..bf951d67 100644 --- a/PROMS/Volian.Base.Library/vlnStackTrace.cs +++ b/PROMS/Volian.Base.Library/vlnStackTrace.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; @@ -9,31 +8,9 @@ namespace Volian.Base.Library // This provides a more robust stack trace than what visual studio offers public static class vlnStackTrace { - public static string GetStack(string str, params object[] objects) - { - return string.Format(str, objects) + StackToString(); - } - public static void ShowStack(string str, params object[] objects) - { - Console.WriteLine(string.Format(str, objects) + StackToString()); - } - public static string GetStack() - { - return StackToString(); - } - public static string GetStack(bool showSame) - { - return StackToString(showSame); - } - public static void ShowStack() - { - Console.WriteLine(StackToString()); - } - public static string StackToString() - { - return StackToString(true); - } - private static string StackToString(bool showSame) + public static string GetStack(bool showSame) => StackToString(showSame); + public static string StackToString() => StackToString(true); + private static string StackToString(bool showSame) { StringBuilder sb = new StringBuilder(); StackTrace st = new StackTrace(true); @@ -71,22 +48,6 @@ namespace Volian.Base.Library } return sb.ToString(); } - public static void ShowStackLocal(string str, params object[] objects) - { - Console.WriteLine(string.Format(str, objects) + StackToStringLocal(2,10)); - } - public static void ShowStackFirstLocal(string str) - { - Console.WriteLine(str + "\r\n" + StackToStringLocal(3, 0)); - } - public static void ShowStackLocal(string str,int start) - { - Console.WriteLine(str + "\r\n" + StackToStringLocal(start,1)); - } - public static void ShowStackLocal(int start, int limit, string str, params object[] objects) - { - Console.WriteLine(string.Format(str, objects) + StackToStringLocal(start, limit)); - } public static string StackToStringLocal(int start, int limit) { StringBuilder sb = new StringBuilder(); @@ -118,36 +79,12 @@ namespace Volian.Base.Library return sb.ToString(); return "No Local Method"; } - public static string CalledFrom - { - get - { - StackTrace st = new StackTrace(true); - StackFrame[] sfs = st.GetFrames(); - int count = 0; - foreach (StackFrame sf in sfs) - { - if (sf.GetFileLineNumber() != 0) // Only look at Local Methods - { - count++; - if (count > 4) // The fourth entry should be the Calling Method - { - string sType = sf.GetMethod().ReflectedType.Name; - string sMethod = sf.GetMethod().Name; - return string.Format("{0}.{1}[{2}]", sType, sMethod, sf.GetFileLineNumber()); - } - } - } - return "No Local Method"; - } - } public static string CalledFromCSLA { get { StackTrace st = new StackTrace(true); StackFrame[] sfs = st.GetFrames(); - int count = 0; string lastWasCSLA = null; foreach (StackFrame sf in sfs) { @@ -187,71 +124,5 @@ namespace Volian.Base.Library if (stackFrame1.GetILOffset() != stackFrame2.GetILOffset()) return false; return true; } - public static bool ScrollInStack() - { - StackTrace st = new StackTrace(true); - StackFrame[] sfs = st.GetFrames(); - bool retval = false; - foreach (StackFrame sf in sfs) - { - string sMethod = sf.GetMethod().Name; - string sNamespace = sf.GetMethod().ReflectedType.Namespace; - string sType = sf.GetMethod().ReflectedType.Name; - if (sMethod.ToUpper().Contains("SCROLL") || sType.ToUpper().Contains("SCROLL")) - { - retval = true; - Console.WriteLine("{0}.{1}.{2}", sNamespace, sType, sMethod); - } - } - return retval; - } - /// - /// This will clear the Output window when run in the Development Environment - /// Add EnvDTE and EnvDTE80 to references from .NET - /// - public static void ClearOutputWindow() - { -#if (DEBUG) - try - { - EnvDTE80.DTE2 dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.8.0"); - dte2.ToolWindows.OutputWindow.ActivePane.Clear(); - } - catch (Exception ex) - { - Console.WriteLine("ClearOutputWindow {0} - {1}\r\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace); - } -#endif - } } - public static class HWndCounter - { - [DllImport("kernel32.dll")] - private static extern IntPtr GetCurrentProcess(); - - [DllImport("user32.dll")] - private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags); - - private enum ResourceType - { - Gdi = 0, - User = 1 - } - public static void GetWindowHandlesForCurrentProcess(IntPtr hWnd) - { - GetWindowHandlesForCurrentProcess(hWnd, ""); - } - private static uint lastUserObject = 0; - public static void GetWindowHandlesForCurrentProcess(IntPtr hWnd, string str, params object[] objects) - { - IntPtr processHandle = GetCurrentProcess(); - uint gdiObjects = GetGuiResources(processHandle, (uint)ResourceType.Gdi); - uint userObjects = GetGuiResources(processHandle, (uint)ResourceType.User); - if (lastUserObject != userObjects) - Console.WriteLine("winhandle count = {0} GDIObjs {1} UserObjs {2} dif {3} {4}", gdiObjects + userObjects, gdiObjects, userObjects,(int)userObjects - (int)lastUserObject, string.Format(str, objects)); - lastUserObject = userObjects; - //return Convert.ToInt32(gdiObjects + userObjects); - } - } - } 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 c1c4cf70..73eaa25a 100644 --- a/PROMS/Volian.Controls.Library/DSOTabPanel.cs +++ b/PROMS/Volian.Controls.Library/DSOTabPanel.cs @@ -12,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 @@ -21,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; @@ -38,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 /// @@ -85,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; @@ -112,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 @@ -140,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(); } @@ -175,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(); @@ -190,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 @@ -210,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) { @@ -234,15 +205,9 @@ namespace Volian.Controls.Library System.IO.FileStream fs = MyDSOFile.MyFile.Create(); fs.Write(myDoc.DocContent, 0, myDoc.DocContent.Length); fs.Close(); - MyDSOFile.SaveFile(0, "", _ItemInfo, false, StatusChanged); // B2017-219 save the restored document to database + MyDSOFile.SaveFile("", _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); } } @@ -251,7 +216,7 @@ namespace Volian.Controls.Library { System.IO.FileStream fs = MyDSOFile.MyFile.Create(); fs.Close(); - MyDSOFile.SaveFile(0, "", _ItemInfo, false, StatusChanged); // B2017-219 save the blank document to database + MyDSOFile.SaveFile("", _ItemInfo, false, StatusChanged); // B2017-219 save the blank document to database MessageBox.Show("Reverting to Blank Document", "Error in MS Word section", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this._MyEdWord = null; // B2017-219 Set MyEdWord to null - we will check for this in the calling functions @@ -262,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); @@ -296,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; @@ -309,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("*"); @@ -345,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 /// @@ -410,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; @@ -446,15 +352,12 @@ 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; } } - MyDSOFile.SaveFile(doc.Length, doc.Ascii, MyDisplayTabItem.MyItemInfo, cvtLibDoc, StatusChanged); + MyDSOFile.SaveFile(doc.Ascii, MyDisplayTabItem.MyItemInfo, cvtLibDoc, StatusChanged); if (cvtLibDoc) { MyDisplayTabItem.Text = MyDisplayTabItem.MyItemInfo.TabTitle; @@ -470,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 @@ -489,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) { @@ -509,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) { @@ -538,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); @@ -590,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; @@ -632,15 +509,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; @@ -656,38 +524,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 c4385cab..584c8a83 100644 --- a/PROMS/Volian.Controls.Library/DisplayRO.cs +++ b/PROMS/Volian.Controls.Library/DisplayRO.cs @@ -16,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; @@ -50,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 @@ -285,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(); } @@ -404,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) @@ -512,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(); } } @@ -526,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) { @@ -566,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 @@ -588,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; } } @@ -701,8 +689,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); @@ -771,8 +761,6 @@ namespace Volian.Controls.Library tvROFST.Nodes.Remove(unitInfoNode); } - _curROTypeFilter = _roTypeFilter; - return updatedROs; } @@ -788,11 +776,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; @@ -815,15 +801,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; } @@ -862,8 +846,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); @@ -874,8 +860,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 { @@ -910,7 +898,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); @@ -939,7 +927,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) { @@ -955,7 +943,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; @@ -1007,10 +995,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 { @@ -1018,10 +1005,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 { @@ -1123,12 +1107,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)) { @@ -1137,7 +1118,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 @@ -1151,7 +1132,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; } } @@ -1195,7 +1176,6 @@ namespace Volian.Controls.Library lbFound.DataSource = null; lbFound.Visible = false; - _lastSearchValue = searchValue; } else if (searchValue.Contains("#Link:ReferencedObject")) // RO Link (roid) { @@ -1217,7 +1197,6 @@ namespace Volian.Controls.Library lbFound.DataSource = null; lbFound.Visible = false; - _lastSearchValue = searchValue; } else // if (searchValue != _lastSearchValue) { @@ -1246,12 +1225,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/DisplaySearch.cs b/PROMS/Volian.Controls.Library/DisplaySearch.cs index 3ddbe677..ce360e31 100644 --- a/PROMS/Volian.Controls.Library/DisplaySearch.cs +++ b/PROMS/Volian.Controls.Library/DisplaySearch.cs @@ -15,7 +15,6 @@ using System.Linq; namespace Volian.Controls.Library { -#pragma warning disable IDE1006 // Naming Styles #pragma warning disable IDE0044 // Add readonly modifier public partial class DisplaySearch : UserControl { @@ -339,14 +338,14 @@ namespace Volian.Controls.Library { if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rodbi db) { - return $"{_MyRODbID.ToString()}:{string.Format("{0}", db.dbiID.ToString("X4"))}"; + return $"{_MyRODbID}:{string.Format("{0}", db.dbiID.ToString("X4"))}"; } else if (cmboTreeROs.SelectedNode.Tag is ROFSTLookup.rochild roch) { ROFSTLookup.rochild[] chld = roch.children; // build a list of ROs to search // B2022-118: remove the ending comma otherwise query will fail - string strRtnStr = $"{_MyRODbID.ToString()}:{GetROsToSearch(chld)}"; + string strRtnStr = $"{_MyRODbID}:{GetROsToSearch(chld)}"; if (strRtnStr.EndsWith(",")) strRtnStr = strRtnStr.Substring(0, strRtnStr.Length - 1); return strRtnStr; @@ -1008,7 +1007,7 @@ namespace Volian.Controls.Library { 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()}", + Name = $"btnCM{sym.Unicode}", Tooltip = sym.Desc, Tag = string.Format(@"{0}", sym.Unicode), FontBold = true @@ -2405,6 +2404,7 @@ namespace Volian.Controls.Library } // if the selected folder has a docversion, handle it: +#pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast -- this is by design if (n.Tag != SelectAllProcedureSetsText) { FolderInfo fi = (FolderInfo)n.Tag; @@ -2417,8 +2417,9 @@ namespace Volian.Controls.Library StartAdvTreeStepTypesFillIn();// B2016-258 Hang after selecting a procedure if the Step Type panel is open on the search panel } } +#pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast - SetupContextMenu(); + SetupContextMenu(); buildSetToSearchPanelTitle(); //C2025-005 Find Step Elements @@ -3653,7 +3654,6 @@ namespace Volian.Controls.Library } } } -#pragma warning restore IDE1006 // Naming Styles #pragma warning restore IDE0044 // Add readonly modifier #endregion diff --git a/PROMS/Volian.Controls.Library/DisplayTabControl.cs b/PROMS/Volian.Controls.Library/DisplayTabControl.cs index 9a1c61d2..a3af8bc0 100644 --- a/PROMS/Volian.Controls.Library/DisplayTabControl.cs +++ b/PROMS/Volian.Controls.Library/DisplayTabControl.cs @@ -59,14 +59,8 @@ namespace Volian.Controls.Library // B2026-074 added flag to use when restoring saved procedure tabs public bool LoadingSavedProcTabs { get; set; } = false; - 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 +69,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 +142,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 +154,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 +219,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 +295,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 +401,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 +469,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 +523,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 +539,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 +561,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 +703,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 +715,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 +748,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 +767,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 +779,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 +805,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 +854,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 +871,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 +925,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 +1011,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 +1021,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 +1072,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 +1084,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 +1100,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 +1131,7 @@ namespace Volian.Controls.Library if (stp != null) { EditItem ei = stp.SelectedEditItem; - if (ei != null) - ei.SaveCurrentAndContents(); + ei?.SaveCurrentAndContents(); } } } @@ -1182,41 +1139,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 +1170,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 +1184,6 @@ namespace Volian.Controls.Library pi.EnhancedProcedureRefreshTextDifferences(iil); } } - //} } pg.MyStepTabPanel.MyProcedureItemInfo = proc; @@ -1269,11 +1198,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; @@ -1295,7 +1219,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); @@ -1304,11 +1228,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; } @@ -1316,7 +1235,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); } @@ -1360,7 +1279,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) { @@ -1369,8 +1288,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 @@ -1392,21 +1309,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; } @@ -1423,12 +1340,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 b52a03cd..eb51397e 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) { @@ -3723,29 +3394,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 @@ -3843,7 +3491,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)); @@ -3867,7 +3515,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) @@ -3877,11 +3525,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); @@ -3914,7 +3563,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]; @@ -4008,12 +3657,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; @@ -4022,8 +3666,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); @@ -4047,9 +3689,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; @@ -4057,7 +3701,6 @@ namespace Volian.Controls.Library MyStepData = itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[ContentType % 10000]; break; } - //this.Move += new EventHandler(DisplayItem_Move); } else { @@ -4070,23 +3713,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; @@ -4100,7 +3740,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" && @@ -4127,7 +3768,6 @@ namespace Volian.Controls.Library } } } - //// TIMING: DisplayItem.TimeIt("CSLARTB Parent"); //C2026-021 Expand Functionality of Viewing Mode if (MyStepPanel.ApplDisplayMode > 0) @@ -4143,7 +3783,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); @@ -4157,8 +3796,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; @@ -4166,8 +3803,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"); @@ -4178,7 +3814,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) { @@ -4200,15 +3835,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 @@ -4222,10 +3848,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; @@ -4237,11 +3859,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) { @@ -4251,8 +3868,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 @@ -4265,8 +3880,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..fc8fad32 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 @@ -140,7 +124,7 @@ namespace Volian.Controls.Library } public override void SetActive() { - this.BackColor = MyStepPanel.ActiveColor; + BackColor = MyStepPanel.ActiveColor; } public override void SetText() { @@ -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(); + private readonly DisplayTags _displayTags = new DisplayTags(); #endregion #region Constructors @@ -314,8 +281,8 @@ namespace Volian.Controls.Library MyPictureBox.Width = wd; MyPictureBox.Height = ht; MyPictureBox.SizeMode = PictureBoxSizeMode.Zoom; - this.Width = MyPictureBox.Width + ImageMargin; - this.Height = MyPictureBox.Height + 10; + Width = MyPictureBox.Width + ImageMargin; + Height = MyPictureBox.Height + 10; _newSizeWd = wd / (MyStepPanel.DPI / 72); _newSizeHt = ht / (MyStepPanel.DPI / 72); @@ -343,13 +310,10 @@ namespace Volian.Controls.Library MyPictureBox.Width = wd; MyPictureBox.Height = ht; MyPictureBox.SizeMode = PictureBoxSizeMode.Zoom; // as resize matches width/height. - this.Width = MyPictureBox.Width + ImageMargin; - this.Height = MyPictureBox.Height + 10; - if (_displayTags != null) - { - // Set the Height and Width on the step properties page for the new image - _displayTags.SetNewImageHeightAndWidth(ht, wd); - } + Width = MyPictureBox.Width + ImageMargin; + Height = MyPictureBox.Height + 10; + // Set the Height and Width on the step properties page for the new image + _displayTags?.SetNewImageHeightAndWidth(ht, wd); } @@ -390,12 +354,9 @@ 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; + Width = 100 + ImageMargin; + Height = 100; if (insType == ImageItem.E_ImageSource.File) { ImageFileDialog(); @@ -409,7 +370,7 @@ namespace Volian.Controls.Library MyPictureBox.Image = img; SetWidthsAndHeights(img); string ext = GetImageFormatExtension(img); - FileName = "paste." + ext; + FileName = $"paste.{ext}"; _IsDirty = true; } } @@ -420,21 +381,22 @@ namespace Volian.Controls.Library } } AdjustTableWidthAndLocation(); - this.Controls.Add(this._MyPictureBox); + Controls.Add(_MyPictureBox); AddEventHandlers(); MyStepRTB.RemoveEventHandlers(); MyStepRTB.Visible = false; } private void ImageFileDialog() { - OpenFileDialog openFileDialog1 = new OpenFileDialog(); + OpenFileDialog openFileDialog1 = new OpenFileDialog + { + InitialDirectory = "c:\\", + Filter = "Image files (*.jpg;*.tif;*.bmp;*.png)|*.jpg;*.tif;*.bmp;*.png|All files (*.*)|*.*", + FilterIndex = 0, + RestoreDirectory = true + }; - openFileDialog1.InitialDirectory = "c:\\"; - openFileDialog1.Filter = "Image files (*.jpg;*.tif;*.bmp;*.png)|*.jpg;*.tif;*.bmp;*.png|All files (*.*)|*.*"; - openFileDialog1.FilterIndex = 0; - openFileDialog1.RestoreDirectory = true; - - if (openFileDialog1.ShowDialog() == DialogResult.OK) + if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { @@ -448,61 +410,18 @@ namespace Volian.Controls.Library _IsDirty = true; } } - catch (Exception ex) - { + catch (Exception) + { FlexibleMessageBox.Show("Could not create image, check file type.", "Error on Image File Selection"); return; } } } - //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() + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping img for potential future use")] + 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; @@ -551,13 +470,11 @@ namespace Volian.Controls.Library if (val != null && val != "?") { string imgname = null; - int W = 0; - int H = 0; - string[] vals = val.Split("\n".ToCharArray()); - W = (int)(Int32.Parse(vals[3], System.Globalization.NumberStyles.AllowHexSpecifier) * MyItemInfo.FormatStepData.Font.CharsToTwips); - int lines = Int32.Parse(vals[2], System.Globalization.NumberStyles.AllowHexSpecifier); - H = lines * 12; - try + string[] vals = val.Split("\n".ToCharArray()); + int W = (int)(Int32.Parse(vals[3], System.Globalization.NumberStyles.AllowHexSpecifier) * MyItemInfo.FormatStepData.Font.CharsToTwips); + int lines = Int32.Parse(vals[2], System.Globalization.NumberStyles.AllowHexSpecifier); + int H = lines * 12; + try { imgname = vals[0]; ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); @@ -572,9 +489,9 @@ namespace Volian.Controls.Library AddROImageToScreen(W, H, imageText); } - catch (Exception ex) - { - string msg = string.Format("Could not display image {0}.", imgname); + catch (Exception) + { + string msg = $"Could not display image {imgname}."; FlexibleMessageBox.Show(msg); } } @@ -591,9 +508,8 @@ namespace Volian.Controls.Library ProcedureInfo proc = MyItemInfo.MyProcedure; DocVersionInfo dvi = proc.ActiveParent as DocVersionInfo; ROFstInfo rofst = dvi.DocVersionAssociations[0].MyROFst; - ROImageInfo roImageInfo = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); - if (roImageInfo == null) roImageInfo = rofst.GetROImageByFilename(vals[0], MyItemInfo); - if (roImageInfo != null) + ROImageInfo roImageInfo = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]) ?? rofst.GetROImageByFilename(vals[0], MyItemInfo); + if (roImageInfo != null) { System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); @@ -606,7 +522,7 @@ namespace Volian.Controls.Library // if there is config data that saves the resize of the image, use it, otherwise use what was passed in: StepConfig sc = new StepConfig(MyItemInfo as StepInfo); SizeF sizef = new Size(1, 1); - if (sc.Step_ImageHeight == null || sc.Step_ImageHeight == 0) + if (sc?.Step_ImageHeight == null || sc.Step_ImageHeight == 0) { sizef = new SizeF((img2.Width / img2.HorizontalResolution), (img2.Height / img2.VerticalResolution)); @@ -635,16 +551,16 @@ namespace Volian.Controls.Library { // Always be sure to add the same event handlers to RemoveEventHandlers MyItemInfo.MyContent.Changed += new VEPROMS.CSLA.Library.ContentInfoEvent(MyContent_Changed); - this.Enter += new System.EventHandler(ImageItem_Enter); - this.MyPictureBox.Enter += new System.EventHandler(ImageItem_Enter); - this.Click += new EventHandler(ImageItem_Click); - this.MyPictureBox.Click += new EventHandler(ImageItem_Click); - this.MyPictureBox.PreviewKeyDown += new PreviewKeyDownEventHandler(ImageItem_PreviewKeyDown); //note that PictureBox does not have cursorkey events - this.MyPictureBox.KeyDown += new KeyEventHandler(ImageItem_KeyDown); - this.MyStepRTB.RoInsert += new StepRTBRoEvent(MyStepRTB_RoInsert); - this.MyStepRTB.DoSaveContents += new StepRTBEvent(MyStepRTB_DoSaveContents); // for storing RO data - this.MyPictureBox.Resize += MyPictureBox_Resize; - this.MyPictureBox.MouseDown += MyPictureBox_MouseDown; + Enter += new System.EventHandler(ImageItem_Enter); + MyPictureBox.Enter += new System.EventHandler(ImageItem_Enter); + Click += new EventHandler(ImageItem_Click); + MyPictureBox.Click += new EventHandler(ImageItem_Click); + MyPictureBox.PreviewKeyDown += new PreviewKeyDownEventHandler(ImageItem_PreviewKeyDown); //note that PictureBox does not have cursorkey events + MyPictureBox.KeyDown += new KeyEventHandler(ImageItem_KeyDown); + MyStepRTB.RoInsert += new StepRTBRoEvent(MyStepRTB_RoInsert); + MyStepRTB.DoSaveContents += new StepRTBEvent(MyStepRTB_DoSaveContents); // for storing RO data + MyPictureBox.Resize += MyPictureBox_Resize; + MyPictureBox.MouseDown += MyPictureBox_MouseDown; } void MyPictureBox_MouseDown(object sender, MouseEventArgs e) @@ -654,10 +570,10 @@ namespace Volian.Controls.Library void MyPictureBox_Resize(object sender, EventArgs e) { - if (this.Height != _MyPictureBox.Height + _MyPictureBox.Top + 7) // add in 7 to make it look good // + 10) + if (Height != _MyPictureBox.Height + _MyPictureBox.Top + 7) // add in 7 to make it look good // + 10) { LastMethodsPush(string.Format("MyPictureBox_Resize {0}", _MyPictureBox.Height)); - this.Height = _MyPictureBox.Height + _MyPictureBox.Top + 7; + Height = _MyPictureBox.Height + _MyPictureBox.Top + 7; LastMethodsPop(); } } @@ -665,16 +581,16 @@ namespace Volian.Controls.Library { // Always be sure to add the same event handlers to RemoveEventHandlers MyItemInfo.MyContent.Changed -= new VEPROMS.CSLA.Library.ContentInfoEvent(MyContent_Changed); - this.Enter -= new System.EventHandler(ImageItem_Enter); - this.MyPictureBox.Enter -= new System.EventHandler(ImageItem_Enter); - this.Click -= new EventHandler(ImageItem_Click); - this.MyPictureBox.Click -= new EventHandler(ImageItem_Click); - this.MyPictureBox.PreviewKeyDown -= new PreviewKeyDownEventHandler(ImageItem_PreviewKeyDown); - this.MyPictureBox.KeyDown -= new KeyEventHandler(ImageItem_KeyDown); - this.MyStepRTB.RoInsert -= new StepRTBRoEvent(MyStepRTB_RoInsert); - this.MyStepRTB.DoSaveContents -= new StepRTBEvent(MyStepRTB_DoSaveContents); - this.MyPictureBox.Resize -= MyPictureBox_Resize; - this.MyPictureBox.MouseDown -= MyPictureBox_MouseDown; + Enter -= new System.EventHandler(ImageItem_Enter); + MyPictureBox.Enter -= new System.EventHandler(ImageItem_Enter); + Click -= new EventHandler(ImageItem_Click); + MyPictureBox.Click -= new EventHandler(ImageItem_Click); + MyPictureBox.PreviewKeyDown -= new PreviewKeyDownEventHandler(ImageItem_PreviewKeyDown); + MyPictureBox.KeyDown -= new KeyEventHandler(ImageItem_KeyDown); + MyStepRTB.RoInsert -= new StepRTBRoEvent(MyStepRTB_RoInsert); + MyStepRTB.DoSaveContents -= new StepRTBEvent(MyStepRTB_DoSaveContents); + MyPictureBox.Resize -= MyPictureBox_Resize; + MyPictureBox.MouseDown -= MyPictureBox_MouseDown; } void ImageItem_Click(object sender, EventArgs e) { @@ -750,13 +666,13 @@ 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) { - int sel = MyStepRTB.SelectionStart + args.ValText.Length; - _IsDirty = true; + _ = MyStepRTB.SelectionStart + args.ValText.Length; + _IsDirty = true; InsType = E_ImageSource.RoFigure; MyStepRTB.UpdateStepRtb(args.LinkText, args.ValText); HandleRoImage(); @@ -805,10 +721,12 @@ namespace Volian.Controls.Library bool success = MyStepRTB.OrigDisplayText.Save((RichTextBox)MyStepRTB); if (success && _newSizeHt != 0) { - StepConfig sc = new StepConfig(MyItemInfo as StepInfo); - sc.Step_ImageWidth = (int)(_newSizeWd / (MyStepPanel.DPI / 72f)); - sc.Step_ImageHeight = (int)(_newSizeHt / (MyStepPanel.DPI / 72f)); - using (Item item = MyItemInfo.Get()) + StepConfig sc = new StepConfig(MyItemInfo as StepInfo) + { + Step_ImageWidth = (int)(_newSizeWd / (MyStepPanel.DPI / 72f)), + Step_ImageHeight = (int)(_newSizeHt / (MyStepPanel.DPI / 72f)) + }; + using (Item item = MyItemInfo.Get()) { item.MyContent.Config = sc.ToString(); item.Save(); @@ -841,9 +759,11 @@ namespace Volian.Controls.Library ImageConfig imgCfg = null; if (_pastedNew && compressed) { - imgCfg = new ImageConfig(); - imgCfg.Image_DataSize = origLen; - _MyItem.MyContent.MyImage.Config = imgCfg.ToString(); + imgCfg = new ImageConfig + { + Image_DataSize = origLen + }; + _MyItem.MyContent.MyImage.Config = imgCfg.ToString(); } else if (_newSizeHt != 0) { @@ -880,10 +800,10 @@ namespace Volian.Controls.Library // 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 (MyItemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds - && !this.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.EditorialChange) + && !MyStepPanel.MyStepTabPanel.MyDisplayTabControl.EditorialChange) { if (sc == null) sc = new StepConfig(); - sc.Step_ChangeID = this.MyStepPanel.MyStepTabPanel.MyDisplayTabControl.ChgId; + sc.Step_ChangeID = MyStepPanel.MyStepTabPanel.MyDisplayTabControl.ChgId; } // We saved changes. Reset the change bar override. // IF there is a step config remove the change bar override by setting the CBOverride value to null @@ -893,8 +813,8 @@ namespace Volian.Controls.Library sc.Step_CBOverride = null; // clear the change bar override MyStepRTB.ClearUndo(); } - catch (Exception ex) - { + catch (Exception) + { FlexibleMessageBox.Show("The image could not be saved.", "Image Save", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } @@ -905,8 +825,10 @@ namespace Volian.Controls.Library { // get filename's extension to map to imageformat: string ext = fname.Substring(fname.LastIndexOf(".") + 1).ToUpper(); - System.Drawing.Imaging.ImageFormat ifmt = System.Drawing.Imaging.ImageFormat.Gif; - switch (ext) +#pragma warning disable IDE0059 // Unnecessary assignment of a value + System.Drawing.Imaging.ImageFormat ifmt = System.Drawing.Imaging.ImageFormat.Gif; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + switch (ext) { case ("JPG"): ifmt = System.Drawing.Imaging.ImageFormat.Jpeg; @@ -964,19 +886,21 @@ namespace Volian.Controls.Library { string ext = ImageItem.GetImageFormatExtension(img); - filename = "paste." + ext; + filename = $"paste.{ext}"; } else img = null; } if (img == null) { - OpenFileDialog openFileDialog1 = new OpenFileDialog(); - openFileDialog1.InitialDirectory = "c:\\"; - openFileDialog1.Filter = "Image files (*.jpg;*.tif;*.bmp;*.png)|*.jpg;*.tif;*.bmp;*.png|All files (*.*)|*.*"; - openFileDialog1.FilterIndex = 0; - openFileDialog1.RestoreDirectory = true; - DialogResult dr = openFileDialog1.ShowDialog(); + OpenFileDialog openFileDialog1 = new OpenFileDialog + { + InitialDirectory = "c:\\", + Filter = "Image files (*.jpg;*.tif;*.bmp;*.png)|*.jpg;*.tif;*.bmp;*.png|All files (*.*)|*.*", + FilterIndex = 0, + RestoreDirectory = true + }; + DialogResult dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { // check that it is an image @@ -984,8 +908,8 @@ namespace Volian.Controls.Library { img = System.Drawing.Image.FromFile(openFileDialog1.FileName); } - catch (Exception ex) - { + catch (Exception) + { img = null; } if (img != null) filename = openFileDialog1.FileName; @@ -1019,9 +943,11 @@ namespace Volian.Controls.Library ImageConfig imgCfg = null; if (compressed) { - imgCfg = new ImageConfig(); - imgCfg.Image_DataSize = origLen; - _MyItem.MyContent.MyImage.Config = imgCfg.ToString(); + imgCfg = new ImageConfig + { + Image_DataSize = origLen + }; + _MyItem.MyContent.MyImage.Config = imgCfg.ToString(); } _MyItem.MyContent.MyImage.Data = imgToByte; _MyItem.MyContent.MyImage.FileName = filename; @@ -1036,13 +962,13 @@ namespace Volian.Controls.Library public override void IdentifyMe(bool highlight) { if (highlight) - this.BackColor = Color.Gray; + BackColor = Color.Gray; else { - if (MyPictureBox.Focused || this.Focused) // If active Set BackColor to the active color - this.BackColor = MyStepPanel.ActiveColor; + if (MyPictureBox.Focused || Focused) // If active Set BackColor to the active color + BackColor = MyStepPanel.ActiveColor; else // note that the 'inactive' color is actually MyStepPanel.PanelColor - this.BackColor = MyItemInfo.ItemAnnotationCount == 0 ? MyStepPanel.PanelColor : MyStepPanel.AnnotationColor; + BackColor = MyItemInfo.ItemAnnotationCount == 0 ? MyStepPanel.PanelColor : MyStepPanel.AnnotationColor; } } #endregion 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 cea369ea..f4636025 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)); @@ -3560,16 +3068,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:"); @@ -3579,7 +3084,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]))) @@ -3679,29 +3184,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)) @@ -3716,41 +3210,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 @@ -3761,16 +3240,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 @@ -3788,87 +3263,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; } @@ -3878,42 +3299,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..d57d3a8f 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 @@ -19,15 +16,20 @@ namespace Volian.Controls.Library private EPFields myEPFields; private AnnotationConfig MyConfig; - private StepTabRibbon _MyStepTabRibbon; - private Dictionary _DicTB; - private Dictionary _DicCheckBox; - private Dictionary _DicComboBox; - private Dictionary _DicSingleRO; - private Dictionary _DicMultiRO; + private readonly StepTabRibbon _MyStepTabRibbon; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicTB; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicCheckBox; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicComboBox; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicSingleRO; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private Dictionary _DicMultiRO; private TablePropertiesControl _TablePropControl; - private string multiseparator = ","; + private readonly string multiseparator = ","; public frmEPAnnotationDetails(AnnotationInfo currAnn) { @@ -61,13 +63,15 @@ namespace Volian.Controls.Library if (EP.type.ToLower() != "tableinput") { - Label wlbl = new Label(); - wlbl.Text = EP.label; - wlbl.Visible = true; - wlbl.TextAlign = ContentAlignment.MiddleLeft; - wlbl.Anchor = AnchorStyles.Left | AnchorStyles.Top; - wlbl.Width = (8 * MaxCharsInLabel) + 5; - panelEP.Controls.Add(wlbl, 0, panelEP.RowCount - 1); + Label wlbl = new Label + { + Text = EP.label, + Visible = true, + TextAlign = ContentAlignment.MiddleLeft, + Anchor = AnchorStyles.Left | AnchorStyles.Top, + Width = (8 * MaxCharsInLabel) + 5 + }; + panelEP.Controls.Add(wlbl, 0, panelEP.RowCount - 1); } if (EP.type.ToLower() == "text") @@ -102,9 +106,11 @@ namespace Volian.Controls.Library } if (EP.type.ToLower() == "logical") { - CheckBox cb = new CheckBox(); - cb.Text = EP.text; - cb.Visible = true; + CheckBox cb = new CheckBox + { + Text = EP.text, + Visible = true + }; string val = MyConfig.GetValue("EP", EP.name); cb.Checked = val != null && val != "" && val.ToUpper()[0] == 'Y'; _DicCheckBox.Add(EP.name, cb); @@ -113,8 +119,10 @@ namespace Volian.Controls.Library } if (EP.type.ToLower() == "combo") { - ComboBox cmb = new ComboBox(); - cmb.Visible = true; + ComboBox cmb = new ComboBox + { + Visible = true + }; string tmp = EP.text; string[] tmps = tmp.Split(",".ToCharArray()); foreach (string t in tmps) cmb.Items.Add(t.Trim()); @@ -127,10 +135,12 @@ namespace Volian.Controls.Library } if (EP.type.ToLower() == "rosingle") { - ComboBox cmb = new ComboBox(); - cmb.Visible = true; + ComboBox cmb = new ComboBox + { + Visible = true + }; - List tmps = EP.getROList(currAnn, true); + List tmps = EP.getROList(currAnn, true); cmb.DisplayMember = "Text"; cmb.ValueMember = "Value"; cmb.DataSource = tmps; @@ -159,9 +169,11 @@ namespace Volian.Controls.Library if (EP.type.ToLower() == "tableinput" && _TablePropControl == null) { string val = MyConfig.GetValue("EP", EP.name); - _TablePropControl = new TablePropertiesControl(EP.name, EP.label, val); - _TablePropControl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; - panelEP.Controls.Add(_TablePropControl, 1, panelEP.RowCount - 1); + _TablePropControl = new TablePropertiesControl(EP.name, EP.label, val) + { + Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top + }; + panelEP.Controls.Add(_TablePropControl, 1, panelEP.RowCount - 1); } 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..abd47b56 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; @@ -15,7 +13,6 @@ namespace Volian.Controls.Library public partial class frmImportWordContents : Form { LBApplicationClass _WordApp; - bool _initializing = false; private StepRTB _MyStepRTB = null; public StepRTB MyStepRTB @@ -25,12 +22,10 @@ namespace Volian.Controls.Library } public frmImportWordContents() { - _initializing = true; InitializeComponent(); // C2019-021 Allow the Number field to be edited. txbWordFile.Text = Properties.Settings.Default.ImportWordFilePath; disableButtons(); - _initializing = false; // B2019-108 Enable/disable buttons btnOpen.Enabled = File.Exists(txbWordFile.Text) && _WordApp == null; } @@ -46,14 +41,9 @@ namespace Volian.Controls.Library btnInsertNext.Enabled = false; btnReplaceNext.Enabled = false; } - private void ofd_FileOk(object sender, CancelEventArgs e) - { - _initializing = true; - txbWordFile.Text = ofd.FileName; - _initializing = false; - } + private void ofd_FileOk(object sender, CancelEventArgs e) => txbWordFile.Text = ofd.FileName; - private void btnBrowse_Click(object sender, EventArgs e) + private void btnBrowse_Click(object sender, EventArgs e) { // if we have a word doc open, then close it and reset WordApp if (_WordApp != null) @@ -109,7 +99,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 @@ -257,8 +246,8 @@ namespace Volian.Controls.Library } return retval.ToString(); } - catch (Exception ex) - { + catch (Exception) + { return "12"; } } @@ -284,8 +273,7 @@ namespace Volian.Controls.Library { try { - if (_WordApp != null) - _WordApp.Quit(); + _WordApp?.Quit(); // B2019-108 Reset WordApp when closed. _WordApp = null; } @@ -294,34 +282,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,17 +342,15 @@ namespace Volian.Controls.Library if (MyStepRTB.Parent is VlnFlexGrid) { VlnFlexGrid vg = MyStepRTB.Parent as VlnFlexGrid; - //vg.FinishEditing(false); vg.SelectNextCell(); } else { - EditItem ei = MyStepRTB.Parent as EditItem; - if (ei != null) - { - ei.AddSiblingAfter(); - } - } + if (MyStepRTB.Parent is EditItem ei) + { + ei.AddSiblingAfter(); + } + } } } @@ -412,10 +370,7 @@ namespace Volian.Controls.Library ei = ei.MyParentEditItem; else ei = ei.MyPreviousEditItem; - if (ei != null) - { - ei.AddSiblingAfter(); - } + ei?.AddSiblingAfter(); } } // C201-021 New Function Add a new High level step @@ -434,10 +389,7 @@ namespace Volian.Controls.Library ei = ei.MyParentEditItem; else ei = ei.MyPreviousEditItem; - if (ei != null) - { - ei.AddSiblingAfter(); - } + ei?.AddSiblingAfter(); } } private EditItem GetEditItem(Control Ctrl) @@ -498,9 +450,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 +463,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 +470,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 +498,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 +509,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 +536,10 @@ 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,15 +554,9 @@ 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(); + ei?.SetAllTabs(); } } @@ -671,7 +586,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; @@ -693,7 +607,7 @@ namespace Volian.Controls.Library int TableWidth = 0; for (iC = 0; iC < tbl.Columns.Count; iC++) { - TableWidth = TableWidth + Wcol[iC]; + TableWidth += Wcol[iC]; } tend = DateTime.Now; Console.WriteLine("{0} before Rollup columns", TimeSpan.FromTicks(tend.Ticks - tstart.Ticks).TotalMilliseconds); tstart = tend; // roll up columns @@ -718,7 +632,7 @@ namespace Volian.Controls.Library Wcell[iR, i] = Wcell[iR, i - 1]; Wcell[iR, i - 1] = 0; } - tmp = tmp - Wcol[iC + SpanC[iR, iC]]; + tmp -= Wcol[iC + SpanC[iR, iC]]; SpanC[iR, iC]++; } iC = iC + SpanC[iR, iC] - 1; @@ -774,16 +688,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 +729,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 +744,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 +762,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..f2e32407 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; @@ -17,7 +13,7 @@ namespace Volian.Controls.Library { public partial class frmSendErrorLog : Form { - private string _ErrorLogPath; + private readonly string _ErrorLogPath; public bool OutlookEmail { get { return rbOutlook.Checked; } @@ -79,19 +75,21 @@ namespace Volian.Controls.Library FileStream fs = null; try { - 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; + MailMessage mm = new MailMessage + { + From = new MailAddress(SMTPUser) + }; + mm.To.Add("support@volian.com"); + mm.Subject = $"PROMS Error Log {DateTime.Now: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); - sc.EnableSsl = true; - sc.Credentials = new NetworkCredential(SMTPUser, tbPassword.Text); - sc.Send(mm); + SmtpClient sc = new SmtpClient(SMTPServer) + { + EnableSsl = true, + Credentials = new NetworkCredential(SMTPUser, tbPassword.Text) + }; + sc.Send(mm); return true; } catch (Exception ex) @@ -109,7 +107,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 +115,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 +133,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: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 +154,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..c8b4a78e 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; @@ -11,13 +6,8 @@ namespace Volian.Controls.Library { public partial class frmViewTextFile : DevComponents.DotNetBar.Office2007Form //Form { - string _FileName; - RichTextBoxStreamType _RTBType; - //public string FileName - //{ - // get { return _FileName; } - // set { _FileName = value; } - //} + readonly string _FileName; + readonly RichTextBoxStreamType _RTBType; 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); diff --git a/PROMS/Volian.Pipe.Library/PipeClient.cs b/PROMS/Volian.Pipe.Library/PipeClient.cs index 502badb0..b4e31394 100644 --- a/PROMS/Volian.Pipe.Library/PipeClient.cs +++ b/PROMS/Volian.Pipe.Library/PipeClient.cs @@ -3,31 +3,19 @@ * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE *********************************************************************************************/ using System; -using System.Collections.Generic; using System.IO.Pipes; -//using System.Linq; using System.Text; -//using System.Threading.Tasks; namespace Volian.Pipe.Library { public class PipeClient { - private string _Name; - public string Name + public string Name { get; set; } + + public int TimeOut { get; set; } = 1000; + public PipeClient(string name) { - get { return _Name; } - set { _Name = value; } - } - private int _TimeOut = 1000; - public int TimeOut - { - get { return _TimeOut; } - set { _TimeOut = value; } - } - public PipeClient(string name) - { - _Name = name; + Name = name; } public void Send(string msg) { diff --git a/PROMS/Volian.Pipe.Library/PipeServer.cs b/PROMS/Volian.Pipe.Library/PipeServer.cs index 197d7a9d..15d3a63d 100644 --- a/PROMS/Volian.Pipe.Library/PipeServer.cs +++ b/PROMS/Volian.Pipe.Library/PipeServer.cs @@ -3,11 +3,8 @@ * Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE *********************************************************************************************/ using System; -using System.Collections.Generic; using System.IO.Pipes; -using System.Linq; using System.Text; -//using System.Threading.Tasks; namespace Volian.Pipe.Library { @@ -15,18 +12,12 @@ namespace Volian.Pipe.Library public delegate void DelegateMessage(string Reply); public class PipeServer { - private string _Name; - public string Name + public string Name { get; set; } + public PipeServer(string name) { - get { return _Name; } - set { _Name = value; } - } - public PipeServer(string name) - { - _Name = name; + Name = name; } public event DelegateMessage PipeMessage; - string _pipeName; public void Listen() { try @@ -66,9 +57,7 @@ namespace Volian.Pipe.Library // Kill original sever and create new wait server pipeServer.Close(); pipeServer = null; - //pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); - //// Recursively wait for the connection again and again.... - //pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); + // Recursively wait for the connection again and again.... Listen(); } catch diff --git a/PROMS/Volian.Print.Library/CPSGen.cs b/PROMS/Volian.Print.Library/CPSGen.cs index 3aa6491c..b0d12e3c 100644 --- a/PROMS/Volian.Print.Library/CPSGen.cs +++ b/PROMS/Volian.Print.Library/CPSGen.cs @@ -1,22 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml; +using System.Xml; using VEPROMS.CSLA.Library; namespace Volian.Print.Library { public class CPSGen { - private vlnParagraph _MyVlnParagraph; - public vlnParagraph MyVlnParagraph + public vlnParagraph MyVlnParagraph { get; set; } + public CPSGen(vlnParagraph myParagraph) { - get { return _MyVlnParagraph; } - set { _MyVlnParagraph = value; } - } - public CPSGen(vlnParagraph myParagraph) - { - _MyVlnParagraph = myParagraph; + MyVlnParagraph = myParagraph; } public void Generate(string fileName) { @@ -33,7 +25,6 @@ namespace Volian.Print.Library AddAttribute(xe, "FromType", fromType); AddAttribute(xe, "Ordinal", itm.Ordinal); AddAttribute(xe, "ParentID", (itm.ActiveParent as ItemInfo).ItemID); - //AddAttribute(xe, "Xoffset", para.XOffset); AddAttribute(xe, "ItemID", itm.ItemID); AddAttribute(xe, "PreviousID", itm.PreviousID); AddAttribute(xe, "ContentID", itm.ContentID); @@ -45,41 +36,20 @@ namespace Volian.Print.Library AddAttribute(xe, "FormatID", itm.MyContent.FormatID); AddAttribute(xe, "Config", itm.MyContent.Config); AddAttribute(xe, "Rtf", para.Rtf); - //AddParts(xe, "PartsAbove", para.PartsAbove); - //AddParts(xe, "PartsLeft", para.PartsLeft); - //AddParts(xe, "PartsRight", para.PartsRight); - //AddParts(xe, "PartsBelow", para.PartsBelow); AddChildren(level,0, parent, "ChildrenAbove", para.ChildrenAbove); AddChildren(level,0, parent, "ChildrenLeft", para.ChildrenLeft); AddChildren(level,0, parent, "ChildrenRight", para.ChildrenRight); AddChildren(level,0, parent, "ChildrenBelow", para.ChildrenBelow); } - private void AddChildren(int level, int fromType, XmlElement parent, string name, vlnParagraphs children) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping fromType and name for Debugging")] + private void AddChildren(int level, int fromType, XmlElement parent, string name, vlnParagraphs children) { if (children == null || children.Count == 0) return; - //XmlElement xchildren = xe.OwnerDocument.AppendChild(xe.OwnerDocument.CreateElement(name)) as XmlElement; foreach(vlnParagraph child in children) { - //XmlElement xechild = xe.ParentNode.AppendChild(xe.OwnerDocument.CreateElement("Item")) as XmlElement; Generate(level+1,0,parent,child); } } - //private void AddParts(XmlElement xe, string name, vlnPrintObjects parts) - //{ - // if (parts == null || parts.Count == 0) return; - // XmlElement xpart = xe.AppendChild(xe.OwnerDocument.CreateElement(name)) as XmlElement; - // foreach (vlnPrintObject part in parts) - // { - // XmlElement xechild = xpart.AppendChild(xe.OwnerDocument.CreateElement(part.GetType().Name)) as XmlElement; - // Generate(xechild, part); - // } - //} - //private void Generate(XmlElement xe, vlnPrintObject part) - //{ - // AddAttribute(xe, "Xoffset", part.XOffset); - // AddAttribute(xe, "Width", part.Width); - // AddAttribute(xe, "Rtf", part.Rtf); - //} private void AddAttribute(XmlElement xe, string attr, object val) { if (val == null) return; diff --git a/PROMS/Volian.Print.Library/CompleteRORpt.cs b/PROMS/Volian.Print.Library/CompleteRORpt.cs index f43a37e1..91e0f123 100644 --- a/PROMS/Volian.Print.Library/CompleteRORpt.cs +++ b/PROMS/Volian.Print.Library/CompleteRORpt.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Windows.Forms; @@ -16,93 +15,54 @@ namespace Volian.Print.Library class CompleteROReport { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - //Dictionary _MyErrorBookMarks = new Dictionary(); - Headers Hdrs; // Header stack object. + readonly Headers Hdrs; // Header stack object. RODataFile RO_df = null; int curheaderlen; - string RODataFileName; - iTextSharp.text.Document _pdfReportDoc = null; + readonly string RODataFileName; + readonly iTextSharp.text.Document _pdfReportDoc; PdfPTable datatable = null; - private iTextSharp.text.Font _f14; // = pdf.GetFont("Arial Unicode MS", 14, 1, Color.BLACK); + public iTextSharp.text.Font F14 { get; set; } - public iTextSharp.text.Font F14 - { - get { return _f14; } - set { _f14 = value; } - } - private iTextSharp.text.Font _f10; + public iTextSharp.text.Font F10 { get; set; } - public iTextSharp.text.Font F10 - { - get { return _f10; } - set { _f10 = value; } - } - private iTextSharp.text.Font _f12; + public iTextSharp.text.Font F12 { get; set; } - public iTextSharp.text.Font F12 - { - get { return _f12; } - set { _f12 = value; } - } - private iTextSharp.text.Font _f10Bold; + public iTextSharp.text.Font F10Bold { get; set; } - public iTextSharp.text.Font F10Bold - { - get { return _f10Bold; } - set { _f10Bold = value; } - } - private iTextSharp.text.Font _f12Bold; + public iTextSharp.text.Font F12Bold { get; set; } - public iTextSharp.text.Font F12Bold - { - get { return _f12Bold; } - set { _f12Bold = value; } - } + public bool ConvertCaretToDelta { get; set; } = true; - private bool _ConvertCaretToDelta = true; + public bool IncludeEmptyROFields { get; set; } = false; - public bool ConvertCaretToDelta - { - get { return _ConvertCaretToDelta; } - set { _ConvertCaretToDelta = value; } - } - private bool _IncludeEmptyROFields = false; - - public bool IncludeEmptyROFields - { - get { return _IncludeEmptyROFields; } - set { _IncludeEmptyROFields = value; } - } - private int _ROFstID; - - public int ROFstID - { - get { return _ROFstID; } - set { _ROFstID = value; } - } - private string ReportTitle = "Complete Referenced Objects Report"; - private PdfWriter _MyPDFWriter; + public int ROFstID { get; set; } + private readonly string ReportTitle = "Complete Referenced Objects Report"; + private readonly PdfWriter _MyPDFWriter; public CompleteROReport(PdfWriter mypdfwriter, iTextSharp.text.Document document, string dataFileName, bool convertCaretToDelta, bool includeEmptyROFields) { Hdrs = new Headers(); _pdfReportDoc = document; RODataFileName = dataFileName; - _ConvertCaretToDelta = convertCaretToDelta; + ConvertCaretToDelta = convertCaretToDelta; _MyPDFWriter = mypdfwriter; - _IncludeEmptyROFields = includeEmptyROFields; + IncludeEmptyROFields = includeEmptyROFields; } public void StartNewDataTable() { - datatable = new PdfPTable(1); - datatable.TotalWidth = _pdfReportDoc.PageSize.Width - _pdfReportDoc.LeftMargin - _pdfReportDoc.RightMargin; - datatable.LockedWidth = true; - PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, F14)); - cell.HorizontalAlignment = Element.ALIGN_CENTER; - cell.BackgroundColor = Color.WHITE; - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); + datatable = new PdfPTable(1) + { + TotalWidth = _pdfReportDoc.PageSize.Width - _pdfReportDoc.LeftMargin - _pdfReportDoc.RightMargin, + LockedWidth = true + }; + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, F14)) + { + HorizontalAlignment = Element.ALIGN_CENTER, + BackgroundColor = Color.WHITE, + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); datatable.HeaderRows = 3; datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; } @@ -113,33 +73,17 @@ namespace Volian.Print.Library PrintReport(); RO_df.close(); } - private Dictionary _MyDocOutline = new Dictionary(); - internal Dictionary MyDocOutline + internal Dictionary MyDocOutline { get; set; } = new Dictionary(); + public class DocOutline { - get { return _MyDocOutline; } - set { _MyDocOutline = value; } - } - public class DocOutline - { - private PdfOutline _MyOutline; + public PdfOutline MyOutline { get; set; } - public PdfOutline MyOutline + public string MyHeader { get; set; } + public DocOutline(PdfOutline outline, string header) { - get { return _MyOutline; } - set { _MyOutline = value; } - } - private string _MyHeader; - - public string MyHeader - { - get { return _MyHeader; } - set { _MyHeader = value; } - } - public DocOutline(PdfOutline outline, string header) - { - _MyHeader = header; - _MyOutline = outline; + MyHeader = header; + MyOutline = outline; } } private string ReplaceLineDrawCharsWithUnicode(string text) @@ -167,7 +111,6 @@ namespace Volian.Print.Library instr = instr.Replace("[RHO]", "\u03C1"); // C2016-018 rho symbol - is being read in as a line draw character, so users need to put "[RHO]" in their text for the rho symbol to print if (ConvertCaretToDelta) { - //char[] ca = instr.ToCharArray(); // for debug instr = instr.Replace("^", "\u0394"); // delta } //instr = instr.Replace("\x94", "\u0394"); // delta - the delta symbol is being read in as character x94 @@ -188,7 +131,7 @@ namespace Volian.Print.Library { string tstr = (instr.Substring(idx+uidx, m1.Index - uidx)); if (tstr.EndsWith(" ")) - tstr = tstr.Substring(0, tstr.Length - 1) + "\xA0"; + tstr = $"{tstr.Substring(0, tstr.Length - 1)}\xA0"; chk = new Chunk(tstr, fnt); if (underlineChunk) chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND); @@ -244,7 +187,7 @@ namespace Volian.Print.Library { string tstr = (strChk.Substring(uidx, m1.Index - uidx)); if (tstr.EndsWith(" ")) - tstr = tstr.Substring(0, tstr.Length - 1) + "\xA0"; + tstr = $"{tstr.Substring(0, tstr.Length - 1)}\xA0"; chk = new Chunk(tstr, fnt); if (underlineChunk) chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND); @@ -264,7 +207,7 @@ namespace Volian.Print.Library { string tstr = strChk.Substring(uidx); if (tstr.EndsWith(" ")) - tstr = tstr.Substring(0, tstr.Length - 1) + "\xA0"; + tstr = $"{tstr.Substring(0, tstr.Length - 1)}\xA0"; chk = new Chunk(tstr, fnt); if (underlineChunk) chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND); @@ -276,12 +219,9 @@ namespace Volian.Print.Library return p; } - public void AddText(string txt, Font fnt) - { - AddText(txt, fnt, Color.BLACK); - } - - public void AddText(string txt, Font fnt, Color txtcolor) + public void AddText(string txt, Font fnt) => AddText(txt, fnt, Color.BLACK); + + public void AddText(string txt, Font fnt, Color txtcolor) { // break the text up on double returns (paragraphs) and put each in their own cell // this will allow for page breaks between paragraphs0 @@ -289,11 +229,15 @@ namespace Volian.Print.Library string[] strlst = txt.Split(delim,StringSplitOptions.None); foreach (string str in strlst) { - Font f = new Font(fnt); - f.Color = txtcolor; - PdfPCell cell = new PdfPCell(ConvertDOSSuperAndSubScripts(str, f)); - cell.BorderColor = Color.WHITE; - if (strlst.Length > 1) + Font f = new Font(fnt) + { + Color = txtcolor + }; + PdfPCell cell = new PdfPCell(ConvertDOSSuperAndSubScripts(str, f)) + { + BorderColor = Color.WHITE + }; + if (strlst.Length > 1) cell.PaddingBottom = 6; datatable.AddCell(cell); } @@ -301,11 +245,12 @@ namespace Volian.Print.Library public void AddImage(string filename) { - ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(_ROFstID, filename); - if (roImage == null) roImage = ROFstInfo.Get(_ROFstID).GetROImageByFilename(filename, null); - PdfPCell spaceCell = new PdfPCell(); - spaceCell.BorderColor = Color.WHITE; - datatable.AddCell(spaceCell); + ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(ROFstID, filename) ?? ROFstInfo.Get(ROFstID).GetROImageByFilename(filename, null); + PdfPCell spaceCell = new PdfPCell + { + BorderColor = Color.WHITE + }; + datatable.AddCell(spaceCell); if (roImage != null) { ROImageConfig rc = new ROImageConfig(roImage); @@ -318,8 +263,8 @@ namespace Volian.Print.Library it_image = iTextSharp.text.Image.GetInstance(dcnt); //iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(ROImageInfo.Decompress(roImage.Content, size)); } - catch (Exception ex) - { + catch (Exception) + { try { MemoryStream ms = new MemoryStream(dcnt); @@ -342,9 +287,11 @@ namespace Volian.Print.Library } } it_image.ScaleToFit(_MyPDFWriter.DirectContent.PdfDocument.PageSize.Width - 144, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height - 216); - PdfPCell cell = new PdfPCell(it_image); - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); + PdfPCell cell = new PdfPCell(it_image) + { + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); roImage.Dispose(); } else @@ -364,17 +311,21 @@ namespace Volian.Print.Library if (ConvertCaretToDelta) plotlang = plotlang.Replace("^", "\x394"); // delta plotlang = plotlang.Replace("\x7F", "\x394"); //delta - PdfPCell spaceCell = new PdfPCell(); - spaceCell.BorderColor = Color.WHITE; - datatable.AddCell(spaceCell); + PdfPCell spaceCell = new PdfPCell + { + BorderColor = Color.WHITE + }; + datatable.AddCell(spaceCell); try { System.Drawing.RectangleF plotRect = MSWordToPDF.CreatePlot(pngFile, plotlang, 600F, MSWordToPDF.FormForPlotGraphics); iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(pngFile); it_image.ScaleToFit(_MyPDFWriter.DirectContent.PdfDocument.PageSize.Width - 144, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height - 216); - PdfPCell cell = new PdfPCell(it_image); - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); + PdfPCell cell = new PdfPCell(it_image) + { + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); } catch (Exception e) { @@ -386,94 +337,88 @@ namespace Volian.Print.Library } private string processingRO = ""; - private string _MyROID = null; - public string MyROID - { - get { return _MyROID; } - set { _MyROID = value; } - } - public void PrintReport() + public string MyROID { get; set; } = null; + + public void PrintReport() { bool StopPrinting = false; - bool UserTerminate = false; - Int16 iRecType = 0; - VlnStatusBar showStatBar = new VlnStatusBar("Complete RO Report"); - try + VlnStatusBar showStatBar = new VlnStatusBar("Complete RO Report"); + try { if (RO_df.GetFileLength() > 0) { showStatBar.BarMax = (int)RO_df.GetFileLength(); showStatBar.StatMsg = "Creating Report"; - // Loop until either printing is aborted or end of file. - while (!StopPrinting && (iRecType = RO_df.ReadInteger16()) != -1) - { - //Console.WriteLine("Record Type: {0}.{0:X}", iRecType); - switch (iRecType) - { - case 1: // Set Header - SetHeader(); - break; - case 2: // Push Header - PushHeader(); - break; - case 3: // Pop Header - PopHeader(); - break; - case 4: // RRO Begin - RROBegin(); - break; - case 5: // RRO End - RROEnd(); - processingRO = ""; - break; - case 6: // Msg - Msg(); - break; - case 7: - processingRO = KeyField(); - break; - case 8: - MyROID = ROIDField(); - break; - case 100: // Text Field - sometimes also XY Plot - Text(); - Application.DoEvents(); - break; - case 101: // Plot Field - XYPlot(); - Application.DoEvents(); - break; - case 102: // Image Field - ImageFile(); - Application.DoEvents(); - break; - case 103: // Multi Begin - Display data for setpoints - Multiple(); - break; - case 104: // Multi End - break; - case 0: // nothing was entered in that field - if (_IncludeEmptyROFields) - NoInformatEntered(); - break; - case 255: - _pdfReportDoc.Add(datatable); - _pdfReportDoc.NewPage(); - StartNewDataTable(); - showStatBar.BarValue = (int)RO_df.GetFilePointerPosition(); - //Console.WriteLine("Record Type: {0} No Operation", iRecType); - //Console.WriteLine("----------------------------------------------"); - break; - default: // Problem - //Console.WriteLine("Record Type: {0} Unrecognized record type", iRecType); - StopPrinting = true; - UserTerminate = true; - MessageBox.Show(string.Format("Unrecognized record type [{0}]", iRecType), "Error Creating Complete RO Report", MessageBoxButtons.OK, MessageBoxIcon.Error); - break; - }; - } - } + short iRecType; + // Loop until either printing is aborted or end of file. + while (!StopPrinting && (iRecType = RO_df.ReadInteger16()) != -1) + { + //Console.WriteLine("Record Type: {0}.{0:X}", iRecType); + switch (iRecType) + { + case 1: // Set Header + SetHeader(); + break; + case 2: // Push Header + PushHeader(); + break; + case 3: // Pop Header + PopHeader(); + break; + case 4: // RRO Begin + RROBegin(); + break; + case 5: // RRO End + RROEnd(); + processingRO = ""; + break; + case 6: // Msg + Msg(); + break; + case 7: + processingRO = KeyField(); + break; + case 8: + MyROID = ROIDField(); + break; + case 100: // Text Field - sometimes also XY Plot + Text(); + Application.DoEvents(); + break; + case 101: // Plot Field + XYPlot(); + Application.DoEvents(); + break; + case 102: // Image Field + ImageFile(); + Application.DoEvents(); + break; + case 103: // Multi Begin - Display data for setpoints + Multiple(); + break; + case 104: // Multi End + break; + case 0: // nothing was entered in that field + if (IncludeEmptyROFields) + NoInformatEntered(); + break; + case 255: + _pdfReportDoc.Add(datatable); + _pdfReportDoc.NewPage(); + StartNewDataTable(); + showStatBar.BarValue = (int)RO_df.GetFilePointerPosition(); + //Console.WriteLine("Record Type: {0} No Operation", iRecType); + //Console.WriteLine("----------------------------------------------"); + break; + default: // Problem + StopPrinting = true; + MessageBox.Show(string.Format("Unrecognized record type [{0}]", iRecType), "Error Creating Complete RO Report", MessageBoxButtons.OK, MessageBoxIcon.Error); + break; + } + ; + } + } else { StartNewDataTable(); @@ -502,20 +447,22 @@ namespace Volian.Print.Library // if there is lenght then we are in the mist of processing an RO string headers = erMsg; for (int iLoop = 0; iLoop < Hdrs.HdrCnt; iLoop++) - headers += Hdrs.strHdrs[iLoop] + "\n "; + headers += $"{Hdrs.strHdrs[iLoop]}\n "; if (processingRO.Length > 0) headers += processingRO; if (erMsg2 != null && erMsg2.Length > 0) headers += "\n" + erMsg2; - //MessageBox.Show(headers, erMsg, MessageBoxButtons.OK, MessageBoxIcon.Error); if (e != null) _MyLog.Error(headers, e); else _MyLog.Error(headers); - PdfOutline outl = new PdfOutline(MyErrorOutline, MyPdfDestPage, processingRO.Length > 0 ? processingRO : "Problem Reading Header"); - //DestSample(outl); - } +#pragma warning disable IDE0059 // Unnecessary assignment of a value - for debugging + PdfOutline outl = new PdfOutline(MyErrorOutline, MyPdfDestPage, processingRO.Length > 0 ? processingRO : "Problem Reading Header"); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + //DestSample(outl); + } + //For Debugging/Testing //private void DestSample(PdfOutline outl) //{ // new PdfOutline(outl, new PdfDestination(PdfDestination.FIT), "FIT"); @@ -531,29 +478,22 @@ namespace Volian.Print.Library public void AddErrorBookmarks() { if (_MyErrorOutline == null) return; - //if (_MyErrorBookMarks.Count == 0) return; - //PdfOutline outline = null; - //foreach (string key in _MyErrorBookMarks.Keys) - //{ - // if (outline == null) outline = new PdfOutline(_MyPDFWriter.DirectContent.RootOutline, _MyErrorBookMarks[key], "Errors"); - // new PdfOutline(outline, _MyErrorBookMarks[key], key); - //} string emsg = "A Bookmark grouping named \"Errors\" was added to the PDF.\n\n Click on the RO in this grouping to jump to the report page which will contain an error message.\n\nThe error were also recorded in the PROMS error log."; MessageBox.Show(emsg, "Errors Found Creating Report", MessageBoxButtons.OK, MessageBoxIcon.Information); } public void Multiple() { - Int16 typ, i, j, nw = 0; + short typ, i, j; string str, sep; string buff = ""; int[] width; LastHeader(); sep = ""; - // nw - number of fields - nw = RO_df.ReadInteger16(); - // allocate space for widths - width = new int[nw]; + // nw - number of fields + short nw = RO_df.ReadInteger16(); + // allocate space for widths + width = new int[nw]; // loop through and load field widths and names for (i = 0; i < nw; i++) { @@ -645,7 +585,7 @@ namespace Volian.Print.Library //Console.WriteLine("Set Header"); // Get the number of header records - Int16 iNewCnt = RO_df.ReadInteger16(); + short iNewCnt = RO_df.ReadInteger16(); //Console.WriteLine("Num Header Records: {0}", iNewCnt); @@ -676,16 +616,11 @@ namespace Volian.Print.Library bool _LastWasName = false;//B2016-251 Don't change underscore to underline to Name value public void PushHeader() { - //if (m_pPrinterOut->Row() > 55) - //// m_pPrinterOut->newpage(); - //pdfReportDoc.NewPage(); string pTmp = RO_df.ReadText(); //Console.WriteLine("PH[{0}]", pTmp); curheaderlen = pTmp.Length; _LastWasName = (pTmp == "Name");//B2016-251 Don't change underscore to underline to Name value - //Hdrs.strHdrs[Hdrs.HdrCnt] = pTmp; Hdrs.strHdrs.Add(pTmp); - //Hdrs.repeatCount[Hdrs.HdrCnt] = 2; Hdrs.repeatCount.Add(2); Hdrs.HdrCnt++; Hdrs.printedLastHeader = false; @@ -704,15 +639,12 @@ namespace Volian.Print.Library // if the last header was pushed on header list // print eject the page if the page ran out, and // print the header with "none". - //if (m_pPrinterOut->Row() > 55) - // m_pPrinterOut->NewPage(); LastHeader(); //m_pPrinterOut->PutLine(0, "none"); //m_pPrinterOut->NewLine(1); } // Remove the header Hdrs.HdrCnt--; - //Hdrs.strHdrs[Hdrs.HdrCnt] = null; Hdrs.strHdrs.RemoveAt(Hdrs.HdrCnt); Hdrs.repeatCount.RemoveAt(Hdrs.HdrCnt); @@ -722,7 +654,6 @@ namespace Volian.Print.Library public void RROBegin() { - //m_pPrinterOut->NewPage(); //Console.WriteLine("RRO Begin"); //Console.WriteLine("----------------------------------------------"); // Start of a new RO, print out the headers @@ -730,12 +661,11 @@ namespace Volian.Print.Library { if (!MyDocOutline.ContainsKey(iLoop) || MyDocOutline[iLoop].MyHeader != Hdrs.strHdrs[iLoop]) { - PdfOutline parentOutline = null; - if (iLoop == 0) + PdfOutline parentOutline; + if (iLoop == 0) parentOutline = MyRootOutline;//_MyPDFWriter.DirectContent.RootOutline; else parentOutline = MyDocOutline[iLoop - 1].MyOutline; - //pdfDest = new PdfDestination(PdfDestination.FITH, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height); AddOutlineLevel(parentOutline, iLoop, Hdrs.strHdrs[iLoop], MyPdfDestPage); } // Change double underscore to spaces in header text @@ -748,20 +678,13 @@ namespace Volian.Print.Library { // FITH was acting strange and shifting towards bottom of the page as the number of pages increased //Console.WriteLine("Top = {0}, {1}", _Top, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height); - //return new PdfDestination(PdfDestination.FITH, _Top);//_MyPDFWriter.DirectContent.PdfDocument.PageSize.Height); return new PdfDestination(PdfDestination.XYZ, 0, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height, 1.5f); } } - public PdfDestination MyPdfDestPage - { - get - { - return new PdfDestination(PdfDestination.FITV,0); - } - } + public PdfDestination MyPdfDestPage => new PdfDestination(PdfDestination.FITV, 0); - private PdfOutline _MyErrorOutline = null; + private PdfOutline _MyErrorOutline = null; public PdfOutline MyErrorOutline { @@ -787,7 +710,6 @@ namespace Volian.Print.Library return _MyRootOutline; } } - private PdfDestination pdfDest = null; private void AddOutlineLevel(PdfOutline parentOutline, int iLoop, string hdr, PdfDestination pdfDest) { if (MyDocOutline.ContainsKey(iLoop)) @@ -798,7 +720,6 @@ namespace Volian.Print.Library public void RROEnd() { - //m_pPrinterOut->PageEnd(); // Remove any headers that are left over //Console.WriteLine("{0} headers cleaned up.", Hdrs.HdrCnt); //Console.WriteLine("RRO End"); @@ -843,7 +764,7 @@ namespace Volian.Print.Library public void Text() { // Get the lenght of the text string and read it in - Int16 iValue = RO_df.ReadInteger16(); + short iValue = RO_df.ReadInteger16(); string szStr = ""; // B2016-247 If size is zero it is an empty string. if (iValue > 0) @@ -867,11 +788,9 @@ namespace Volian.Print.Library if (isXYPlot || (iValue + curheaderlen) > 72 || (szStr.IndexOf('\r') != -1)) { - // If the lenght of the string plus the field title is greater + // If the length of the string plus the field title is greater // than 72 characters or has a carriage return character in it // then output the text on multiple lines - //if (m_pPrinterOut->Row() > 55) - // m_pPrinterOut->newpage(); // the header goes on its own line cell.AddElement(p); @@ -891,10 +810,6 @@ namespace Volian.Print.Library datatable.AddCell(cell); //m_pPrinterOut->SetNumberOfNewLines(0); //m_pPrinterOut->putline(0, temp); - //if (m_pPrinterOut->Row() + 1 > 55) - // Hdrs.repeatCount[Hdrs.HdrCnt] = 1; - //else - // m_pPrinterOut->newline(1); } //Console.WriteLine("Text"); //Console.WriteLine("Value: {0}", iValue); @@ -906,10 +821,11 @@ namespace Volian.Print.Library { // use the key field as the PDF bookbark string szStr = RO_df.ReadText(); - //PdfDestination pdfDest = new PdfDestination(PdfDestination.FITH, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height); - PdfOutline outl = new PdfOutline(MyDocOutline[Hdrs.HdrCnt - 1].MyOutline, MyPdfDestTop, szStr); - //DestSample(outl); - return szStr; +#pragma warning disable IDE0059 // Unnecessary assignment of a value - For Debugging + PdfOutline outl = new PdfOutline(MyDocOutline[Hdrs.HdrCnt - 1].MyOutline, MyPdfDestTop, szStr); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + //DestSample(outl); + return szStr; //Console.WriteLine("Key Field"); //Console.WriteLine("Key Text: {0}", szStr); //Console.WriteLine("----------------------------------------------"); @@ -918,6 +834,7 @@ namespace Volian.Print.Library { // use the key field as the PDF bookbark string szStr = RO_df.ReadText(); + //For Dubugging //PdfDestination pdfDest = new PdfDestination(PdfDestination.FITH, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height); //PdfOutline outl = new PdfOutline(MyDocOutline[Hdrs.HdrCnt - 1].MyOutline, MyPdfDestTop, szStr); //DestSample(outl); @@ -931,25 +848,26 @@ namespace Volian.Print.Library public void ImageFile() { string fn = RO_df.ReadText(); - Int16 ht = RO_df.ReadInteger16(); - Int16 wd = RO_df.ReadInteger16(); - //m_pPrinterOut->PrintImage(fn, wd, ht); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - for Debugging + short ht = RO_df.ReadInteger16(); + short wd = RO_df.ReadInteger16(); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + //m_pPrinterOut->PrintImage(fn, wd, ht); - //Console.WriteLine("ImageFile"); - //Console.WriteLine("Name: {0}", fn); - //Console.WriteLine("Height: {0}", ht); - //Console.WriteLine("Width: {0}", wd); - //Console.WriteLine("----------------------------------------------"); - AddImage(fn); + //Console.WriteLine("ImageFile"); + //Console.WriteLine("Name: {0}", fn); + //Console.WriteLine("Height: {0}", ht); + //Console.WriteLine("Width: {0}", wd); + //Console.WriteLine("----------------------------------------------"); + AddImage(fn); } // Read in the X/Y plot info. public void XYPlot() { // Get the lenght of the text string and read it in - Int16 iValue = RO_df.ReadInteger16(); + short iValue = RO_df.ReadInteger16(); string szStr = RO_df.ReadText(iValue); - string temp = szStr; - Chunk chk = LastHeader(); // = new Chunk(m.Value, fnt); + Chunk chk = LastHeader(); Phrase p = new Phrase(); PdfPCell cell = new PdfPCell(); p.Add(chk); // add the header chunk @@ -997,7 +915,6 @@ namespace Volian.Print.Library chk = new Chunk(hdrtxt, F10Bold); Hdrs.printedLastHeader = true; return chk; - //m_pPrinterOut->LastHeader(); } }// end CompSumROReport @@ -1005,9 +922,7 @@ namespace Volian.Print.Library public class Headers { - //public string[] strHdrs; public List strHdrs; -// public int[] repeatCount; public int HdrCnt; public List repeatCount; public bool printedLastHeader; @@ -1022,8 +937,8 @@ namespace Volian.Print.Library public class RODataFile { - FileStream fs = null; - BinaryReader br = null; + readonly FileStream fs = null; + readonly BinaryReader br = null; public RODataFile(string fname) { fs = new FileStream(fname,FileMode.Open); @@ -1034,16 +949,10 @@ namespace Volian.Print.Library br.Close(); fs.Close(); } - public long GetFileLength() - { - return fs.Length; - } - public long GetFilePointerPosition() - { - return fs.Position; - } -// Read an integer value from the data file - public Int16 ReadInteger16() + public long GetFileLength() => fs.Length; + public long GetFilePointerPosition() => fs.Position; + // Read an integer value from the data file + public Int16 ReadInteger16() { try { @@ -1055,18 +964,15 @@ namespace Volian.Print.Library return -1; } } -// Read a text string from the data file and returns it. -// The calling program is responsible for free it -// with the "delete" operator. + // Read a text string from the data file and returns it. + // The calling program is responsible for free it + // with the "delete" operator. - public string ReadText() - { - return ReadText(-1); - } + public string ReadText() => ReadText(-1); - public string ReadText(Int16 i16CharCount) + public string ReadText(Int16 i16CharCount) { - Int16 i16DataSize; + short i16DataSize; if (i16CharCount == -1) i16DataSize = ReadInteger16(); else @@ -1082,15 +988,14 @@ namespace Volian.Print.Library for (int i = 0; i < i16DataSize; i++) str += Convert.ToChar(charbuff[i]).ToString(); return (str); - //return (Encoding.ASCII.GetString(charbuff, 0, i16DataSize)); // this didn't handle line draw chars } } // Search through the file to find the next record public long NextRecord() { - Int16 iType; - Int16 RECORD_START = 255; + short iType; + short RECORD_START = 255; // While not the next record and not end of file get the next meta item while ((iType = ReadInteger16()) != RECORD_START && iType != -1) { @@ -1101,28 +1006,25 @@ namespace Volian.Print.Library // Get the next meta item and discard the data public long NextItem() { - string pTmp; - Int16 iRecType = ReadInteger16(); - Int16 iNewCnt; - int iLoop; - switch (iRecType) + short iRecType = ReadInteger16(); + short iNewCnt; + int iLoop; + switch (iRecType) { case 1: // Set Header iNewCnt = ReadInteger16(); for (iLoop = 0; iLoop < iNewCnt; iLoop++) { ReadInteger16(); - pTmp = ReadText(); - //delete pTmp; + _ = ReadText(); } break; case 2: // Push Header case 6: // Msg case 7: // Key Field case 100: // Text Field - case 101: // Plot Field - pTmp = ReadText(); - //delete pTmp; + case 101: // Plot Field + _ = ReadText(); break; case 3: // Pop Header case 4: // RRO Begin @@ -1133,8 +1035,7 @@ namespace Volian.Print.Library // Do nothing break; case 102: // Image Field - pTmp = ReadText(); - //delete pTmp; + _ = ReadText(); ReadInteger16(); ReadInteger16(); break; diff --git a/PROMS/Volian.Print.Library/ContActionSum.cs b/PROMS/Volian.Print.Library/ContActionSum.cs index 02276c91..87b04c9f 100644 --- a/PROMS/Volian.Print.Library/ContActionSum.cs +++ b/PROMS/Volian.Print.Library/ContActionSum.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Text; -using System.Drawing; using LBWordLibrary; using VEPROMS.CSLA.Library; using System.Text.RegularExpressions; @@ -10,12 +8,12 @@ namespace Volian.Print.Library { public class ContinuousActionSummary : IDisposable { - private LBApplicationClass _WordApp; - private LBDocumentClass _WordDoc; - private LBSelection _WordSel; + private readonly LBApplicationClass _WordApp; + private readonly LBDocumentClass _WordDoc; + private readonly LBSelection _WordSel; private LBTable _WordTbl; private const string TheQuickBrownFox = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."; - private VE_Font _pkFont; + private readonly VE_Font _pkFont; public ContinuousActionSummary() { _WordApp = new LBApplicationClass(); @@ -41,7 +39,6 @@ namespace Volian.Print.Library _WordApp = new LBApplicationClass(); _WordDoc = _WordApp.Documents.Add(); _WordSel = _WordApp.Selection; - //_WordApp.Visible = true; _pkFont = pkFont; AddTable(); AddHeader(doingTimeCriticalSummary); // F2022-024 pass flag when creating a Time Critical Action Summary report @@ -72,11 +69,11 @@ namespace Volian.Print.Library if (txtPageNum == "") txtPageNum = (pghC.MyParagraph.MyItemInfo.PageNumber + 1).ToString(); AddContinuousAction(NoteCautionTab, GetContActStepText(pghC.MyParagraph.MyItemInfo), doneStr, txtPageNum, 0, 0); } - string stpTab = pgh.MyParagraph.MyItemInfo.MyTab.CleanText.Trim() + " "; // this is either the High Level step tab or the sub-step tab + string stpTab = $"{pgh.MyParagraph.MyItemInfo.MyTab.CleanText.Trim()} "; // this is either the High Level step tab or the sub-step tab float preTabLen = 0; if (pgh.MyParagraph.MyItemInfo.IsNote || pgh.MyParagraph.MyItemInfo.IsCaution) // only the caution and/or note is on the CAS - high level step not selected { - stpTab = string.Format("{0} ", hlsii.MyTab.Text.Trim()) + " " + stpTab; + stpTab = $"{hlsii.MyTab.Text.Trim()} {stpTab}"; } else if (!pgh.MyParagraph.MyItemInfo.IsHigh) // if the high level step was not included, adjust the tab for a sub-step/RNO { @@ -98,13 +95,13 @@ namespace Volian.Print.Library prevItemInfo = prevItemInfo.MyParent; } if (_FirstLine) // the first of a CAS on the report include the High Level Step tab - sbTabPre.Insert(0, (hlsii != null) ? hlsii.MyTab.Text.Trim() + " " : ""); + sbTabPre.Insert(0, (hlsii != null) ? $"{hlsii.MyTab.Text.Trim()} " : ""); tabPre = sbTabPre.ToString(); if (!_FirstLine) // if not the first line we indent the size of high level step tab - preTabLen = GetTextWidth(hlsii.MyTab.Text.Trim() + " ") / 72f; + preTabLen = GetTextWidth($"{hlsii.MyTab.Text.Trim()} ") / 72f; if (pgh.MyParagraph.MyItemInfo.IsInRNO) { - stpTab = stpTab.TrimEnd() + "[R] "; + stpTab = $"{stpTab.TrimEnd()}[R] "; } stpTab = tabPre + stpTab; } @@ -135,7 +132,7 @@ namespace Volian.Print.Library string stpTab = cpgh.MyParagraph.MyItemInfo.MyTab.CleanText.Trim() + (cpgh.MyParagraph.MyItemInfo.IsInRNO ? "[R] ": " "); if (cpgh.MyParagraph.MyItemInfo.IsNote || cpgh.MyParagraph.MyItemInfo.IsCaution) { - stpTab = string.Format("{0} ", cpgh.MyParagraph.MyParent.MyTab.Text.Trim()) + " " + stpTab; + stpTab = $"{string.Format("{0} ", cpgh.MyParagraph.MyParent.MyTab.Text.Trim())} {stpTab}"; } ItemInfo prevItmInfo = cpgh.MyParagraph.MyItemInfo.MyParent; // F2026-001 the while loop below will add the sub-step's parent tab if applicable @@ -154,19 +151,9 @@ namespace Volian.Print.Library } } - private string GetContActStepText(ItemInfo myItemInfo) - { - //string conActSumText = ""; - //StepConfig sc = myItemInfo.MyConfig as StepConfig; - //if (sc != null && sc.Step_AlternateContActSumText != null) - // conActSumText = sc.Step_AlternateContActSumText; - //if (conActSumText == "") - // conActSumText = myItemInfo.FormattedDisplayText; - //return conActSumText; - return myItemInfo.FormattedDisplayText; - } + private string GetContActStepText(ItemInfo myItemInfo) => myItemInfo.FormattedDisplayText; - private void AddNotesOrCautions(pkParagraph pgh, int level) + private void AddNotesOrCautions(pkParagraph pgh, int level) { foreach (pkParagraph cpgh in pgh.MyCautionsAndNotes) { @@ -305,7 +292,7 @@ namespace Volian.Print.Library } _FirstLine = false; } - static Regex rgx = new Regex(@"\\(b|ul|up[1-9]|dn0|up0|dn[1-9]|b0|ulnone)( |$|(?=\\))"); + static readonly Regex rgx = new Regex(@"\\(b|ul|up[1-9]|dn0|up0|dn[1-9]|b0|ulnone)( |$|(?=\\))"); private void WriteRTF(string text) { Match m = rgx.Match(text); @@ -363,17 +350,8 @@ namespace Volian.Print.Library _WordSel.ParagraphFormat.Alignment = hAlign; _WordSel.Cells.VerticalAlignment = vAlign; } - private void Advance(int count) - { - _WordSel.MoveRight(LBWdUnits.wdCell, count, false); - } - private void Advance() - { - Advance(1); - } - public void Dispose() - { - _WordApp.Quit(false); - } - } + private void Advance(int count) => _WordSel.MoveRight(LBWdUnits.wdCell, count, false); + private void Advance() => Advance(1); + public void Dispose() => _WordApp.Quit(false); + } } diff --git a/PROMS/Volian.Print.Library/GlobalSuppressions.cs b/PROMS/Volian.Print.Library/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/Volian.Print.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.Print.Library/Grid2Pdf.cs b/PROMS/Volian.Print.Library/Grid2Pdf.cs index 652cc3fd..c37c7688 100644 --- a/PROMS/Volian.Print.Library/Grid2Pdf.cs +++ b/PROMS/Volian.Print.Library/Grid2Pdf.cs @@ -2,12 +2,8 @@ using System; using System.Collections.Generic; using System.Text; using C1.Win.C1FlexGrid; -using System.IO; using Itenso.Rtf; -using Itenso.Rtf.Parser; -using Itenso.Rtf.Interpreter; using Itenso.Rtf.Support; -using Volian.Print.Library; using Volian.Controls.Library; using iTextSharp.text; using iTextSharp.text.pdf; @@ -19,139 +15,37 @@ namespace Volian.Print.Library #region Settings // RHM20150429 - Table Scrunch public partial class vlnTable { - private string _DebugInfo = null; // RHM20150429 - Table Scrunch - public string DebugInfo - { - get { return _DebugInfo; } - set { _DebugInfo = value; } - } - private int _ItemID = 0; - public int ItemID - { - get { return _ItemID; } - set { _ItemID = value; } - } - private bool _ShowDetails = false; - public bool ShowDetails - { - get { return _ShowDetails; } - set { _ShowDetails = value; } - } - private bool _IsTooBig = false; - public bool IsTooBig - { - get { return _IsTooBig; } - set { _IsTooBig = value; } - } - } - public partial class vlnCells - { - private static float YAdjust_HContent = 4; // 4 - private float YAdjust_SpacingAfter - { - get - { - return 8-8*MyTable.Adjustment;//0; // 8 - } - } - } + public string DebugInfo { get; set; } = null; + public int ItemID { get; set; } = 0; + public bool ShowDetails { get; set; } = false; + public bool IsTooBig { get; set; } = false; + } public partial class vlnCell { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - public bool ShowDetails - { get { return MyTable.ShowDetails; } } - private static float YAdjust_h = 0; // 0 - private float YAdjust_TextLocation - { - get - { - return 4 - 4 * MyTable.Adjustment; ;//0; // 4 - } - } - } - //public partial class vlnTable - //{ - // private static float YAdjust_RowTop = 0;//8; // 0 - //} - //public partial class vlnCells - //{ - // private static float YAdjust_HContent = 4; // 4 - // private static float YAdjust_SpacingAfter = 8;//0; // 8 - //} - //public partial class vlnCell - //{ - // private static float YAdjust_h = 0; // 0 - // private static float YAdjust_TextLocation = 4;//0; // 4 - //} + #endregion + public bool ShowDetails => MyTable.ShowDetails; + private static readonly float YAdjust_h = 0; + } #endregion public partial class vlnTable { - #region Properties - // HContents: For each row, contains the largest height for all columns in that row. - // Merged cells are accounted for. This is done in vlnCells:SetupCells - private float[] _HContents;// RHM20150525 - Table Scrunch - public float[] HContents - { - get { return _HContents; } - set { _HContents = value; } - } - private float[] _RowTop; - public float[] RowTop - { - get { return _RowTop; } - set { _RowTop = value; } - } - private float[] _ColLeft; - public float[] ColLeft - { - get { return _ColLeft; } - set { _ColLeft = value; } - } - private VlnFlexGrid _MyFlexGrid; - public VlnFlexGrid MyFlexGrid - { - get { return _MyFlexGrid; } - set { _MyFlexGrid = value; } - } - private VlnBorders _MyBorders; - public VlnBorders MyBorders - { - get { return _MyBorders; } - set { _MyBorders = value; } - } - // C2021-004 Table cell shading - private VlnGridCellShading _MyShading; - public VlnGridCellShading MyShading - { - get { return _MyShading; } - set { _MyShading = value; } - } - private iTextSharp.text.pdf.PdfContentByte _MyContentByte; - public iTextSharp.text.pdf.PdfContentByte MyContentByte - { - get { return _MyContentByte; } - set { _MyContentByte = value; } - } - private vlnCells _MyCells; - public vlnCells MyCells - { - get { return _MyCells; } - set { _MyCells = value; } - } - public float Height - { get - { - return RowTop[RowTop.Length - 1]; - } } - public float Width - { get - { - return ColLeft[ColLeft.Length - 1]; - } } + #region Properties + // HContents: For each row, contains the largest height for all columns in that row. + // Merged cells are accounted for. This is done in vlnCells:SetupCells + public float[] HContents { get; set; } + public float[] RowTop { get; set; } + public float[] ColLeft { get; set; } + public VlnFlexGrid MyFlexGrid { get; set; } + public VlnBorders MyBorders { get; set; } + public VlnGridCellShading MyShading { get; set; } + public iTextSharp.text.pdf.PdfContentByte MyContentByte { get; set; } + public vlnCells MyCells { get; set; } + public float Height => RowTop[RowTop.Length - 1]; + public float Width => ColLeft[ColLeft.Length - 1]; - private static float _XOffset = -1; // This moves the borders with respect to the text + private static float _XOffset = -1; // This moves the borders with respect to the text public static float XOffset { get { return vlnTable._XOffset; } @@ -186,7 +80,7 @@ namespace Volian.Print.Library get { return (LineThicknessForThick - LineThicknessForDouble) / 2; }//LineThicknessForThick - 2 * LineThicknessForDouble; } } private float _TotalContentHeight = 0;// RHM20150525 - Table Scrunc - // TotalContentHeight - height of just the content of all rows in the table. + public float TotalContentHeight { get @@ -199,29 +93,28 @@ namespace Volian.Print.Library return _TotalContentHeight; } } - public float SpaceAvailable// RHM20150525 - Table Scrunc - { - // SpaceAvailable is the amount of white space there is to work with. It uses the bottom location - // of the table and subtracts how much height the actual contents take, TotalContentHeight. TotalContentHeight - // includes size/height (font size - assumes 12, 6LPI) of text & leading (space between lines) - get { return TotalContentHeight ==0 ? 0 : RowTop[RowTop.Length - 1] - TotalContentHeight; } - } - public float LeadingSpaceAvailable// B2018-085 - Table Scrunch Fix: - { - // LeadingSpaceAvailable is the amount of 'blank' space between lines, this is included in TotalContentHeight. - // 1.5 is difference between 12 and 13.5, 12 is the standard font size, i.e. 6LPI. 13.5 is line leading. - // 1.5/13.5 is amount of space used by leading. - get { return TotalContentHeight == 0 ? 0 : TotalContentHeight * 1.5F/13.5F; } - } - // TooBig is the amount that the grid is over the amount of space on the page. To start (value in TooBig), it is set to - // (height of grid w/ compressed setting if needed + line) - (how much room on page), i.e. negative number if it can fit - private float _TooBig;// RHM20150525 - Table Scrunc + + // RHM20150525 - Table Scrunc + // SpaceAvailable is the amount of white space there is to work with. It uses the bottom location + // of the table and subtracts how much height the actual contents take, TotalContentHeight. TotalContentHeight + // includes size/height (font size - assumes 12, 6LPI) of text & leading (space between lines) + public float SpaceAvailable => TotalContentHeight == 0 ? 0 : RowTop[RowTop.Length - 1] - TotalContentHeight; + + // B2018-085 - Table Scrunch Fix: + // LeadingSpaceAvailable is the amount of 'blank' space between lines, this is included in TotalContentHeight. + // 1.5 is difference between 12 and 13.5, 12 is the standard font size, i.e. 6LPI. 13.5 is line leading. + // 1.5/13.5 is amount of space used by leading. + public float LeadingSpaceAvailable => TotalContentHeight == 0 ? 0 : TotalContentHeight * 1.5F / 13.5F; + // TooBig is the amount that the grid is over the amount of space on the page. To start (value in TooBig), it is set to + // (height of grid w/ compressed setting if needed + line) - (how much room on page), i.e. negative number if it can fit + private float _TooBig;// RHM20150525 - Table Scrunc public float TooBig { get { return _TooBig; } set { _TooBig = value; + //Debugging //_Adjustment = Math.Min(1F, (_TooBig / (RowTop.Length - 1)) / 12); //if (ShowDetails) Console.WriteLine("TooBig\t{0}\t{1}", value, _Adjustment); //if(ShowDetails) Console.WriteLine("Before RowTop={0}", RowTop[RowTop.Length-1] ); @@ -252,21 +145,10 @@ namespace Volian.Print.Library //if(ShowDetails) Console.WriteLine("After RowTop={0}", RowTop[RowTop.Length-1] ); } } - private float _Adjustment = 0;// RHM20150525 - Table Scrunc - public float Adjustment - { - get { return _Adjustment; } - set { _Adjustment = value; } - } - //private float _YAdjust_RowTop = 0;//8; // 0 - public float YAdjust_RowTop - { - get - { - return _Adjustment * 12; - } - } - private void DrawRuler(PdfContentByte cb, float x, float yTop, float height)// RHM20150525 - Table Scrunc + + public float Adjustment { get; set; } = 0; + public float YAdjust_RowTop => Adjustment * 12; + private void DrawRuler(PdfContentByte cb, float x, float yTop, float height)// RHM20150525 - Table Scrunc { VlnSvgPageHelper myPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; if (myPageHelper.DebugLayer != null) @@ -290,8 +172,8 @@ namespace Volian.Print.Library cb.LineTo(x, y); cb.Stroke(); } - i = 0; - cb.Stroke(); + + cb.Stroke(); cb.RestoreState(); cb.EndLayer(); } @@ -320,17 +202,12 @@ namespace Volian.Print.Library 0, myItemInfo.ItemID, myItemInfo.FormatStepType, myItemInfo.FormatStepData == null ? "NoStepData" : myItemInfo.FormatStepData.Type, myItemInfo.StepLevel, myItemInfo.ShortPath, Width, XOffset, YOffset); } - #endregion - private string _Path; + #endregion -public string Path -{ - get { return _Path; } - set { _Path = value; } -} + public string Path { get; set; } - #region Constructors - public vlnTable(VlnFlexGrid myFlexGrid, iTextSharp.text.pdf.PdfContentByte myContentByte) + #region Constructors + public vlnTable(VlnFlexGrid myFlexGrid, iTextSharp.text.pdf.PdfContentByte myContentByte) { MyFlexGrid = myFlexGrid; MyContentByte = myContentByte; @@ -374,7 +251,7 @@ public string Path string myLPI = myPageHelper.YMultiplier == 1.0F ? ",6LPI" : ",7LPI"; Rtf2Pdf.DrawPdfDebug(myColumnText.Canvas, left-2, top+1, left + Width, top-myPageHelper.YMultiplier *(Height+1), DebugInfo+", Height= " + (myPageHelper.YMultiplier * Height).ToString() + myLPI, 0); - PdfLayer textLayer = myPageHelper == null ? null : myPageHelper.TextLayer; // RHM20150429 - Table Scrunch + PdfLayer textLayer = myPageHelper?.TextLayer; // RHM20150429 - Table Scrunch if (textLayer != null) cb.BeginLayer(textLayer); myPageHelper.AddGap(top, top - Height, left, left + Width); MyCells.ToPdf(myColumnText, left, top); @@ -383,6 +260,7 @@ public string Path ShowRowTops("ToPDF2"); if (ShowDetails) Console.WriteLine("^^^^^^ToPdf============{0}===============", ItemID); } + //For Debugging private void ZoomGrid(iTextSharp.text.pdf.ColumnText myColumnText, float left, float top) { PdfDestination dest = new PdfDestination(PdfDestination.FITR, left - 4, top - Height - 4, left + Width, top + 4); @@ -394,58 +272,41 @@ public string Path { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - #region Properties - private VlnFlexGrid _MyFlexGrid; - public VlnFlexGrid MyFlexGrid - { - get { return _MyFlexGrid; } - set { _MyFlexGrid = value; } - } - private vlnTable _MyTable; - public vlnTable MyTable - { - get { return _MyTable; } - set { _MyTable = value; } - } - public bool ShowDetails// RHM20150525 - Table Scrunc + #endregion + #region Properties + public VlnFlexGrid MyFlexGrid { get; set; } + public vlnTable MyTable { get; set; } + public bool ShowDetails// RHM20150525 - Table Scrunc { get { return MyTable.ShowDetails; }} - private iTextSharp.text.pdf.PdfContentByte _MyContentByte; - public iTextSharp.text.pdf.PdfContentByte MyContentByte - { - get { return _MyContentByte; } - set { _MyContentByte = value; } - } - #endregion - #region Constructors - public vlnCells(vlnTable myTable, VlnFlexGrid myFlexGrid, iTextSharp.text.pdf.PdfContentByte myContentByte) + + public iTextSharp.text.pdf.PdfContentByte MyContentByte { get; set; } + #endregion + #region Constructors + public vlnCells(vlnTable myTable, VlnFlexGrid myFlexGrid, iTextSharp.text.pdf.PdfContentByte myContentByte) { MyTable = myTable; MyFlexGrid = myFlexGrid; MyContentByte = myContentByte; SetupCells(); - foreach(vlnCell cell in this) - { - myTable.MyShading = VlnGridCellShading.Get(myFlexGrid.MyShading.ConvertToString()); // C2021-004 Table Cell Shading - myTable.MyBorders = VlnBorders.Get(myFlexGrid.MyBorders.ConvertToString()); - GridLinePattern glp = cell.AboveLeftSide; - glp = cell.AboveRightSide; - glp = cell.BelowLeftSide; - glp = cell.BelowRightSide; - glp = cell.RightOfBottomSide; - glp = cell.RightOfTopSide; - object ta = cell.TextAlign; - } - } - #endregion - private float _MyLeading = 13.5F; // B2018-085 AEP and APP worked with 13.5 - public float MyLeading - { - get { return _MyLeading; } - set { _MyLeading = value; } - } - #region Private Methods - private void SetupCells() + //Note - this is done in case goes outside boundries to set bounds of cell + //loops through cells - side effect code checks for merged cells + foreach (vlnCell cell in this) + { + myTable.MyShading = VlnGridCellShading.Get(myFlexGrid.MyShading.ConvertToString()); // C2021-004 Table Cell Shading + myTable.MyBorders = VlnBorders.Get(myFlexGrid.MyBorders.ConvertToString()); + _ = cell.AboveLeftSide; + _ = cell.AboveRightSide; + _ = cell.BelowLeftSide; + _ = cell.BelowRightSide; + _ = cell.RightOfBottomSide; + _ = cell.RightOfTopSide; + _ = cell.TextAlign; + } + } + #endregion + public float MyLeading { get; set; } = 13.5F; + #region Private Methods + private void SetupCells() { // Create a ColumnText to determine the cell heights iTextSharp.text.pdf.ColumnText myColumnText1 = new iTextSharp.text.pdf.ColumnText(MyContentByte); @@ -526,9 +387,9 @@ public string Path TrimNewlines(myPara); // RHM20150429 - Table Scrunch myColumnText1.AddElement(myPara); - float posBefore = myColumnText1.YLine; // position is y of top of paragraph since paragraph was just added - int status = myColumnText1.Go(true); // 'puts out' text for info only - float posAfter = myColumnText1.YLine; // posAfter is y of bottom of paragraph, really y top of line below this + float posBefore = myColumnText1.YLine; // position is y of top of paragraph since paragraph was just added + _ = myColumnText1.Go(true); // 'puts out' text for info only + float posAfter = myColumnText1.YLine; // posAfter is y of bottom of paragraph, really y top of line below this float hContent = 4 + posBefore - posAfter; // TableScrunch Phase 4: sets content height, uses the size derived from iTextsharp putting out text @@ -566,6 +427,7 @@ public string Path } } } + //For Debugging: // This summarizes the Content heights per row //int i=0; //foreach (float h in MyTable.HContents) @@ -580,41 +442,6 @@ public string Path return total; } - // B2017-105 if a symbol character was set to a bigger font size, then the positioning of the larger symbol character was printing too high on the line - // found with Wolf Creek use of the empty box symbol - //private float BiggestFontSize(Paragraph myPara) - //{ - // float fontSize = 12; - // foreach (Chunk ck in myPara.Chunks) - // { - // fontSize = Math.Max(fontSize, ck.Font.Size); - // if (ck.Font.Size > 12) - // { - // ck.SetTextRise(-2f); - // //_MyLog.WarnFormat("set text rise"); - // } - // } - // return fontSize; - //} - // B2017-233, B2017-234 needed to get the smallest font size to help decide if a vertical adjustment of the text is needed in a table cell - //private float SmallestFontSize(Paragraph myPara) - //{ - // float fontSize = 30; - // foreach (Chunk ck in myPara.Chunks) - // { - // fontSize = Math.Min(fontSize, ck.Font.Size); - // } - // return fontSize; - //} - //private void ShowChunks(System.Collections.ArrayList chunks) // RHM20150429 - Table Scrunch - //{ - // StringBuilder sb = new StringBuilder(); - // foreach (Chunk chk in chunks) - // { - // sb.Append(BuildChunks(chk.Content)); - // } - // //if (ShowDetails) Console.WriteLine("Chunks = '{0}'", sb.ToString()); - //} private string BuildChunks(string str) { StringBuilder sb = new StringBuilder(); @@ -625,44 +452,25 @@ public string Path else sb.Append(c); } - return "{" + sb.ToString() + "}"; + return $"{{{sb}}}"; } private void TrimNewlines(Paragraph myPara) { while (myPara.Count > 0 && ParaEndsWithNewLine(myPara)) myPara.RemoveAt(myPara.Count - 1); } - private bool ParaEndsWithNewLine(Paragraph myPara) + private bool ParaEndsWithNewLine(Paragraph myPara) => myPara[myPara.Count - 1] is Chunk chk && chk.Content == "\n"; + internal static void FixHyphens(Paragraph myPara, vlnTable myTable) { - Chunk chk = myPara[myPara.Count - 1] as Chunk; - if (chk == null) return false; - if (chk.Content == "\n") return true; - return false; - } - public class VlnSplitCharacter : ISplitCharacter - { - public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) - { - return (cc[current] == ' '); - } - public bool IsSplitCharacter(char c) - { - return (c == ' '); - } - } - public static VlnSplitCharacter mySplitter = new VlnSplitCharacter(); - internal static void FixHyphens(Paragraph myPara, vlnTable myTable) - { - // Find chunk with hardhyphen + // Find chunk with hardhyphen - // If a hard hyphen is found, the remove it and add a dash (keyboard minus sign) to the beginning - // of the text that follows it. - int hype=-1; - Font fnt = null; - while ((hype = GetHyphen(myPara)) > -1) + // If a hard hyphen is found, the remove it and add a dash (keyboard minus sign) to the beginning + // of the text that follows it. + int hype; + while ((hype = GetHyphen(myPara)) > -1) { - fnt = null; - if (hype > 0) + Font fnt = null; + if (hype > 0) { Chunk chk1 = (Chunk)myPara[hype - 1]; if (hype > 1 && chk1.Content.Equals("\n")) @@ -750,16 +558,15 @@ public string Path internal static void FixBackslashes(Paragraph myPara, vlnTable myTable) { - // Find chunk with backslash B2014-108 backslash in tables + // Find chunk with backslash B2014-108 backslash in tables - // If a backslash symbold is found, the remove it and add a backslash (keyboard char) to the beginning - // of the text that follows it. - int bckSlsh = -1; - Font fnt = null; - while ((bckSlsh = GetBackslash(myPara)) > -1) + // If a backslash symbold is found, the remove it and add a backslash (keyboard char) to the beginning + // of the text that follows it. + int bckSlsh; + while ((bckSlsh = GetBackslash(myPara)) > -1) { - fnt = null; - if (bckSlsh > 0) + Font fnt = null; + if (bckSlsh > 0) { Chunk chk1 = (Chunk)myPara[bckSlsh - 1]; if (bckSlsh > 1 && chk1.Content.Equals("\n")) @@ -842,23 +649,17 @@ public string Path public static float CalculateHangingIndent(string rtf) { float chkW = 0; - // **** This is intened to be a temporary fix for V.C.Summer **** - // Two procedures would not print: A-2 SAG in Summer's SAMG set, and SAG-3 in Summer's PWOG DAMG set. - // These procedures have tables with hanging indents and use the Letter Gothic Tall font. - // It appears that the font information for the hanging indent character is not included in the RTF - // for those table cells. - // This piece of code checks for the existance of a font definition of \f1 which is need for the \u9999? indent character - // If the a font definition of \f1 is not found then the indent character is removed. This will allow the procedure to print - // but the text in that table cell will not be indented. - jsj 10/10/2014 - //IRtfDocument rtfDoc2 = RtfInterpreterTool.BuildDoc(rtf.Replace(@"\'05", @"\f1 \u9999? \f0 ")); - IRtfDocument rtfDoc2 = null; - //if (rtf.Contains(@"\f1\fnil\fcharset0 ")) - // rtfDoc2 = RtfInterpreterTool.BuildDoc(rtf.Replace(@"\'05", @"\f1 \u9999? \f0 ")); - //else - //{ - // first add the symbol font and then surround the indent as above. - rtfDoc2 = RtfInterpreterTool.BuildDoc(rtf.Replace(@"\'05", @"\par\u9999?\par")); - //} + // **** This is intened to be a temporary fix for V.C.Summer **** + // Two procedures would not print: A-2 SAG in Summer's SAMG set, and SAG-3 in Summer's PWOG DAMG set. + // These procedures have tables with hanging indents and use the Letter Gothic Tall font. + // It appears that the font information for the hanging indent character is not included in the RTF + // for those table cells. + // This piece of code checks for the existance of a font definition of \f1 which is need for the \u9999? indent character + // If the a font definition of \f1 is not found then the indent character is removed. This will allow the procedure to print + // but the text in that table cell will not be indented. - jsj 10/10/2014 + // add the symbol font and then surround the indent. + //IRtfDocument rtfDoc2 = RtfInterpreterTool.BuildDoc(rtf.Replace(@"\'05", @"\f1 \u9999? \f0 ")); + IRtfDocument rtfDoc2 = RtfInterpreterTool.BuildDoc(rtf.Replace(@"\'05", @"\par\u9999?\par")); Rtf2iTextSharp rtf2IText2 = new Rtf2iTextSharp(rtfDoc2); iTextSharp.text.Paragraph para2 = rtf2IText2.Convert(); @@ -883,7 +684,7 @@ public string Path return chkW; } - private static StepRTB _StatRTB = new StepRTB(); + private static readonly StepRTB _StatRTB = new StepRTB(); private string PreProcessRTF(float w, string str) { _StatRTB.Text = string.Empty; @@ -912,25 +713,7 @@ public string Path _StatRTB.Text = str; _StatRTB.SelectAll(); _StatRTB.SelectionColor = PrintOverride.OverrideTextColor(System.Drawing.Color.Black); - str = _StatRTB.Rtf; - // RHM 20180607 The following lines calculated line spacing but it did not give consistent values - //System.Drawing.Point location0 = _StatRTB.GetPositionFromCharIndex(0); - //int ii = 1; - //System.Drawing.Point locnext = location0; - //while (ii < 1000 && (locnext = _StatRTB.GetPositionFromCharIndex(ii)).Y == location0.Y) - // ii++; - //if (ii < 1000) - //{ - // myLeading = (locnext.Y - location0.Y) * 72.0F / 96.0F; - // Console.WriteLine("{0} - {1}", _StatRTB.Font, myLeading); - //} - //else - // myLeading = 12.0F; - // myLeading = 13.5F; // RHM 20180607 This worked for AEP - // RHM 20180607 The following did not work - //RTBAPI.ParaFormatTwo pft = RTBAPI.GetParaFormat(_StatRTB); - //myLeading = Math.Max(12.0F, pft.dyLineSpacing); - return str; + return _StatRTB.Rtf; } private iTextSharp.text.Paragraph RtfToParagraph(string rtf, iTextSharp.text.Font mySymFont,int r, int c) { @@ -940,10 +723,11 @@ public string Path rtf = rtf.Replace(@"\_", "-").Replace(@"\u8209?", "-"); rtf = FixRTFToPrint(rtf, r, c); IRtfDocument rtfDoc = RtfInterpreterTool.BuildDoc(rtf); - Rtf2iTextSharp rtf2IText = new Rtf2iTextSharp(rtfDoc); - rtf2IText.DefaultFont = mySymFont; - iTextSharp.text.Paragraph para = rtf2IText.Convert(); - //para.SetLeading(MyLeading , 0);// RHM 20180607 Not Needed - performed in SetupCells + Rtf2iTextSharp rtf2IText = new Rtf2iTextSharp(rtfDoc) + { + DefaultFont = mySymFont + }; + iTextSharp.text.Paragraph para = rtf2IText.Convert(); return para; } // The text font used in FixRTFToPrint for grid @@ -1011,7 +795,6 @@ public string Path // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 - //rtb.SelectionFont = new System.Drawing.Font(DefaultFont, fnt.Style); rtb.SelectionFont = VE_Font.GetWinSysFont(DefaultFont, fnt.Style); changed = true; } @@ -1027,8 +810,7 @@ public string Path { //use bolding underline italics from local font System.Drawing.Font fnt = rtb.SelectionFont; - //System.Drawing.Font fntw = new System.Drawing.Font((rc.Family != null) ? rc.Family : fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); - System.Drawing.Font fntw = VE_Font.GetWinSysFont((rc.Family != null) ? rc.Family : fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); + System.Drawing.Font fntw = VE_Font.GetWinSysFont(rc.Family ?? fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); rtb.SelectionFont = fntw; if (rc.Replace != null) { @@ -1047,7 +829,6 @@ public string Path } return rtf; } - private static float _SixLinesPerInch = 12; // twips #endregion #region Public Methods // C2021-005 Get the largest font size being used. @@ -1116,60 +897,20 @@ public string Path } public partial class vlnCell // RHM20150429 - Table Scrunch { - #region Properties - private vlnTable _MyTable; - public vlnTable MyTable - { - get { return _MyTable; } - set { _MyTable = value; } - } - public VlnBorders MyBorders - { - get { return _MyTable.MyBorders; } - } - private int _r1; - public int r1 - { - get { return _r1; } - set { _r1 = value; } - } - private int _c1; - public int c1 - { - get { return _c1; } - set { _c1 = value; } - } - private int _r2; - public int r2 - { - get { return _r2; } - set { _r2 = value; } - } - private int _c2; - public int c2 - { - get { return _c2; } - set { _c2 = value; } - } - private iTextSharp.text.Paragraph _MyPara; - public iTextSharp.text.Paragraph MyPara - { - get { return _MyPara; } - set { _MyPara = value; } - } - private float _HContent; - public float HContent - { - get { return _HContent; } - set { _HContent = value; } - } - public VlnGridCellShading MyShading - { - get { return _MyTable.MyShading; } - } - #endregion - #region Line Pattern Diagram - /* + #region Properties + public vlnTable MyTable { get; set; } + public VlnBorders MyBorders => MyTable.MyBorders; + + public int r1 { get; set; } + public int c1 { get; set; } + public int r2 { get; set; } + public int c2 { get; set; } + public iTextSharp.text.Paragraph MyPara { get; set; } + public float HContent { get; set; } + public VlnGridCellShading MyShading => MyTable.MyShading; + #endregion + #region Line Pattern Diagram + /* The diagram below identifies the various border names for the cell in the center |-AboveLeftSide |-AboveRightSide @@ -1192,9 +933,9 @@ public string Path |-BelowLeftSide |-BelowRightSide */ - #endregion - #region Horizontal Line Patterns - private GridLinePattern _TopSide = GridLinePattern.Unknown; + #endregion + #region Horizontal Line Patterns + private GridLinePattern _TopSide = GridLinePattern.Unknown; public GridLinePattern TopSide { get @@ -1408,27 +1149,27 @@ public string Path return _AboveLeftSide; } } - #endregion - #region Static Properties - private static float XOffset { get { return vlnTable.XOffset; } } - private static float YOffset { get { return vlnTable.YOffset; } } - private static float LineThicknessForThin { get { return vlnTable.LineThicknessForThin; } } - private static float LineThicknessForThick { get { return vlnTable.LineThicknessForThick; } } - private static float LineThicknessForDouble { get { return vlnTable.LineThicknessForDouble; } } - private static float DoubleLineOffset { get { return vlnTable.DoubleLineOffset; } } + #endregion + #region Static Properties + private static float XOffset => vlnTable.XOffset; + private static float YOffset => vlnTable.YOffset; + private static float LineThicknessForThin => vlnTable.LineThicknessForThin; + private static float LineThicknessForThick => vlnTable.LineThicknessForThick; + private static float LineThicknessForDouble => vlnTable.LineThicknessForDouble; + private static float DoubleLineOffset => vlnTable.DoubleLineOffset; - // adjustments for line intersections: - private static float ThickOverDouble { get { return ((2 * DoubleLineOffset) + LineThicknessForDouble - LineThicknessForThick) / 2; } } - private static float ThickUnderDouble { get { return DoubleLineOffset + (LineThicknessForThick - LineThicknessForDouble) / 2; } } - private static float ThickOverThin { get { return (LineThicknessForThin - LineThicknessForThick) / 2; } } - private static float ThinOverThick { get { return (LineThicknessForThick - LineThicknessForThin) / 2; } } - private static float ThinUnderDouble { get { return DoubleLineOffset + (LineThicknessForThin - LineThicknessForDouble) / 2; } } - private static float ThinOverDouble { get { return (DoubleLineOffset + LineThicknessForThin - LineThicknessForDouble) / 2; } } - private static float DoubleUnderThin { get { return (LineThicknessForThin - LineThicknessForDouble) / 2; } } - private static float DoubleUnderThick { get { return (LineThicknessForThick - LineThicknessForDouble) / 2; } } - #endregion - #region Constructors - public vlnCell(int r1, int c1, int r2, int c2, vlnTable myTable, iTextSharp.text.Paragraph myPara, float hContent) + // adjustments for line intersections: + private static float ThickOverDouble => ((2 * DoubleLineOffset) + LineThicknessForDouble - LineThicknessForThick) / 2; + private static float ThickUnderDouble => DoubleLineOffset + (LineThicknessForThick - LineThicknessForDouble) / 2; + private static float ThickOverThin => (LineThicknessForThin - LineThicknessForThick) / 2; + private static float ThinOverThick => (LineThicknessForThick - LineThicknessForThin) / 2; + private static float ThinUnderDouble => DoubleLineOffset + (LineThicknessForThin - LineThicknessForDouble) / 2; + private static float ThinOverDouble => (DoubleLineOffset + LineThicknessForThin - LineThicknessForDouble) / 2; + private static float DoubleUnderThin => (LineThicknessForThin - LineThicknessForDouble) / 2; + private static float DoubleUnderThick => (LineThicknessForThick - LineThicknessForDouble) / 2; + #endregion + #region Constructors + public vlnCell(int r1, int c1, int r2, int c2, vlnTable myTable, iTextSharp.text.Paragraph myPara, float hContent) { this.r1 = r1; this.c1 = c1; @@ -1438,19 +1179,14 @@ public string Path MyPara = myPara; HContent = hContent; } - #endregion - #region Public Methods - public override string ToString() - { - return string.Format("{0}:{1}", r1, c1); - } - // B2018-003 - RHM 20180319 Add - public void PdfDebug(iTextSharp.text.pdf.ColumnText myColumnText, float x, float bottom, float right, float y, string debugText, float yDescent) + #endregion + #region Public Methods + public override string ToString() => string.Format("{0}:{1}", r1, c1); + public void PdfDebug(iTextSharp.text.pdf.ColumnText myColumnText, float x, float bottom, float right, float y, string debugText, float yDescent) { PdfContentByte cb = myColumnText.Canvas; - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer debugLayer = _MyPageHelper == null ? null : _MyPageHelper.DebugLayer; - if (debugLayer == null) return; + PdfLayer debugLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.DebugLayer; + if (debugLayer == null) return; System.Drawing.Color sysColor = PrintOverride.OverrideDebugColor(System.Drawing.Color.Gray); cb.SaveState(); cb.BeginLayer(debugLayer); @@ -1481,7 +1217,6 @@ public string Path cb.EndLayer(); cb.RestoreState(); } - //RHM 20180319 End of Add // B2021-137 Added doShading parameter // We call this twice. The first time to print the shading the second time to print the borders and text public void ToPdf(iTextSharp.text.pdf.ColumnText myColumnText, float left, float top, int topPlacementAdjust, bool doShading) @@ -1518,7 +1253,6 @@ public string Path // B2019-093 missing table cell text when printing South Texas FSG-20 step 1 // Added two more to the last parameter of SetSimplColun (it's the ury value - upper y value) // this will have the cell text print a little more toward the top of the cell - //myColumnText1.SetSimpleColumn(1 + left + x, top - y - h, left + x + w - 2, 3 + top - y - hAdjust - adjustTextLocation); // 2 == Default Padding // B2019-109 Adjusted width of cell to match edit cell // B2020-034 - use the passed in topPlacementAdjust value which is set based on the font size. myColumnText1.SetSimpleColumn(.5F + left + x, top - y - h, left + x + w - 1.5F, topPlacementAdjust + top - y - hAdjust - adjustTextLocation); // 2 == Default Padding @@ -1566,7 +1300,6 @@ public string Path int cellStatus = myColumnText1.Go(); // B2019-109 Add to Error Log if cell too small if (cellStatus != 1) { - //System.Windows.Forms.MessageBox.Show("Cell width too narrow \r\n" + MyTable.Path, "Narrow Cell", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); _MyLog.WarnFormat("\r\n=-=-=-= Cell Width too narrow, text is wrapping ItemID={0} Location={1}, Row={2}, Col={3}, Status={4}",MyTable.ItemID, MyTable.Path, r1, c1, cellStatus); } float posAfter = myColumnText1.YLine; // RHM20150429 - Table Scrunch @@ -1606,7 +1339,6 @@ public string Path } return sb.ToString(); } - private static float _SixLinesPerInch = 12; // twips public bool IsRangeStyleNull = false; private TextAlignEnum? _TextAlign = null; public TextAlignEnum? TextAlign @@ -1635,7 +1367,6 @@ public string Path private float VeritcalTextAlignment(float h, float mult) { float hAdjust = 0; - //CellRange cr = MyTable.MyFlexGrid.GetCellRange(r1, c1, r2, c2); if (!IsRangeStyleNull) { switch (TextAlign) @@ -1913,28 +1644,10 @@ public string Path else if (linePattern == GridLinePattern.Dashed) cb.SetLineDash(4, 4, 0); } - private static void SetLineColor(PdfContentByte cb, int row, int col, string side) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping row and col for Debugging")] + private static void SetLineColor(PdfContentByte cb, int row, int col, string side) { iTextSharp.text.Color lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Black)); - //switch (side) - //{ - // case "Top": - // if (col == 0) lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Blue)); - // else lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Cyan)); - // break; - // case "Left": - // if (row == 0) lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Red)); - // else lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Magenta)); - // break; - // case "Bottom": - // if (col == 0) lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Green)); - // else lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Cyan)); - // break; - // case "Right": - // if (row == 0) lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Orange)); - // else lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Magenta)); - // break; - //} cb.SetColorStroke(lineColor); } private static void InitializeLineStyle(PdfContentByte cb) @@ -1946,9 +1659,11 @@ public string Path #region Debug Methods private static void SetOpacity(PdfContentByte cb, float opacity) { - PdfGState gs = new PdfGState(); - gs.StrokeOpacity = opacity; - cb.SetGState(gs); + PdfGState gs = new PdfGState + { + StrokeOpacity = opacity + }; + cb.SetGState(gs); } private static void ZoomToCell(iTextSharp.text.pdf.ColumnText myColumnText, float xLeft, float yTop, float xRight, float yBottom) { @@ -1956,141 +1671,5 @@ public string Path myColumnText.Canvas.SetAction(PdfAction.GotoLocalPage(myColumnText.Canvas.PdfWriter.CurrentPageNumber, dest, myColumnText.Canvas.PdfWriter), xLeft, yBottom, xRight, yTop); } #endregion - #region Old Border Methods - //private void DrawLeftLine(PdfContentByte cb, float xLeft, float yTop, float yBottom) - //{ - // if (c1 == 0 && LineLeft != GridLinePattern.None) - // { - // InitializeLineStyle(cb); - // SetLineColor(cb, r1, c1, "Left"); - // if (LineLeft == GridLinePattern.Double) - // { - // //Left Line - // float dyTop = DoubleIntersectionLeft(LineTopLeft, LineTop, LineLeftAbove); - // float dyBottom = -DoubleIntersectionRight(LineBottom, LineBottomLeft, LineLeftBelow); - // DrawLine(cb, LineThicknessForDouble, xLeft - DoubleLineOffset, yTop + dyTop, xLeft - DoubleLineOffset, yBottom + dyBottom); - // //Right Line - // dyTop = DoubleIntersectionRight(LineTopLeft, LineTop, LineLeftAbove); - // dyBottom = -DoubleIntersectionLeft(LineBottom, LineBottomLeft, LineLeftBelow); - // DrawLine(cb, LineThicknessForDouble, xLeft + DoubleLineOffset, yTop + dyTop, xLeft + DoubleLineOffset, yBottom + dyBottom); - // } - // else if (LineLeft != GridLinePattern.Thick) - // { - // SetLinePattern(cb, LineLeft); - // float dyTop = ThinIntersection(LineTopLeft, LineTop, LineLeftAbove); - // float dyBottom = -ThinIntersection(LineBottom, LineBottomLeft, LineLeftBelow); - // DrawLine(cb, LineThicknessForThin, xLeft, yTop + dyTop, xLeft, yBottom + dyBottom); - // } - // else - // { - // float dyTop = ThickIntersection(LineTopLeft, LineTop, LineLeftAbove); - // float dyBottom = -ThickIntersection(LineBottom, LineBottomLeft, LineLeftBelow); - // DrawLine(cb, LineThicknessForThick, xLeft, yTop + dyTop, xLeft, yBottom + dyBottom); - // } - // cb.Stroke(); - // } - //} - //private void DrawRightLine(PdfContentByte cb, float xRight, float yTop, float yBottom) - //{ - // if (LineRight != GridLinePattern.None) - // { - // InitializeLineStyle(cb); - // SetLineColor(cb, r1, c1, "Right"); - // if (LineRight == GridLinePattern.Double) - // { - // //Left Line - // float dyTop = DoubleIntersectionLeft(LineTop, LineTopRight, LineRightAbove); - // float dyBottom = -DoubleIntersectionRight(LineBottomRight, LineBottom, LineRightBelow); - // DrawLine(cb, LineThicknessForDouble, xRight - DoubleLineOffset, yTop + dyTop, xRight - DoubleLineOffset, yBottom + dyBottom); - // //Right Line - // dyTop = DoubleIntersectionRight(LineTop, LineTopRight, LineRightAbove); - // dyBottom = -DoubleIntersectionLeft(LineBottomRight, LineBottom, LineRightBelow); - // DrawLine(cb, LineThicknessForDouble, xRight + DoubleLineOffset, yTop + dyTop, xRight + DoubleLineOffset, yBottom + dyBottom); - // } - // else if (LineRight != GridLinePattern.Thick) - // { - // float dyTop = ThinIntersection(LineTop, LineTopRight, LineRightAbove); - // float dyBottom = -ThinIntersection(LineBottomRight, LineBottom, LineRightBelow); - // SetLinePattern(cb, LineRight); - // DrawLine(cb, LineThicknessForThin, xRight, yTop + dyTop, xRight, yBottom + dyBottom); - // } - // else - // { - // float dyTop = ThickIntersection(LineTop, LineTopRight, LineRightAbove); - // float dyBottom = -ThickIntersection(LineBottomRight, LineBottom, LineRightBelow); - // DrawLine(cb, LineThicknessForThick, xRight, yTop + dyTop, xRight, yBottom + dyBottom); - // } - // cb.Stroke(); - // } - //} - //private void DrawTopLine(PdfContentByte cb, float xLeft, float xRight, float yTop) - //{ - // if (r1 == 0 && TopSide != GridLinePattern.None) - // { - // InitializeLineStyle(cb); - // SetLineColor(cb, r1, c1, "Top"); - // if (TopSide == GridLinePattern.Double) - // { - // // Top Line - // float dxLeft = -DoubleIntersectionRight(LeftSide, AboveLeftSide, LeftOfTopSide); - // float dxRight = DoubleIntersectionLeft(AboveRightSide, RightSide, RightOfTopSide); - // DrawLine(cb, LineThicknessForDouble, xLeft + dxLeft, yTop + DoubleLineOffset, xRight + dxRight, yTop + DoubleLineOffset); - // // Bottom Line - // dxLeft = -DoubleIntersectionLeft(LeftSide, AboveLeftSide, LeftOfTopSide); - // dxRight = DoubleIntersectionRight(AboveRightSide, RightSide, RightOfTopSide); - // DrawLine(cb, LineThicknessForDouble, xLeft + dxLeft, yTop - DoubleLineOffset, xRight + dxRight, yTop - DoubleLineOffset); - // } - // else if (TopSide != GridLinePattern.Thick) - // { - // SetLinePattern(cb, TopSide); - // float dxLeft = -ThinIntersection(LeftSide, AboveLeftSide, LeftOfTopSide); - // float dxRight = ThinIntersection(AboveRightSide, RightSide, RightOfTopSide); - // DrawLine(cb, LineThicknessForThin, xLeft + dxLeft, yTop, xRight + dxRight, yTop); - // } - // else - // { - // float dxLeft = -ThickIntersection(LeftSide, AboveLeftSide, LeftOfTopSide); - // float dxRight = ThickIntersection(AboveRightSide, RightSide, RightOfTopSide); - // if (c1 == 0) - // Console.WriteLine("'{0}','{1}','{2}',{3},{4}", LeftSide, AboveLeftSide, LeftOfTopSide, dxLeft, ThickOverThin); - // DrawLine(cb, LineThicknessForThick, xLeft + dxLeft, yTop, xRight + dxRight, yTop); - // } - // cb.Stroke(); - // } - //} - //private void DrawBottomLine(PdfContentByte cb, float xLeft, float xRight, float yBottom) - //{ - // if (BottomSide != GridLinePattern.None) - // { - // InitializeLineStyle(cb); - // SetLineColor(cb, r1, c1, "Bottom"); - // if (BottomSide == GridLinePattern.Double) - // { - // // Top Line - // float dxLeft = -DoubleIntersectionRight(BelowLeftSide, LeftSide, LeftOfBottomSide); - // float dxRight = DoubleIntersectionLeft(RightSide, BelowRightSide, RightOfBottomSide); - // DrawLine(cb, LineThicknessForDouble, xLeft + dxLeft, yBottom + DoubleLineOffset, xRight + dxRight, yBottom + DoubleLineOffset);// Top Line - // // Bottom Line - // dxLeft = -DoubleIntersectionLeft(BelowLeftSide, LeftSide, LeftOfBottomSide); - // dxRight = DoubleIntersectionRight(RightSide, BelowRightSide, RightOfBottomSide); - // DrawLine(cb, LineThicknessForDouble, xLeft + dxLeft, yBottom - DoubleLineOffset, xRight + dxRight, yBottom - DoubleLineOffset);//Bottom Line - // } - // else if (BottomSide != GridLinePattern.Thick) // Bottom line is thin. Determine if intersecting with double: - // { - // SetLinePattern(cb, BottomSide); - // float dxLeft = -ThinIntersection(BelowLeftSide, LeftSide, LeftOfBottomSide); - // float dxRight = ThinIntersection(RightSide, BelowRightSide, RightOfBottomSide); - // DrawLine(cb, LineThicknessForThin, xLeft + dxLeft, yBottom, xRight + dxRight, yBottom); - // } - // else - // { - // float dxLeft = -ThickIntersection(BelowLeftSide, LeftSide, LeftOfBottomSide); - // float dxRight = ThickIntersection(RightSide, BelowRightSide, RightOfBottomSide); - // DrawLine(cb, LineThicknessForThick, xLeft + dxLeft, yBottom, xRight + dxRight, yBottom); - // } - // cb.Stroke(); - // } - //} - #endregion } } diff --git a/PROMS/Volian.Print.Library/MergedPdf.cs b/PROMS/Volian.Print.Library/MergedPdf.cs index 059c9919..e9ceb8f1 100644 --- a/PROMS/Volian.Print.Library/MergedPdf.cs +++ b/PROMS/Volian.Print.Library/MergedPdf.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; @@ -14,34 +13,15 @@ namespace Volian.Print.Library { public class MergedPdfProc { - private string _Title; - public string Title + public string Title { get; // used for pdf outline + set; } + public int PageCount { get; set; } + public string PdfFileName { get; set; } + public bool FirstPageNoPageNum { get; set; } = false; + public MergedPdfProc(string title, string pfname) { - get { return _Title; } // used for pdf outline - set { _Title = value; } - } - private int _PageCount; // number of pages in the particular pdf, to aid in determining total page count for merged pdf - public int PageCount - { - get { return _PageCount; } - set { _PageCount = value; } - } - private string _PdfFileName; // used for finding the procedure's pdf file to merge - public string PdfFileName - { - get { return _PdfFileName; } - set { _PdfFileName = value; } - } - private bool _FirstPageNoPageNum = false; - public bool FirstPageNoPageNum - { - get { return _FirstPageNoPageNum; } - set { _FirstPageNoPageNum = value; } - } - public MergedPdfProc(string title, string pfname) - { - _Title = title; - _PdfFileName = pfname; + Title = title; + PdfFileName = pfname; } } // this class will manage the data & do subsequent merging of pdf files. It is used if the user @@ -49,25 +29,11 @@ namespace Volian.Print.Library public class MergedPdf { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private List _mergedPdfs = null; // This list has all procedure pdfs that will be included in the merged file. - public List MergedPdfs - { - get { return _mergedPdfs; } - set { _mergedPdfs = value; } - } - string _mergedFileName = null; // this is the name to be given the merged file - public string MergedFileName - { - get { return _mergedFileName; } - set { _mergedFileName = value; } - } - private string _folder; // this is folder to create the merged file in - public string Folder - { - get { return _folder; } - set { _folder = value; } - } - private DocVersionInfo _docVersionInfo; + + public List MergedPdfs { get; set; } = null; + public string MergedFileName { get; set; } = null; + public string Folder { get; set; } + private readonly DocVersionInfo _docVersionInfo; private string _pageof = null; private iTextSharp.text.Font _itextFont = null; private MergedPdfsPageNumCorner _corner; @@ -80,11 +46,11 @@ namespace Volian.Print.Library // the following constructs the class that contains data for merging a group of pdfs. public MergedPdf(string folder, DocVersionInfo dvi) { - _folder = folder; + Folder = folder; _docVersionInfo = dvi; } // the following merges the procedure pdfs into a single pdf - public bool DoTheMerge(Dictionary> MergedLandscapPages, bool generatePointListFile) + public bool DoTheMerge(bool generatePointListFile) { if (MergedPdfs == null) { @@ -93,7 +59,7 @@ namespace Volian.Print.Library } iTextSharp.text.Document doc = new iTextSharp.text.Document(); string slashReplace = _docVersionInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SlashReplace ?? "_"; - MergedFileName = _folder + @"\" + _docVersionInfo.MyFolder.Name.Replace("/", slashReplace).Replace("\\", slashReplace) + ".pdf"; + MergedFileName = Folder + @"\" + _docVersionInfo.MyFolder.Name.Replace("/", slashReplace).Replace("\\", slashReplace) + ".pdf"; MergedFileName = ItemInfo.StripRtfFormatting(MergedFileName); // C2021-063 file name of Alarm Point List file containing Serial Number, Title, and merged Page Number StreamWriter sw = null; @@ -109,12 +75,12 @@ namespace Volian.Print.Library { writer = PdfWriter.GetInstance(doc, new FileStream(MergedFileName, FileMode.Create)); } - catch (Exception ex) - { + catch (Exception) + { StringBuilder sb = new StringBuilder(); sb.AppendLine("Could not create"); sb.AppendLine(); - sb.AppendLine(MergedFileName + "."); + sb.AppendLine($"{MergedFileName}."); sb.AppendLine(); sb.AppendLine("If it is open, close and retry."); FlexibleMessageBox.Show(sb.ToString(), "Error on CreatePdf", MessageBoxButtons.OK, MessageBoxIcon.Warning); @@ -136,7 +102,7 @@ namespace Volian.Print.Library // write Serial Number, Title, and Page Number in the Point List file sw.WriteLine("{0}\t{1}\t{2}", idxSerialNum++, mpp.Title, mergedPageNumber + 1); } - string pdffilename = _folder + @"\" + mpp.PdfFileName; + string pdffilename = $@"{Folder}\{mpp.PdfFileName}"; if (!File.Exists(pdffilename)) { FlexibleMessageBox.Show("Error in finding pdf files to merge. Cannot print with date/time as part of pdf name. Or check that individual pdfs were generated.", "Error on CreatePdf", MessageBoxButtons.OK, MessageBoxIcon.Warning); @@ -154,7 +120,7 @@ namespace Volian.Print.Library PdfReader reader = null; try // B2019-041: added a try/catch for when a corrupt pdf was created for a procedure, just skip & add message to error log. { - reader = new PdfReader(_folder + @"\" + mpp.PdfFileName); + reader = new PdfReader($@"{Folder}\{mpp.PdfFileName}"); int numPages = reader.NumberOfPages; int currentPageNumber = 0; PdfOutline outline = null; @@ -178,7 +144,7 @@ namespace Volian.Print.Library // if on the first page, add the pdfname & title as part of outline. If on remaining pages, just put out page number. // Later this may need expanded to put sections/steps/etc. if (currentPageNumber == 1) - outline = new PdfOutline(canvas.RootOutline, dest, mpp.PdfFileName.Replace(".pdf", "") + " - " + mpp.Title, false); + outline = new PdfOutline(canvas.RootOutline, dest, $"{mpp.PdfFileName.Replace(".pdf", "")} - {mpp.Title}", false); else new PdfOutline(outline, dest, "Page " + currentPageNumber.ToString(), false); canvas.AddTemplate(page, 0, 0); // adds the page to the combined pdf @@ -204,17 +170,13 @@ namespace Volian.Print.Library private void AddPageNumberToPage(PdfImportedPage page, PdfContentByte cb, string outputpage, bool landscape) { float pgright = page.BoundingBox.Right; - float pgleft = page.BoundingBox.Left; float pgtop = page.BoundingBox.Top; - float pgbot = page.BoundingBox.Bottom; MergedPdfsPageNumCorner cnr = _corner; // C2021-047: Allow for setting of Merged Pdf Landscape Page Number Location // B2019-152: Landscape page numbers when merging if (landscape) { pgright = page.BoundingBox.Top; - pgleft = page.BoundingBox.Bottom; pgtop = page.BoundingBox.Right; - pgbot = page.BoundingBox.Left; cnr = _landcorner; // C2021-047: Allow for setting of Merged Pdf Landscape Page Number Location } Phrase ph = new Phrase(); @@ -281,7 +243,7 @@ namespace Volian.Print.Library private bool GetPageOfInfo() { DocVersionConfig dvc = (DocVersionConfig) _docVersionInfo.MyConfig; - MergedPdfsPageOf po = dvc.Print_MergedPdfsPageOf; + _ = dvc.Print_MergedPdfsPageOf; string tmp = EnumDescConverter.GetEnumDescription((Enum)dvc.Print_MergedPdfsPageOf); if (tmp == "None") return false; // no page number, return false so no page number is put out. @@ -297,7 +259,7 @@ namespace Volian.Print.Library famtmp = _docVersionInfo.ActiveFormat.PlantFormat.FormatData.Font.Family; } tmp = dvc.Print_MergedPdfsPageNumFontSize; - float? tmpi=0; + float? tmpi; if (tmp == null || tmp == "") { // use the default from the format from this working draft diff --git a/PROMS/Volian.Print.Library/PDFChronologyReport.cs b/PROMS/Volian.Print.Library/PDFChronologyReport.cs index 73e7ca1e..c2f5c13c 100644 --- a/PROMS/Volian.Print.Library/PDFChronologyReport.cs +++ b/PROMS/Volian.Print.Library/PDFChronologyReport.cs @@ -26,36 +26,17 @@ namespace Volian.Print.Library return _AnnotationLookup; } } - private string _FileName; - public string FileName + + public string FileName { get; set; } + public ProcedureInfo MyProc { get; set; } + public ContentAuditInfoList AuditList { get; set; } + public AnnotationAuditInfoList AnnotationList { get; set; } + public PDFChronologyReport(string fileName, ProcedureInfo myProc, ContentAuditInfoList auditList, AnnotationAuditInfoList annotationList) { - get { return _FileName; } - set { _FileName = value; } - } - private ProcedureInfo _MyProc; - public ProcedureInfo MyProc - { - get { return _MyProc; } - set { _MyProc = value; } - } - private ContentAuditInfoList _AuditList; - public ContentAuditInfoList AuditList - { - get { return _AuditList; } - set { _AuditList = value; } - } - private AnnotationAuditInfoList _AnnotationList; - public AnnotationAuditInfoList AnnotationList - { - get { return _AnnotationList; } - set { _AnnotationList = value; } - } - public PDFChronologyReport(string fileName, ProcedureInfo myProc, ContentAuditInfoList auditList, AnnotationAuditInfoList annotationList) - { - _FileName = fileName; - _MyProc = myProc; - _AuditList = auditList; - _AnnotationList = annotationList; + FileName = fileName; + MyProc = myProc; + AuditList = auditList; + AnnotationList = annotationList; } public void BuildChronology() { @@ -68,7 +49,6 @@ namespace Volian.Print.Library } catch (Exception ex) { - StringBuilder msg = new StringBuilder(); document.Add(new Paragraph("Error:")); while (ex != null) { @@ -82,28 +62,22 @@ namespace Volian.Print.Library if (document.IsOpen()) { document.Close(); - System.Diagnostics.Process.Start(_FileName); + System.Diagnostics.Process.Start(FileName); } } } - public void BuildSummary() + public void BuildSummary() => BuildSummary(true); + public void BuildSummary(bool openReport) { - BuildSummary(true); - } - public void BuildSummary(bool openReport) - { - bool hasData = false; Rectangle paperSize = PDFPageSize.UsePaperSize(MyProc.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize); // C2020-002 paper size is now set in the format files iTextSharp.text.Document document = new iTextSharp.text.Document(paperSize, 36, 36, 36, 36); if (!CreateResultsPDF(document)) return; try { BuildSummaryReport(document); - //BuildSummaryReport2(document); } catch (Exception ex) { - StringBuilder msg = new StringBuilder(); document.Add(new Paragraph("Error:")); while (ex != null) { @@ -118,7 +92,7 @@ namespace Volian.Print.Library { document.Close(); if(openReport) - System.Diagnostics.Process.Start(_FileName); + System.Diagnostics.Process.Start(FileName); } } } @@ -129,12 +103,12 @@ namespace Volian.Print.Library int i = 0; // just for safety, the while loop expects to find a file extension // so make sure it has one before going into the loop - if (!_FileName.ToUpper().EndsWith(".PDF")) - _FileName += ".pdf"; + if (!FileName.ToUpper().EndsWith(".PDF")) + FileName += ".pdf"; // Try to open a file for creating the PDF. while (result == false) { - string fileName = _FileName; + string fileName = FileName; // Bug fix: B2013-086 // the folder path part of _FileName contained a folder name with a period // resulting is an invalid file location/file name. @@ -143,12 +117,10 @@ namespace Volian.Print.Library int loc = fileName.LastIndexOf("."); if (loc > -1) { - string fname = fileName.Substring(0, loc); - fileName = fname + suffix + ".pdf"; + fileName = $"{fileName.Substring(0, loc)}{suffix}.pdf"; } else - fileName = fileName + suffix + ".pdf"; -// string fileName = _FileName.ToLower().Replace(".pdf", suffix + ".pdf"); + fileName = $"{fileName}{suffix}.pdf"; try { PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); @@ -157,7 +129,7 @@ namespace Volian.Print.Library writer.PageEvent = new MyPageHelper("Procedure Changes"); document.SetMargins(36, 36, 36, 36); document.Open(); - _FileName = fileName; + FileName = fileName; result = true; } catch (System.IO.IOException exIO) @@ -196,51 +168,59 @@ namespace Volian.Print.Library } private PdfPCell BlankCell(int colSpan) { - PdfPCell c = new PdfPCell(); - c.Colspan = colSpan; - c.Border = 0; - return c; + PdfPCell c = new PdfPCell + { + Colspan = colSpan, + Border = 0 + }; + return c; } private void BuildChronologyReport(iTextSharp.text.Document doc) { int lastAnnotationID = 0; int cols = 5; - int borders = 0; int paddingBottom = 6; - PdfPTable t = new PdfPTable(cols); - t.HeaderRows = 4; - t.DefaultCell.Padding = 4; + PdfPTable t = new PdfPTable(cols) + { + HeaderRows = 4 + }; + t.DefaultCell.Padding = 4; t.WidthPercentage = 100; float[] widths = new float[] { 1f, 1f, 1f, 1f, 4f }; t.SetWidths(widths); - //t.HorizontalAlignment = 0; // C2017-036 get best available proportional font for symbols that looks close to Arial // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 9, 0, Color.BLACK); iTextSharp.text.Font f4 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 9, 1, Color.BLACK); - //report title - Phrase h = new Phrase(); - h.Font = f1; - h.Add("Chronology of Changes Report"); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + //report title + Phrase h = new Phrase + { + Font = f1 + }; + h.Add("Chronology of Changes Report"); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); - //procedure title - h = new Phrase(); - h.Font = f2; - h.Add(string.Format("{0} - {1}", MyProc.DisplayNumber, MyProc.DisplayText)); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + //procedure title + h = new Phrase + { + Font = f2 + }; + h.Add(string.Format("{0} - {1}", MyProc.DisplayNumber, MyProc.DisplayText)); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); string section = string.Empty; string stepnum = string.Empty; @@ -249,7 +229,6 @@ namespace Volian.Print.Library ContentAuditInfo oldCAI = null; string oldText = string.Empty; string oldTypeName = string.Empty; -// Dictionary processedAAI = new Dictionary(); Dictionary processedAAI = new Dictionary(); foreach (ContentAuditInfo cai in AuditList) { @@ -259,15 +238,18 @@ namespace Volian.Print.Library { AddStepAnnotation(ref lastAnnotationID, cols, paddingBottom, t, f3, f4, ref h, ref c, oldCAI, processedAAI); section = NewPath[0]; - h = new Phrase(); - h.Font = f4; - h.Add(section); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add(section); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); } //step @@ -286,16 +268,19 @@ namespace Volian.Print.Library // This was happening when we were reporting change information of a section number/title if (stepnum2 != "") { - h = new Phrase(); - h.Font = f3; - h.Add(string.Format("Step {0}", stepnum2)); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.PaddingRight = 10; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(string.Format("Step {0}", stepnum2)); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_RIGHT, + PaddingBottom = paddingBottom, + PaddingRight = 10 + }; + t.AddCell(c); } else t.AddCell(BlankCell(1)); @@ -304,44 +289,51 @@ namespace Volian.Print.Library t.AddCell(BlankCell(1)); //what if (cai.ContentID != lastID) maxDTS = DateTime.MinValue; - h = new Phrase(); - h.Font = f3; - string actionWhat = (cai.ActionWhat == "Added" && cai.DTS <= MyProc.ChangeBarDate) ? "Original" : cai.ActionWhat != "Changed" ? cai.ActionWhat : cai.DTS <= maxDTS ? "Restored" : cai.DTS > MyProc.ChangeBarDate ? cai.ActionWhat : "Original"; + h = new Phrase + { + Font = f3 + }; + string actionWhat = (cai.ActionWhat == "Added" && cai.DTS <= MyProc.ChangeBarDate) ? "Original" : cai.ActionWhat != "Changed" ? cai.ActionWhat : cai.DTS <= maxDTS ? "Restored" : cai.DTS > MyProc.ChangeBarDate ? cai.ActionWhat : "Original"; if (actionWhat == "Deleted" || actionWhat == "Restored") - h.Add(actionWhat + "\r\n" + (cai.ActionWhen < cai.DTS ? cai.DTS.ToString("M/dd/yyyy") : cai.ActionWhen.ToString())); + h.Add($"{actionWhat}\r\n{(cai.ActionWhen < cai.DTS ? cai.DTS.ToString("M/dd/yyyy") : cai.ActionWhen.ToString())}"); else h.Add(actionWhat); if (cai.DTS > maxDTS) maxDTS = cai.DTS; lastID = cai.ContentID; - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(cai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(cai.DTS.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - //h.Add(cai.Text); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(cai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(cai.DTS.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); if (cai.Type == 20008) { GridAuditInfoList gail = GridAuditInfoList.Get(cai.ContentID); @@ -351,7 +343,6 @@ namespace Volian.Print.Library GridAuditInfo gai = gail[0]; System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.LoadXml(gai.Data); - //int grows = int.Parse(xd.SelectSingleNode("C1FlexGrid/RowInfo/Count").InnerText); int gcols = int.Parse(xd.SelectSingleNode("C1FlexGrid/ColumnInfo/Count").InnerText); string data = ItemInfo.ConvertToDisplayText(cai.Text); PdfPTable gtbl = new PdfPTable(gcols); @@ -363,9 +354,11 @@ namespace Volian.Print.Library addedInfo = true; string val = data.Substring(0, data.IndexOf(";")); data = data.Substring(data.IndexOf(";") + 1); - Phrase hh = new Phrase(); - hh.Font = f4; - hh.Add(val); + Phrase hh = new Phrase + { + Font = f4 + }; + hh.Add(val); PdfPCell cc = new PdfPCell(hh); gtbl.AddCell(cc); } @@ -375,17 +368,21 @@ namespace Volian.Print.Library // If added info above, i.e. no error, put out the cell if (addedInfo) { - c = new PdfPCell(gtbl); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - t.AddCell(c); + c = new PdfPCell(gtbl) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT + }; + t.AddCell(c); } } if (!addedInfo) // Didn't add info, report that data not available { - h = new Phrase(); - h.Font = f4; - c = new PdfPCell(h); + h = new Phrase + { + Font = f4 + }; + c = new PdfPCell(h); h.Add("No Audit Details Available"); c.Colspan = cols - 4; c.HorizontalAlignment = Element.ALIGN_LEFT; @@ -395,12 +392,14 @@ namespace Volian.Print.Library } else { - h = new Phrase(); - h.Font = f4; - if (cai.Text != oldText && cai.TypeName != oldTypeName) - h.Add(string.Format("[Type Change {0} to {1}] - {2}", oldTypeName, cai.TypeName, ItemInfo.ConvertToDisplayText(cai.Text)));// + " to " + cai.TypeName); + h = new Phrase + { + Font = f4 + }; + if (cai.Text != oldText && cai.TypeName != oldTypeName) + h.Add(string.Format("[Type Change {0} to {1}] - {2}", oldTypeName, cai.TypeName, ItemInfo.ConvertToDisplayText(cai.Text))); else if (cai.Text == oldText && cai.TypeName != oldTypeName) - h.Add(oldTypeName + " to " + cai.TypeName); + h.Add($"{oldTypeName} to {cai.TypeName}"); else { string txt = null; @@ -450,22 +449,14 @@ namespace Volian.Print.Library oldCAI = cai; oldText = cai.Text; oldTypeName = cai.TypeName; - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } - ////old text - //t.AddCell(BlankCell(3)); - //h = new Phrase(); - //h.Font = f4; - //h.Add("Old text: " + cai.OldText); - //c = new PdfPCell(h); - //c.Colspan = 7; - //c.Border = 0; - //t.AddCell(c); } //see if any annotations for old stepnum here and add them foreach (AnnotationAuditInfo aai in AnnotationList) @@ -473,57 +464,67 @@ namespace Volian.Print.Library if (oldCAI != null && aai.IContentID == oldCAI.ContentID) { //add annotation to minilist -// processedAAI.Add(aai.AnnotationID, aai); if (!processedAAI.ContainsKey(aai)) // bug fix, only add to the processed list if it is not already in the list processedAAI.Add(aai, aai); //write row to table t.AddCell(BlankCell(1)); - h = new Phrase(); - h.Font = f3; - if (aai.AnnotationID != lastAnnotationID) + h = new Phrase + { + Font = f3 + }; + if (aai.AnnotationID != lastAnnotationID) { lastAnnotationID = aai.AnnotationID; - h.Add(AnnotationLookup[aai.TypeID] + " " + aai.ActionWhat); + h.Add($"{AnnotationLookup[aai.TypeID]} {aai.ActionWhat}"); } else h.Add(aai.ActionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(aai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(aai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(aai.ActionWhen.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //new text + h = new Phrase + { + Font = f4 + }; + h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } } bool annotationHeader = false; @@ -531,21 +532,23 @@ namespace Volian.Print.Library stepnum = string.Empty; foreach (AnnotationAuditInfo aai in AnnotationList) { -// if (!processedAAI.ContainsKey(aai.AnnotationID)) if (!processedAAI.ContainsKey(aai)) { if (!annotationHeader) { t.AddCell(BlankCell(cols)); - h = new Phrase(); - h.Font = f4; - h.Add("ANNOTATIONS"); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add("ANNOTATIONS"); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); annotationHeader = true; } @@ -554,90 +557,109 @@ namespace Volian.Print.Library { section = NewPath[0]; stepnum = string.Empty; - h = new Phrase(); - h.Font = f4; - h.Add(section); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add(section); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } if (NewPath[1] != stepnum) { stepnum = NewPath[1]; string stepnum2 = Regex.Replace(stepnum, "([0-9])[.]([A-Za-z])", "$1 $2"); stepnum2 = stepnum2.Replace("RNO.", "RNO"); - h = new Phrase(); - h.Font = f3; - h.Add(string.Format("Step {0}", stepnum2)); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.PaddingRight = 10; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(string.Format("Step {0}", stepnum2)); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_RIGHT, + PaddingBottom = paddingBottom, + PaddingRight = 10 + }; + t.AddCell(c); } else { t.AddCell(BlankCell(1)); } - //what - h = new Phrase(); - h.Font = f3; - if (aai.AnnotationID != lastAnnotationID) + //what + h = new Phrase + { + Font = f3 + }; + if (aai.AnnotationID != lastAnnotationID) { lastAnnotationID = aai.AnnotationID; - h.Add(AnnotationLookup[aai.TypeID] + " " + aai.ActionWhat); + h.Add($"{AnnotationLookup[aai.TypeID]} {aai.ActionWhat}"); } else h.Add(aai.ActionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(aai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(aai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(aai.ActionWhen.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //new text + h = new Phrase + { + Font = f4 + }; + h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } } if (t.Rows.Count == t.HeaderRows) { - c = new PdfPCell(new Phrase("No changes to report")); - c.Colspan = cols; - t.AddCell(c); + c = new PdfPCell(new Phrase("No changes to report")) + { + Colspan = cols + }; + t.AddCell(c); } doc.Add(t); } @@ -650,66 +672,75 @@ namespace Volian.Print.Library if (oldCAI != null && aai.IContentID == oldCAI.ContentID) { //add annotation to minilist - // processedAAI.Add(aai.AnnotationID, aai); if(processedAAI.ContainsKey(aai)) return; processedAAI.Add(aai, aai); //write row to table t.AddCell(BlankCell(1)); - h = new Phrase(); - h.Font = f3; - if (aai.AnnotationID != lastAnnotationID) + h = new Phrase + { + Font = f3 + }; + if (aai.AnnotationID != lastAnnotationID) { lastAnnotationID = aai.AnnotationID; - h.Add(AnnotationLookup[aai.TypeID] + " " + aai.ActionWhat); + h.Add($"{AnnotationLookup[aai.TypeID]} {aai.ActionWhat}"); } else h.Add(aai.ActionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(aai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(aai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(aai.ActionWhen.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //new text + h = new Phrase + { + Font = f4 + }; + h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } } } private static string[] SplitPath(string path) { // Remove Procedure Number and Title - string sectionAndStep = Regex.Replace(path + "\x7\x7\x7", "^.+?\\u0007", ""); - //sectionAndStep = sectionAndStep.Replace("\x11", sectionAndStep[0] == '\x11' ? "" : " - "); + string sectionAndStep = Regex.Replace($"{path}\x7\x7\x7", "^.+?\\u0007", ""); sectionAndStep = sectionAndStep.Replace("\x11", sectionAndStep[0] == '\x11' ? "" : " "); sectionAndStep = sectionAndStep.Replace("\\u160?", " "); // replace a hardspace with a space // Split Section frrom Steps @@ -729,327 +760,15 @@ namespace Volian.Print.Library } return "Section\x7Step".Split("\x7".ToCharArray()); } - private void BuildSummaryReport2(iTextSharp.text.Document doc) - { - string section = string.Empty; - string stepnum = string.Empty; - ContentAuditInfo firstCAI = null; - ContentAuditInfo nextCAI = null; - ContentAuditInfo lastCAI = null; - List auditList = new List(); - foreach (ContentAuditInfo cai in AuditList) - { - string[] NewPath = SplitPath(cai.Path); - if (NewPath[1] != stepnum) - { - stepnum = NewPath[1]; - if (firstCAI != null) - { - if (lastCAI == null) - { - auditList.Add(firstCAI); - } - else if (lastCAI.ActionWhat == "Deleted" && firstCAI.DTS < MyProc.ChangeBarDate) - { - auditList.Add(lastCAI); - } - else if (lastCAI.ActionWhat == "Changed" && lastCAI.Text != firstCAI.Text) - { - auditList.Add(firstCAI); - auditList.Add(lastCAI); - } - else if (lastCAI.ActionWhat == "Changed" && firstCAI.ActionWhat == "Added" && lastCAI.Text == firstCAI.Text) - { - auditList.Add(firstCAI); - } - else if (lastCAI == null && firstCAI.ActionWhat == "Added") - { - auditList.Add(firstCAI); - } - lastCAI = null; - } - firstCAI = cai; - } - else - { - lastCAI = cai; - } - } - if (firstCAI != null) - auditList.Add(firstCAI); - if (lastCAI != null) - auditList.Add(lastCAI); - #region annotations - AnnotationAuditInfo firstAAI = null; - AnnotationAuditInfo nextAAI = null; - AnnotationAuditInfo lastAAI = null; - int icontentID = 0; - List annotationList = new List(); - foreach (AnnotationAuditInfo aai in AnnotationList) - { - if (aai.IContentID != icontentID) - { - icontentID = aai.IContentID; - if (firstAAI != null) - { - if (lastAAI == null) - { - annotationList.Add(firstAAI); - } - else if (lastAAI.ActionWhat == "Deleted" && firstAAI.DTS < MyProc.ChangeBarDate) - { - annotationList.Add(lastAAI); - } - else if (lastAAI.ActionWhat == "Changed" && lastAAI.SearchText != firstAAI.SearchText) - { - annotationList.Add(firstAAI); - annotationList.Add(lastAAI); - } - else if (lastAAI.ActionWhat == "Changed" && firstAAI.ActionWhat == "Added" && lastAAI.SearchText == firstAAI.SearchText) - { - annotationList.Add(firstAAI); - } - else if (lastAAI == null && firstAAI.ActionWhat == "Added") - { - annotationList.Add(firstAAI); - } - lastAAI = null; - } - firstAAI = aai; - } - else - lastAAI = aai; - } - if (firstAAI != null) - annotationList.Add(firstAAI); - if (lastAAI != null) - annotationList.Add(lastAAI); - #endregion - int cols = 5; - int borders = 0; - int paddingBottom = 6; - PdfPTable t = new PdfPTable(cols); - t.HeaderRows = 4; - t.DefaultCell.Padding = 4; - t.WidthPercentage = 100; - float[] widths = new float[] { 1f, 1f, 1f, 1f, 4f }; - t.SetWidths(widths); - //t.HorizontalAlignment = 0; - // C2017-036 get best available proportional font for symbols that looks close to Arial. - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 9, 0, Color.BLACK); - iTextSharp.text.Font f4 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 9, 1, Color.BLACK); - //report title - Phrase h = new Phrase(); - h.Font = f1; - h.Add("Summary of Changes Report"); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - t.AddCell(BlankCell(cols)); - //procedure title - h = new Phrase(); - h.Font = f2; - h.Add(string.Format("{0} - {1}", MyProc.DisplayNumber, MyProc.DisplayText)); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - t.AddCell(BlankCell(cols)); - foreach (ContentAuditInfo cai in auditList) - { - //raw path - string[] NewPath = SplitPath(cai.Path); - if (NewPath[0] != section) - { - section = NewPath[0]; - h = new Phrase(); - h.Font = f4; - h.Add(section); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - t.AddCell(BlankCell(cols)); - } - //step - if (NewPath[1] != stepnum) - { - firstCAI = cai; - stepnum = NewPath[1]; - string stepnum2 = Regex.Replace(stepnum, "([0-9])[.]([A-Za-z])", "$1 $2"); - stepnum2 = stepnum2.Replace("RNO.", "RNO"); - h = new Phrase(); - h.Font = f3; - h.Add(string.Format("Step {0}", stepnum2)); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.PaddingRight = 10; - //c.Border = borders; - t.AddCell(c); - } - else - { - t.AddCell(BlankCell(1)); - nextCAI = cai; - } - //what - h = new Phrase(); - h.Font = f3; - h.Add(cai.ActionWhen > MyProc.ChangeBarDate ? cai.ActionWhat : "Original"); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(cai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(cai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(cai.Text)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - ////old text - //t.AddCell(BlankCell(3)); - //h = new Phrase(); - //h.Font = f4; - //h.Add("Old text: " + cai.OldText); - //c = new PdfPCell(h); - //c.Colspan = 7; - //c.Border = 0; - //t.AddCell(c); - } - t.AddCell(BlankCell(cols)); - h = new Phrase(); - h.Font = f4; - h.Add("ANNOTATIONS"); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - t.AddCell(BlankCell(cols)); - stepnum = string.Empty; - foreach (AnnotationAuditInfo aai in annotationList) - { - foreach (ContentAuditInfo cai in auditList) - { - if (cai.ContentID == aai.IContentID) - { - string[] NewPath = SplitPath(cai.Path); - if (NewPath[1] != stepnum) - { - stepnum = NewPath[1]; - string stepnum2 = Regex.Replace(stepnum, "([0-9])[.]([A-Za-z])", "$1 $2"); - stepnum2 = stepnum2.Replace("RNO.", "RNO"); - h = new Phrase(); - h.Font = f3; - h.Add(string.Format("Step {0}", stepnum2)); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.PaddingRight = 10; - //c.Border = borders; - t.AddCell(c); - break; - } - else - { - t.AddCell(BlankCell(1)); - break; - } - } - } - //what - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(aai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - } - doc.Add(t); - } - private void BuildSummaryReport(iTextSharp.text.Document doc) + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "firstCAI and lastCAI are re-used so good to set them back to null")] + private void BuildSummaryReport(iTextSharp.text.Document doc) { int lastAnnotationID = 0; string section = string.Empty; string stepnum = string.Empty; int contentID = 0; ContentAuditInfo firstCAI = null; - ContentAuditInfo nextCAI = null; ContentAuditInfo lastCAI = null; List auditList1 = new List(); foreach (ContentAuditInfo cai in AuditList) @@ -1105,7 +824,6 @@ namespace Volian.Print.Library } else if (firstCAI.ActionWhat == "Added" && lastCAI.ActionWhat == "Deleted" && firstCAI.DTS == lastCAI.DTS) { - //auditList.Add(lastCAI); firstCAI = null; lastCAI = null; } @@ -1116,14 +834,6 @@ namespace Volian.Print.Library firstCAI = null; lastCAI = null; } - //added by jcb - //else if (firstCAI.ActionWhat == "Added" && lastCAI.ActionWhat == "Changed" && firstCAI.DTS == lastCAI.DTS) - //{ - // auditList.Add(firstCAI); - // auditList.Add(lastCAI); - // firstCAI = null; - // lastCAI = null; - //} } } firstCAI = cai; @@ -1170,7 +880,6 @@ namespace Volian.Print.Library { if (lastCAI.ActionWhat == "Deleted" && firstCAI.DTS == lastCAI.DTS) { - //auditList.Add(lastCAI); firstCAI = null; lastCAI = null; } @@ -1185,7 +894,6 @@ namespace Volian.Print.Library } #region annotations commented out AnnotationAuditInfo firstAAI = null; - AnnotationAuditInfo nextAAI = null; AnnotationAuditInfo lastAAI = null; int annotationID = 0; List annotationList = new List(); @@ -1247,19 +955,19 @@ namespace Volian.Print.Library { annotationList.Add(lastAAI); } - else if (lastAAI.ActionWhat == "Changed" && firstAAI.ActionWhat != "Added") // && lastAAI.SearchText != firstAAI.SearchText) + else if (lastAAI.ActionWhat == "Changed" && firstAAI.ActionWhat != "Added") { annotationList.Add(firstAAI); annotationList.Add(lastAAI); } - else if (lastAAI.ActionWhat == "Changed" && firstAAI.ActionWhat == "Added") // && lastAAI.SearchText != firstAAI.SearchText) + else if (lastAAI.ActionWhat == "Changed" && firstAAI.ActionWhat == "Added") { lastAAI.ActionWhat = firstAAI.ActionWhat; annotationList.Add(lastAAI); firstAAI = null; lastAAI = null; } - else if (lastAAI.ActionWhat == "Restored" && firstAAI.ActionWhat == "Added") // && lastAAI.SearchText != firstAAI.SearchText) + else if (lastAAI.ActionWhat == "Restored" && firstAAI.ActionWhat == "Added") { lastAAI.ActionWhat = firstAAI.ActionWhat; annotationList.Add(lastAAI); @@ -1271,86 +979,87 @@ namespace Volian.Print.Library annotationList.Add(firstAAI); } } - //if (firstAAI != null) - // annotationList.Add(firstAAI); - //if (lastAAI != null) - // annotationList.Add(lastAAI); #endregion //new final cleanup List auditList2 = new List(); ContentAuditInfo caiFirst = null; foreach (ContentAuditInfo cai in auditList1) { - if (caiFirst == null) + if (caiFirst == null) caiFirst = cai; else { - if (cai.ContentID == caiFirst.ContentID && cai.Text != caiFirst.Text) - { - if (caiFirst.ActionWhat == "Added" && (cai.ActionWhat == "Added" || cai.ActionWhat == "Restored")) - { - auditList2.Add(cai); - caiFirst = null; - } - else - { - auditList2.Add(caiFirst); - auditList2.Add(cai); - caiFirst = null; - } - } - else - { - if(caiFirst.Text != string.Empty && !(caiFirst.UserID.Contains("Renumber") || cai.UserID.Contains("Renumber"))) - auditList2.Add(caiFirst); - caiFirst = cai; - } - } + if (cai.ContentID == caiFirst.ContentID && cai.Text != caiFirst.Text) + { + if (caiFirst.ActionWhat == "Added" && (cai.ActionWhat == "Added" || cai.ActionWhat == "Restored")) + { + auditList2.Add(cai); + caiFirst = null; + } + else + { + auditList2.Add(caiFirst); + auditList2.Add(cai); + caiFirst = null; + } + } + else + { + if(caiFirst.Text != string.Empty && !(caiFirst.UserID.Contains("Renumber") || cai.UserID.Contains("Renumber"))) + auditList2.Add(caiFirst); + caiFirst = cai; + } + } } if (caiFirst != null) //ciaFirst could end up being null at the end of the above foreach loop auditList2.Add(caiFirst); int cols = 5; - int borders = 0; int paddingBottom = 6; - PdfPTable t = new PdfPTable(cols); - t.HeaderRows = 4; - t.DefaultCell.Padding = 4; + PdfPTable t = new PdfPTable(cols) + { + HeaderRows = 4 + }; + t.DefaultCell.Padding = 4; t.WidthPercentage = 100; float[] widths = new float[] { 1f, 1f, 1f, 1f, 4f }; t.SetWidths(widths); - //t.HorizontalAlignment = 0; // C2017-036 get best available proportional font for symbols that looks close to Arial // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 9, 0, Color.BLACK); iTextSharp.text.Font f4 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 9, 1, Color.BLACK); - //report title - Phrase h = new Phrase(); - h.Font = f1; - h.Add("Summary of Changes Report"); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + //report title + Phrase h = new Phrase + { + Font = f1 + }; + h.Add("Summary of Changes Report"); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); - //procedure title - h = new Phrase(); - h.Font = f2; - h.Add(string.Format("{0} - {1}", MyProc.DisplayNumber, MyProc.DisplayText)); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + //procedure title + h = new Phrase + { + Font = f2 + }; + h.Add(string.Format("{0} - {1}", MyProc.DisplayNumber, MyProc.DisplayText)); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); ContentAuditInfo oldCAI = null; string oldText = string.Empty; string oldTypeName = string.Empty; - // Dictionary processedAAI = new Dictionary(); Dictionary processedAAI = new Dictionary(); foreach (ContentAuditInfo cai in auditList2) { @@ -1360,73 +1069,24 @@ namespace Volian.Print.Library { AddStepAnnotation(ref lastAnnotationID, cols, paddingBottom, t, f3, f4, ref h, ref c, oldCAI, processedAAI); section = NewPath[0]; - h = new Phrase(); - h.Font = f4; - h.Add(section); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add(section); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); } //step if (NewPath[1] != stepnum) { AddStepAnnotation(ref lastAnnotationID, cols, paddingBottom, t, f3, f4, ref h, ref c, oldCAI, processedAAI); - ////see if any annotations for old stepnum here and add them - //foreach (AnnotationAuditInfo aai in annotationList) - //{ - // if (oldCAI != null && aai.IContentID == oldCAI.ContentID) - // { - // //add annotation to minilist - // // processedAAI.Add(aai.AnnotationID, aai); - // processedAAI.Add(aai, aai); - // //write row to table - // t.AddCell(BlankCell(1)); - // h = new Phrase(); - // h.Font = f3; - // h.Add(AnnotationLookup[aai.TypeID] + " " + aai.ActionWhat); - // c = new PdfPCell(h); - // c.Colspan = 1; - // c.HorizontalAlignment = Element.ALIGN_CENTER; - // c.PaddingBottom = paddingBottom; - // //c.Border = borders; - // t.AddCell(c); - // //who - // h = new Phrase(); - // h.Font = f3; - // h.Add(aai.UserID); - // c = new PdfPCell(h); - // c.Colspan = 1; - // c.HorizontalAlignment = Element.ALIGN_CENTER; - // c.PaddingBottom = paddingBottom; - // //c.Border = borders; - // t.AddCell(c); - // //when - // h = new Phrase(); - // h.Font = f3; - // h.Add(aai.ActionWhen.ToString()); - // c = new PdfPCell(h); - // c.Colspan = 1; - // c.HorizontalAlignment = Element.ALIGN_CENTER; - // c.PaddingBottom = paddingBottom; - // //c.Border = borders; - // t.AddCell(c); - // //new text - // h = new Phrase(); - // h.Font = f4; - // //h.Add(cai.Text); - // h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - // c = new PdfPCell(h); - // c.Colspan = cols - 4; - // c.HorizontalAlignment = Element.ALIGN_LEFT; - // c.PaddingBottom = paddingBottom; - // //c.Border = borders; - // t.AddCell(c); - // } - //} oldCAI = cai; oldText = cai.Text; oldTypeName = cai.TypeName; @@ -1440,16 +1100,19 @@ namespace Volian.Print.Library // This was happening when we were reporting change information of a section number/title if (stepnum2 != "") { - h = new Phrase(); - h.Font = f3; - h.Add(string.Format("Step {0}", stepnum2)); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.PaddingRight = 10; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(string.Format("Step {0}", stepnum2)); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_RIGHT, + PaddingBottom = paddingBottom, + PaddingRight = 10 + }; + t.AddCell(c); } else t.AddCell(BlankCell(1)); @@ -1457,49 +1120,56 @@ namespace Volian.Print.Library else { t.AddCell(BlankCell(1)); - nextCAI = cai; } - //what - h = new Phrase(); - h.Font = f3; - // h.Add(cai.ActionWhen > MyProc.DTS ? cai.ActionWhat : "Original"); - string actionWhat = ((cai.ActionWhat == "Added" || cai.ActionWhat == "Changed") && cai.DTS <= MyProc.ChangeBarDate) ? "Original" : cai.ActionWhat; //(cai.ActionWhat == "Added" && cai.DTS <= MyProc.DTS) ? "Original" : cai.ActionWhat != "Changed" ? cai.ActionWhat : cai.DTS <= maxDTS ? "Restored" : cai.DTS > MyProc.DTS ? cai.ActionWhat : "Original"; + //what + h = new Phrase + { + Font = f3 + }; + string actionWhat = ((cai.ActionWhat == "Added" || cai.ActionWhat == "Changed") && cai.DTS <= MyProc.ChangeBarDate) ? "Original" : cai.ActionWhat; //(cai.ActionWhat == "Added" && cai.DTS <= MyProc.DTS) ? "Original" : cai.ActionWhat != "Changed" ? cai.ActionWhat : cai.DTS <= maxDTS ? "Restored" : cai.DTS > MyProc.DTS ? cai.ActionWhat : "Original"; if (actionWhat == "Deleted" || actionWhat == "Restored") - h.Add(actionWhat + "\r\n" + (cai.ActionWhen < cai.DTS ? cai.DTS.ToString("M/dd/yyyy") : cai.ActionWhen.ToString())); + h.Add($"{actionWhat}\r\n{(cai.ActionWhen < cai.DTS ? cai.DTS.ToString("M/dd/yyyy") : cai.ActionWhen.ToString())}"); else h.Add(actionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(cai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(cai.DTS.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - //h.Add(ItemInfo.ConvertToDisplayText(cai.Text)); - if (cai.Type == 20008) + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(cai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(cai.DTS.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //new text + h = new Phrase + { + Font = f4 + }; + if (cai.Type == 20008) { GridAuditInfoList gail = GridAuditInfoList.Get(cai.ContentID); bool addedInfo = false; @@ -1508,7 +1178,6 @@ namespace Volian.Print.Library GridAuditInfo gai = gail[0]; System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.LoadXml(gai.Data); - //int grows = int.Parse(xd.SelectSingleNode("C1FlexGrid/RowInfo/Count").InnerText); int gcols = int.Parse(xd.SelectSingleNode("C1FlexGrid/ColumnInfo/Count").InnerText); string data = ItemInfo.ConvertToDisplayText(cai.Text); PdfPTable gtbl = new PdfPTable(gcols); @@ -1520,9 +1189,11 @@ namespace Volian.Print.Library addedInfo = true; string val = data.Substring(0, data.IndexOf(";")); data = data.Substring(data.IndexOf(";") + 1); - Phrase hh = new Phrase(); - hh.Font = f4; - hh.Add(val); + Phrase hh = new Phrase + { + Font = f4 + }; + hh.Add(val); PdfPCell cc = new PdfPCell(hh); gtbl.AddCell(cc); } @@ -1531,36 +1202,42 @@ namespace Volian.Print.Library } if (addedInfo) { - c = new PdfPCell(gtbl); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - //c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + c = new PdfPCell(gtbl) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT + }; + t.AddCell(c); } } // B2017-058: The following was added to handle when there are no grid audits, just put a message. Without // adding this cell to the output, the columns get out of sync for rest of report. else { - h = new Phrase(); - h.Font = f4; - h.Add( "No change in table text found."); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add( "No change in table text found."); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } } else { - h = new Phrase(); - h.Font = f4; - if (cai.Text != oldText && cai.TypeName != oldTypeName) - h.Add(string.Format("[Type Change {0} to {1}] - {2}", oldTypeName, cai.TypeName, ItemInfo.ConvertToDisplayText(cai.Text)));// + " to " + cai.TypeName); + h = new Phrase + { + Font = f4 + }; + if (cai.Text != oldText && cai.TypeName != oldTypeName) + h.Add(string.Format("[Type Change {0} to {1}] - {2}", oldTypeName, cai.TypeName, ItemInfo.ConvertToDisplayText(cai.Text))); else if (cai.Text == oldText && cai.TypeName != oldTypeName) - h.Add(oldTypeName + " to " + cai.TypeName); + h.Add($"{oldTypeName} to {cai.TypeName}"); else { string txt = null; @@ -1612,30 +1289,14 @@ namespace Volian.Print.Library } oldText = cai.Text; oldTypeName = cai.TypeName; -// h.Add(ItemInfo.ConvertToDisplayText(cai.Text) + " " + cai.TypeName); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } - - //c = new PdfPCell(h); - //c.Colspan = cols - 4; - //c.HorizontalAlignment = Element.ALIGN_LEFT; - //c.PaddingBottom = paddingBottom; - ////c.Border = borders; - //t.AddCell(c); - ////old text - //t.AddCell(BlankCell(3)); - //h = new Phrase(); - //h.Font = f4; - //h.Add("Old text: " + cai.OldText); - //c = new PdfPCell(h); - //c.Colspan = 7; - //c.Border = 0; - //t.AddCell(c); } //see if any annotations for old stepnum here and add them foreach (AnnotationAuditInfo aai in annotationList) @@ -1643,64 +1304,63 @@ namespace Volian.Print.Library if (oldCAI != null && aai.IContentID == oldCAI.ContentID && !processedAAI.ContainsKey(aai)) { //add annotation to minilist - // processedAAI.Add(aai.AnnotationID, aai); processedAAI.Add(aai, aai); //write row to table t.AddCell(BlankCell(1)); - h = new Phrase(); - h.Font = f3; - h.Add(AnnotationLookup[aai.TypeID] + " " + aai.ActionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(aai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add($"{AnnotationLookup[aai.TypeID]} {aai.ActionWhat}"); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(aai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(aai.ActionWhen.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //new text + h = new Phrase + { + Font = f4 + }; + h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } } bool annotationHeader = false; - //t.AddCell(BlankCell(cols)); - //h = new Phrase(); - //h.Font = f4; - //h.Add("ANNOTATIONS"); - //c = new PdfPCell(h); - //c.Colspan = cols; - //c.HorizontalAlignment = Element.ALIGN_LEFT; - //c.PaddingBottom = paddingBottom; - ////c.Border = borders; - //t.AddCell(c); - //t.AddCell(BlankCell(cols)); section = string.Empty; stepnum = string.Empty; foreach (AnnotationAuditInfo aai in annotationList) @@ -1711,15 +1371,18 @@ namespace Volian.Print.Library if (!annotationHeader) { t.AddCell(BlankCell(cols)); - h = new Phrase(); - h.Font = f4; - h.Add("ANNOTATIONS"); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add("ANNOTATIONS"); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); annotationHeader = true; } @@ -1728,85 +1391,104 @@ namespace Volian.Print.Library { section = NewPath[0]; stepnum = string.Empty; - h = new Phrase(); - h.Font = f4; - h.Add(section); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f4 + }; + h.Add(section); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } if (NewPath[1] != stepnum) { stepnum = NewPath[1]; string stepnum2 = Regex.Replace(stepnum, "([0-9])[.]([A-Za-z])", "$1 $2"); stepnum2 = stepnum2.Replace("RNO.", "RNO"); - h = new Phrase(); - h.Font = f3; - h.Add(string.Format("Step {0}", stepnum2)); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.PaddingRight = 10; - //c.Border = borders; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(string.Format("Step {0}", stepnum2)); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_RIGHT, + PaddingBottom = paddingBottom, + PaddingRight = 10 + }; + t.AddCell(c); } else { t.AddCell(BlankCell(1)); } - //what - h = new Phrase(); - h.Font = f3; - - h.Add(AnnotationLookup[aai.TypeID] + " " + aai.ActionWhat); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //who - h = new Phrase(); - h.Font = f3; - h.Add(aai.UserID); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //when - h = new Phrase(); - h.Font = f3; - h.Add(aai.ActionWhen.ToString()); - c = new PdfPCell(h); - c.Colspan = 1; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); - //new text - h = new Phrase(); - h.Font = f4; - //h.Add(cai.Text); - h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); - c = new PdfPCell(h); - c.Colspan = cols - 4; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - //c.Border = borders; - t.AddCell(c); + //what + h = new Phrase + { + Font = f3 + }; + + h.Add($"{AnnotationLookup[aai.TypeID]} {aai.ActionWhat}"); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //who + h = new Phrase + { + Font = f3 + }; + h.Add(aai.UserID); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //when + h = new Phrase + { + Font = f3 + }; + h.Add(aai.ActionWhen.ToString()); + c = new PdfPCell(h) + { + Colspan = 1, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom + }; + t.AddCell(c); + //new text + h = new Phrase + { + Font = f4 + }; + h.Add(ItemInfo.ConvertToDisplayText(aai.SearchText)); + c = new PdfPCell(h) + { + Colspan = cols - 4, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } } if (t.Rows.Count == t.HeaderRows) { - c = new PdfPCell(new Phrase("No changes to report")); - c.Colspan = cols; - t.AddCell(c); + c = new PdfPCell(new Phrase("No changes to report")) + { + Colspan = cols + }; + t.AddCell(c); } doc.Add(t); } diff --git a/PROMS/Volian.Print.Library/PDFConsistencyCheckReport.cs b/PROMS/Volian.Print.Library/PDFConsistencyCheckReport.cs index ff5c357f..a1c4658b 100644 --- a/PROMS/Volian.Print.Library/PDFConsistencyCheckReport.cs +++ b/PROMS/Volian.Print.Library/PDFConsistencyCheckReport.cs @@ -6,35 +6,20 @@ using iTextSharp.text.pdf; using iTextSharp.text; using System.IO; using System.Text.RegularExpressions; -using System.Windows.Forms; +using System.Linq; namespace Volian.Print.Library { public class PDFConsistencyCheckReport { - private DocVersionInfo _MyDocVersion; - public DocVersionInfo MyDocVersion + public DocVersionInfo MyDocVersion { get; set; } + public string FileName { get; set; } + public ItemInfoList MyItemInfoList { get; set; } + public PDFConsistencyCheckReport(string fileName, ItemInfoList myItemInfoList, DocVersionInfo myDocVersion) { - get { return _MyDocVersion; } - set { _MyDocVersion = value; } - } - private string _FileName; - public string FileName - { - get { return _FileName; } - set { _FileName = value; } - } - private ItemInfoList _MyItemInfoList; - public ItemInfoList MyItemInfoList - { - get { return _MyItemInfoList; } - set { _MyItemInfoList = value; } - } - public PDFConsistencyCheckReport(string fileName, ItemInfoList myItemInfoList, DocVersionInfo myDocVersion) - { - _FileName = fileName; - _MyItemInfoList = myItemInfoList; - _MyDocVersion = myDocVersion; //B2020-020 needed to pass in DocVersion to get paper size from format + FileName = fileName; + MyItemInfoList = myItemInfoList; + MyDocVersion = myDocVersion; //B2020-020 needed to pass in DocVersion to get paper size from format } public void BuildReport() { @@ -47,7 +32,6 @@ namespace Volian.Print.Library } catch (Exception ex) { - StringBuilder msg = new StringBuilder(); document.Add(new Paragraph("Error:")); while (ex != null) { @@ -61,7 +45,7 @@ namespace Volian.Print.Library if (document.IsOpen()) { document.Close(); - System.Diagnostics.Process.Start(_FileName); + System.Diagnostics.Process.Start(FileName); } } } @@ -73,13 +57,13 @@ namespace Volian.Print.Library // Try to open a file for creating the PDF. while (result == false) { - string fileName = _FileName.ToLower().Replace(".pdf", suffix + ".pdf"); + string fileName = FileName.ToLower().Replace(".pdf", suffix + ".pdf"); try { PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); document.SetMargins(36, 36, 36, 36); document.Open(); - _FileName = fileName; + FileName = fileName; result = true; } catch (System.IO.IOException exIO) @@ -118,10 +102,12 @@ namespace Volian.Print.Library } private PdfPCell BlankCell(int colSpan) { - PdfPCell c = new PdfPCell(); - c.Colspan = colSpan; - c.Border = 0; - return c; + PdfPCell c = new PdfPCell + { + Colspan = colSpan, + Border = 0 + }; + return c; } private void BuildConsistencyReport(iTextSharp.text.Document doc) { @@ -132,7 +118,6 @@ namespace Volian.Print.Library iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 8, 0, Color.BLACK); iTextSharp.text.Font f4 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 2, Color.BLACK); int cols = 5; - int borders = 0; int paddingBottom = 6; // float[] widths; Csla.SortedBindingList sortedProcs = new Csla.SortedBindingList(MyItemInfoList); @@ -141,7 +126,7 @@ namespace Volian.Print.Library // B2019-024: First page of Report prints the title at the top and the remainder of the page is blank. // Check if procedure(s) are printed on that page and if not, change message to "No..." and don't do // pagebreak. - foreach (ProcedureInfo pi in sortedProcs) + foreach (ProcedureInfo pi in sortedProcs.OfType()) { if (pi.IsSelected) { @@ -160,17 +145,21 @@ namespace Volian.Print.Library lbSrchResults.DataSource = sortedResults; */ - foreach (ProcedureInfo pi in sortedProcs) + foreach (ProcedureInfo pi in sortedProcs.OfType()) { if (pi.IsSelected) { - PdfPTable tt = new PdfPTable(cols); - tt.KeepTogether = true; - tt.AddCell(AddSubTableCell(pi.DisplayNumber, f2, cols, paddingBottom)); + PdfPTable tt = new PdfPTable(cols) + { + KeepTogether = true + }; + tt.AddCell(AddSubTableCell(pi.DisplayNumber, f2, cols, paddingBottom)); tt.AddCell(AddSubTableCell(pi.MyDifferencesText, f3, cols, paddingBottom)); - PdfPCell c = new PdfPCell(tt); - c.Colspan = cols; - t.AddCell(c); + PdfPCell c = new PdfPCell(tt) + { + Colspan = cols + }; + t.AddCell(c); } } t.AddCell(BlankCell(cols)); @@ -179,60 +168,76 @@ namespace Volian.Print.Library if (didSome) doc.NewPage(); t = CreatePdfPTable(cols); CreatePageHeader(t, f1, f4, cols, paddingBottom, "Approval Consistency Report", "Procedures that should be selected to be approved in order to maintain consistency"); - foreach (ProcedureInfo pi in MyItemInfoList) + foreach (ProcedureInfo pi in MyItemInfoList.OfType()) { if (!pi.IsSelected) { - PdfPTable tt = new PdfPTable(cols); - tt.KeepTogether = true; - tt.AddCell(AddSubTableCell(pi.DisplayNumber, f2, cols, paddingBottom)); + PdfPTable tt = new PdfPTable(cols) + { + KeepTogether = true + }; + tt.AddCell(AddSubTableCell(pi.DisplayNumber, f2, cols, paddingBottom)); tt.AddCell(AddSubTableCell(pi.MyDifferencesText, f3, cols, paddingBottom)); - PdfPCell c = new PdfPCell(tt); - c.Colspan = cols; - t.AddCell(c); + PdfPCell c = new PdfPCell(tt) + { + Colspan = cols + }; + t.AddCell(c); } } doc.Add(t); } private PdfPCell AddSubTableCell(string text, iTextSharp.text.Font f, int cols, float pb) { - Phrase h = new Phrase(); - h.Font = f; - h.Add(text); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = pb; - return c; + Phrase h = new Phrase + { + Font = f + }; + h.Add(text); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = pb + }; + return c; } private void CreatePageHeader(PdfPTable t, iTextSharp.text.Font f1, iTextSharp.text.Font f2, int cols, float pb, string hdr1, string hdr2) { - //report title - Phrase h = new Phrase(); - h.Font = f1; - h.Add(hdr1); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = pb; - //c.Border = borders; - t.AddCell(c); - h = new Phrase(); - h.Font = f2; - h.Add(hdr2); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = pb; - //c.Border = borders; - t.AddCell(c); + //report title + Phrase h = new Phrase + { + Font = f1 + }; + h.Add(hdr1); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = pb + }; + t.AddCell(c); + h = new Phrase + { + Font = f2 + }; + h.Add(hdr2); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = pb + }; + t.AddCell(c); t.AddCell(BlankCell(cols)); } private PdfPTable CreatePdfPTable(int cols) { - PdfPTable t = new PdfPTable(cols); - t.HeaderRows = 3; - t.DefaultCell.Padding = 4; + PdfPTable t = new PdfPTable(cols) + { + HeaderRows = 3 + }; + t.DefaultCell.Padding = 4; t.WidthPercentage = 100; float[] widths = new float[] { 1f, 1f, 1f, 1f, 4f }; t.SetWidths(widths); @@ -251,7 +256,6 @@ namespace Volian.Print.Library } catch (Exception ex) { - StringBuilder msg = new StringBuilder(); document.Add(new Paragraph("Error:")); while (ex != null) { @@ -265,7 +269,7 @@ namespace Volian.Print.Library if (document.IsOpen()) { document.Close(); - System.Diagnostics.Process.Start(_FileName); + System.Diagnostics.Process.Start(FileName); } } } @@ -276,33 +280,40 @@ namespace Volian.Print.Library iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 1, Color.BLACK); iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 8, 0, Color.BLACK); - iTextSharp.text.Font f4 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 2, Color.BLACK); int cols = 3; - int borders = 0; - int paddingBottom = 6; - PdfPTable t = new PdfPTable(cols); - t.HeaderRows = 1; - t.WidthPercentage = 100; - float[] widths = new float[] { 1f, 1f, 10f }; + PdfPTable t = new PdfPTable(cols) + { + HeaderRows = 1, + WidthPercentage = 100 + }; + float[] widths = new float[] { 1f, 1f, 10f }; t.SetWidths(widths); - Phrase h = new Phrase(); - h.Font = f1; - h.Add("Approved Procedures Inconsistencies Report"); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = 1; - t.AddCell(c); - // C2021-013: Include the Procedure set name & date - h = new Phrase(); - h.Font = f1; - string tmp = MyDocVersion.MyFolder.Name + " " + DateTime.Now.ToString("M/d/yyyy"); + Phrase h = new Phrase + { + Font = f1 + }; + h.Add("Approved Procedures Inconsistencies Report"); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = 1 + }; + t.AddCell(c); + // C2021-013: Include the Procedure set name & date + h = new Phrase + { + Font = f1 + }; + string tmp = MyDocVersion.MyFolder.Name + " " + DateTime.Now.ToString("M/d/yyyy"); h.Add(tmp); - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = 1; - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = 1 + }; + t.AddCell(c); Dictionary types = new Dictionary(); - foreach (ProcedureInfo pi in MyItemInfoList) + foreach (ProcedureInfo pi in MyItemInfoList.OfType()) { string type = pi.MyDifferences.ROConsistency.MyROChecks.Length > 0 ? "Reference Object Inconsistencies" : ""; if (type != string.Empty && !types.ContainsKey(0)) @@ -314,15 +325,18 @@ namespace Volian.Print.Library if (type != string.Empty && !types.ContainsKey(2)) types.Add(2, type); } -// types.Clear(); if (types.Count == 0) { - h = new Phrase(); - h.Font = f2; - h.Add("No Inconsistencies"); - c = new PdfPCell(h); - c.Colspan = cols; - t.AddCell(c); + h = new Phrase + { + Font = f2 + }; + h.Add("No Inconsistencies"); + c = new PdfPCell(h) + { + Colspan = cols + }; + t.AddCell(c); } else { @@ -335,7 +349,7 @@ namespace Volian.Print.Library ROFSTLookup lu = rofst.GetROFSTLookup(dvi); if (types.ContainsKey(0)) { - foreach (ProcedureInfo pi in MyItemInfoList) + foreach (ProcedureInfo pi in MyItemInfoList.OfType()) { foreach (ROCheck roc in pi.MyDifferences.ROConsistency.MyROChecks) { @@ -364,7 +378,7 @@ namespace Volian.Print.Library //Dictionary> trs = new Dictionary>(); if (types.ContainsKey(1)) { - foreach (ProcedureInfo pi in MyItemInfoList) + foreach (ProcedureInfo pi in MyItemInfoList.OfType()) { foreach (TransitionCheck trc in pi.MyDifferences.TransitionConsistency.MyTransitionChecks) { @@ -397,7 +411,7 @@ namespace Volian.Print.Library //Dictionary> lds = new Dictionary>(); if (types.ContainsKey(2)) { - foreach (ProcedureInfo pi in MyItemInfoList) + foreach (ProcedureInfo pi in MyItemInfoList.OfType()) { foreach (LibDocCheck ldc in pi.MyDifferences.LibDocConsistency.MyLibDocChecks) { @@ -420,28 +434,38 @@ namespace Volian.Print.Library Color badColor = new Color(System.Drawing.Color.Khaki); if (types.ContainsKey(0)) { - h = new Phrase(); - h.Font = f2; - h.Add(types[0]); - c = new PdfPCell(h); - c.Colspan = cols; - t.AddCell(c); + h = new Phrase + { + Font = f2 + }; + h.Add(types[0]); + c = new PdfPCell(h) + { + Colspan = cols + }; + t.AddCell(c); foreach (string rotitle in ros.Keys) { t.AddCell(BlankCell(1)); - h = new Phrase(); - h.Font = f3; - h.Add(rotitle); - c = new PdfPCell(h); - c.Colspan = cols - 1; - c.BackgroundColor = goodColor; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(rotitle); + c = new PdfPCell(h) + { + Colspan = cols - 1, + BackgroundColor = goodColor + }; + t.AddCell(c); foreach (KeyValuePair d in ros[rotitle]) { t.AddCell(BlankCell(2)); - h = new Phrase(); - h.Font = f3; - h.Add(d.Key); + h = new Phrase + { + Font = f3 + }; + h.Add(d.Key); c = new PdfPCell(h); if (d.Value) c.BackgroundColor = goodColor; @@ -451,31 +475,40 @@ namespace Volian.Print.Library } } } -//jcb if (types.ContainsKey(1)) { - h = new Phrase(); - h.Font = f2; - h.Add(types[1]); - c = new PdfPCell(h); - c.Colspan = cols; - t.AddCell(c); + h = new Phrase + { + Font = f2 + }; + h.Add(types[1]); + c = new PdfPCell(h) + { + Colspan = cols + }; + t.AddCell(c); foreach (string trtitle in trs.Keys) { t.AddCell(BlankCell(1)); - h = new Phrase(); - h.Font = f3; - h.Add(trtitle); - c = new PdfPCell(h); - c.Colspan = cols - 1; - c.BackgroundColor = goodColor; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(trtitle); + c = new PdfPCell(h) + { + Colspan = cols - 1, + BackgroundColor = goodColor + }; + t.AddCell(c); foreach (KeyValuePair d in trs[trtitle]) { t.AddCell(BlankCell(2)); - h = new Phrase(); - h.Font = f3; - h.Add(d.Key); + h = new Phrase + { + Font = f3 + }; + h.Add(d.Key); c = new PdfPCell(h); if (d.Value) c.BackgroundColor = goodColor; @@ -488,28 +521,38 @@ namespace Volian.Print.Library //end jcb if (types.ContainsKey(2)) { - h = new Phrase(); - h.Font = f2; - h.Add(types[2]); - c = new PdfPCell(h); - c.Colspan = cols; - t.AddCell(c); + h = new Phrase + { + Font = f2 + }; + h.Add(types[2]); + c = new PdfPCell(h) + { + Colspan = cols + }; + t.AddCell(c); foreach (string ldtitle in lds.Keys) { t.AddCell(BlankCell(1)); - h = new Phrase(); - h.Font = f3; - h.Add(ldtitle); - c = new PdfPCell(h); - c.Colspan = cols - 1; - c.BackgroundColor = goodColor; - t.AddCell(c); + h = new Phrase + { + Font = f3 + }; + h.Add(ldtitle); + c = new PdfPCell(h) + { + Colspan = cols - 1, + BackgroundColor = goodColor + }; + t.AddCell(c); foreach (KeyValuePair d in lds[ldtitle]) { t.AddCell(BlankCell(2)); - h = new Phrase(); - h.Font = f3; - h.Add(d.Key); + h = new Phrase + { + Font = f3 + }; + h.Add(d.Key); c = new PdfPCell(h); if (d.Value) c.BackgroundColor = goodColor; diff --git a/PROMS/Volian.Print.Library/PDFPageSize.cs b/PROMS/Volian.Print.Library/PDFPageSize.cs index d294ceab..c4db26d2 100644 --- a/PROMS/Volian.Print.Library/PDFPageSize.cs +++ b/PROMS/Volian.Print.Library/PDFPageSize.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using VEPROMS.CSLA.Library; +using System.Collections.Generic; using iTextSharp.text; @@ -11,9 +6,11 @@ namespace Volian.Print.Library { public class PDFPageSize { - // C2020-002 paper size is now set in the format files - this class is use to select the page size that PROMS should be using - private static Dictionary dicPDFPageSize = new Dictionary(); - private static Dictionary dicPDFPageSizePnts = new Dictionary(); + // C2020-002 paper size is now set in the format files - this class is use to select the page size that PROMS should be using + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary dicPDFPageSize = new Dictionary(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static Dictionary dicPDFPageSizePnts = new Dictionary(); private static void BuildPDFPageSizeDic() { // the page size is set in the format files using a string description i.e.: diff --git a/PROMS/Volian.Print.Library/PDFReport.cs b/PROMS/Volian.Print.Library/PDFReport.cs index e660630e..2fec6f98 100644 --- a/PROMS/Volian.Print.Library/PDFReport.cs +++ b/PROMS/Volian.Print.Library/PDFReport.cs @@ -1,2018 +1,1967 @@ -using System; -using System.Collections.Generic; -using System.Text; -using VEPROMS.CSLA.Library; -using iTextSharp.text.pdf; using iTextSharp.text; -using System.IO; -using System.Text.RegularExpressions; +using iTextSharp.text.pdf; +using System; using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using VEPROMS.CSLA.Library; namespace Volian.Print.Library { - // B2022-026 New code for RO Memory reduction - now use SQL tables instead of building dictionarys to get RO values - public class PDFReport - { - #region Enums - - public enum ReportType - { - SearchResults = 0, - LibraryDocUsage = 1, - ReferencedObjectsUsage = 2, - TransitionUsage = 3, - ReferencedObjectSummary = 4, - ReferencedObjectComplete = 5 - } - - #endregion - - #region Fields - - private PdfWriter _MyPdfWriter; - private ICollection _ResultList; - - private string _FileName; - private string _ReportTitle; - private string _TypesSelected; - private bool _ShowAnnotations = true; - private string _SearchString; - private string _SortedBy; // C2019-013 pass in sorting information - private DocumentInfoList _LibDocList; - - private int _ReportType = 0; - private string _ByLine; - private bool _SortUsageByProcedure = false; - private string _RODataFile = string.Empty; - private List _ROList; - private ROFSTLookup _ROFSTLookup; - private bool _IncludeMissingROs = false; - private bool _ConvertCaretToDelta = true; - private bool _IncludeEmptyROFields = false; - - private string _PaperSize = "Letter"; // C2020-002 paper size is now set in the format files - private string _RegexSearchString = null; - private ArrayList ProcSetList; - - #endregion - - #region Properties - - public ICollection ResultList - { - get { return _ResultList; } - set { _ResultList = value; } - } - - public string FileName - { - get { return _FileName; } - set { _FileName = value; } - } - - public string ReportTitle - { - get { return _ReportTitle; } - set { _ReportTitle = value; } - } - - public string TypesSelected - { - get { return _TypesSelected; } - set { _TypesSelected = value; } - } - - public bool ShowAnnotations - { - get { return _ShowAnnotations; } - set { _ShowAnnotations = value; } - } - - public string SearchString - { - get { return _SearchString; } - set { _SearchString = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(value); } - } - - public string SortedBy - { - get { return _SortedBy; } - set { _SortedBy = value; } - } - - public DocumentInfoList LibDocList - { - get { return _LibDocList; } - set { _LibDocList = value; } - } - - private string RegexSearchString - { - get - { - if (_RegexSearchString == null) - { - _RegexSearchString = _SearchString; - - // Make it match the smallest matching string - _RegexSearchString = _RegexSearchString.Replace("*", ".*?"); - - // If search string starts with a wildcard use the beginning of line token (^) - if (_RegexSearchString.StartsWith(".*?")) - { - _RegexSearchString = "^" + _RegexSearchString; - } - - // If search string ends with a wildcard use the end of line token ($) - if (_RegexSearchString.EndsWith(".*?")) - { - _RegexSearchString = _RegexSearchString + "$"; - } - - _RegexSearchString = _RegexSearchString.Replace("[", @"\["); - _RegexSearchString = _RegexSearchString.Replace("]", @"\]"); - _RegexSearchString = _RegexSearchString.Replace("(", @"\("); - _RegexSearchString = _RegexSearchString.Replace(")", @"\)"); - } - - return _RegexSearchString; - } - } - - #endregion - - #region Constructors - - /// - /// Search Results Report - /// - /// - /// - /// - /// - /// - /// - public PDFReport(string reportTitle, string typesSelected, ICollection resultList, string fileName, string paperSize, string sortedBy) - { - _ResultList = resultList; - _FileName = fileName; - _ReportTitle = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(reportTitle); - _TypesSelected = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(typesSelected); - _ReportType = (int)ReportType.SearchResults; - _ByLine = "PROMS Search Results"; - _PaperSize = paperSize; - _SortedBy = sortedBy; // C2019--13 pass in sorted by information - - } - - /// - /// Library Document Report - /// - /// - /// - /// - /// - public PDFReport(string reportTitle, DocumentInfoList libDocList, string fileName, string paperSize) - { - _LibDocList = libDocList; - _FileName = fileName; - _ReportTitle = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(reportTitle); - _ReportType = (int)ReportType.LibraryDocUsage; - _ByLine = "Generated By PROMS"; - _PaperSize = paperSize; - } - - /// - /// RO Usage - /// - /// - /// - /// - /// - /// - /// - public PDFReport(string reportTitle, ICollection resultList, string fileName, bool sortUsageByProcedure, bool includeMissingROs, string paperSize) - { - _ResultList = resultList; - _FileName = fileName; - _ReportTitle = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(reportTitle); - _ReportType = (int)ReportType.ReferencedObjectsUsage; - _ByLine = "Generated By PROMS"; - _SortUsageByProcedure = sortUsageByProcedure; - _IncludeMissingROs = includeMissingROs; - _PaperSize = paperSize; - } - - /// - /// RO Complete RO Report - /// - /// - /// - /// - /// - /// - /// - /// - /// - public PDFReport(string reportTitle, string roDataFile, string outfile, ROFSTLookup fstlookup, bool completeReport, bool convertCaretToDelta, bool includeEmptyROFields, string paperSize) - { - _FileName = outfile; - _ReportTitle = reportTitle; - _ReportType = (int)ReportType.ReferencedObjectComplete; - _ByLine = "Complete Referenced Objects Report"; - _RODataFile = roDataFile; - _ConvertCaretToDelta = convertCaretToDelta; - _ROFSTLookup = fstlookup; - _IncludeEmptyROFields = includeEmptyROFields; - _PaperSize = paperSize; - } - - /// - /// RO Summary Report - /// - /// - /// - /// - /// - /// - public PDFReport(string reportTitle, string outfile, ROFSTLookup fstlookup, List roList, string paperSize) - { - _FileName = outfile; - _ReportTitle = reportTitle; - _ReportType = (int)ReportType.ReferencedObjectSummary; - _ByLine = "RO Summary Report"; - _ROFSTLookup = fstlookup; - _ROList = roList; - _PaperSize = paperSize; - } - - #endregion - - #region Public Methods - - public void AddMainRODatabaseTitle(PdfPTable datatable, int dbTitleIndex, Font f2, Color bgColor) - { - string dbTitle = _ROFSTLookup.GetRODatabaseTitle(dbTitleIndex); - - PdfPCell cell = new PdfPCell(new Phrase(dbTitle, f2)); - cell.BorderColor = Color.WHITE; - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - datatable.AddCell(cell); - } - - public void AddMainPathGroup(PdfPTable datatable, string dvPath, int splitLevel, Font f2, Color bgColor, int colSpan) - { - int level = 0; - StringBuilder sb = new StringBuilder(); - string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string sep = string.Empty; - int n = NewPath.Length; - - for (int j = 1; j < n && j < splitLevel; j++) - { - sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); - sep = "\r\n"; - level++; - } - - if (sb.Length > 0) - { - PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); - - cell.Colspan = colSpan; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - - datatable.AddCell(cell); - } - } - - public void AddSubPathGroup(PdfPTable datatable, string oldDVPath, string dvPath, int splitLevel, Font f2, Color bgColor, int colSpan) - { - int level = 0; - StringBuilder sb = new StringBuilder(); - string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string[] OldPath = oldDVPath.Split("\x7".ToCharArray()); - string sep = string.Empty; - int n = NewPath.Length - 1; - - for (int i = 0; i < n; i++) - { - if (OldPath[i] != NewPath[i]) - { - splitLevel = Math.Max(splitLevel, i); - break; - } - } - - if (splitLevel < n) - { - for (int j = splitLevel; j < n; j++) - { - sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); - sep = "\r\n"; - level++; - } - - if (sb.Length > 0) - { - PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); - - cell.Colspan = colSpan; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - - datatable.AddCell(cell); - } - } - } - - public void Build() - { - iTextSharp.text.Document document = new iTextSharp.text.Document(PDFPageSize.UsePaperSize(_PaperSize), 36, 36, 36, 36); // C2020-002 paper size is now set in the format files - - if (!CreateResultsPDF(document, _ReportType)) - return; - - try - { - switch (_ReportType) // set in the PDFReport constructor - { - case (int)ReportType.SearchResults: - BuildSearchResultsTable(document); - break; - - case (int)ReportType.LibraryDocUsage: - BuildLibDocUsageReport(document); - break; - - case (int)ReportType.ReferencedObjectsUsage: - if (_SortUsageByProcedure) - BuildROUsageTableByProcedure(document); - else - BuildROUsageTableByRO(document); - break; - - case (int)ReportType.ReferencedObjectComplete: - BuildCompleteROReport(document); - break; - - case (int)ReportType.ReferencedObjectSummary: - BuildROSummaryReport(document); - break; - } - } - catch (Exception ex) - { - StringBuilder msg = new StringBuilder(); - document.Add(new Paragraph("Error:")); - - while (ex != null) - { - document.Add(new Paragraph(ex.GetType().Name)); - document.Add(new Paragraph(ex.Message)); - ex = ex.InnerException; - } - } - finally - { - if (document.IsOpen()) - { - //document.Add(new Phrase("End of Search Results",FontFactory.GetFont("Arial",4))); // B2019-089 commented out - used for debug - document.Add(new Phrase(" ", FontFactory.GetFont("Arial", 4))); // B2019-089 - assure output has at least a blank space to prevent error on close - document.Close(); - System.Diagnostics.Process.Start(_FileName); - } - } - } - - #endregion - - #region Private Methods - - private string AddGroup(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) - { - int level = 0; - string retval = string.Empty; - StringBuilder sb = new StringBuilder(); - string ttt = dvPath.Replace("\x11", " "); - string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); - string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string sep = string.Empty; - bool foundMisMatch = false; - - // n-1 Exclude the "Working Draft" entry from the list - int n = NewPath.Length - 1; - int jstart = (skipFirst) ? 1 : 0; - - if (StripLast) - { - retval = NewPath[--n]; - if (retval.Contains("\x11")) - { - retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number - } - } - - if (n == 0) - { - // B2020-006: 'clean-up' the output string by making string replaces as in 'else' below. - sb.Append(dvPath.Replace("\x11", " ").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\")); - } - else - { - for (int j = jstart; j < n; j++) - { - if (!string.IsNullOrEmpty(NewPath[j]) && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) - { - // B2020-006: Add hard space '\u160?' - sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\"); - sep = "\r\n"; - foundMisMatch = true; - } - - level++; - } - } - - if (sb.Length > 0) - { - PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); - - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - datatable.AddCell(cell); - } - - return retval; - } - - private string AddGroupLibDoc(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) - { - int level = 0; - string retval = string.Empty; - StringBuilder sb = new StringBuilder(); - string ttt = dvPath.Replace("\x11", " "); - string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); - string[] NewPath = dvPath.Split("\x7".ToCharArray()); - string sep = string.Empty; - bool foundMisMatch = false; - int n = NewPath.Length - 1; - int jstart = (skipFirst) ? 1 : 0; - - if (StripLast) - { - retval = NewPath[--n]; - if (retval.Contains("\x11")) - { - retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number - } - } - - //If no colons output the entire text - if (n == 0) - { - sb.Append(dvPath); - } - else - { - for (int j = jstart; j < n; j++) - { - if (!string.IsNullOrEmpty(NewPath[j]) && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) - { - sb.Append(sep + "".PadLeft(2 * level) + NewPath[j].Replace("\x11", " ")).Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); - sep = "\r\n"; - foundMisMatch = true; - } - - level++; - } - } - - if (sb.Length > 0) - { - PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)); - - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - datatable.AddCell(cell); - } - - return retval; - } - - private void AddProcedureSectionGroup(PdfPTable datatable, string curProc, string lastProc, string curSect, string lastSect, Font f2, Color bgColor) - { - string headerText = string.Empty; - - if (curProc != lastProc) - headerText = curProc + "\r\n"; - - if (curSect != lastSect) - headerText += " " + curSect; - - if (headerText.Length > 0) - { - headerText = headerText.Replace(@"\u8209?", "-");// repace unicode with dash char - headerText = headerText.Replace(@"\u160?", " "); // replace Hard Space with normal Space - headerText = headerText.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash - - PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)); - cell.Colspan = 2; - cell.BackgroundColor = bgColor; - cell.BorderWidthTop = 1; - datatable.AddCell(cell); - } - } - - private string GetCurProcNum(string path) - { - string[] NewPath = path.Split("\x7".ToCharArray()); - string pnumtitle = NewPath[1]; - pnumtitle = pnumtitle.Replace('\x11', ' '); - - return pnumtitle; - } - - private string GetCurSectionNumTitle(ItemInfo itm) - { - string rtnstr = string.Empty; - - if (itm.ActiveSection != null) - { - rtnstr = itm.ActiveSection.DisplayNumber; - if (rtnstr.Length > 0) rtnstr += " "; - rtnstr += itm.ActiveSection.DisplayText; - } - - return rtnstr; // string containing section and subsection number/titles - } - - private int FindSpitLevel() - { - int level = 0; - bool foundMisMatch = false; - string lastPath = string.Empty; - - foreach (string p in ProcSetList) - { - string[] NewPath = p.Split("\x7".ToCharArray()); - - if (lastPath != string.Empty) - { - string[] OldPath = lastPath.Split("\x7".ToCharArray()); - int n = NewPath.Length; - int lvl = 0; - foundMisMatch = false; - - for (int j = 0; j < n && !foundMisMatch; j++) - { - if (NewPath[j] != string.Empty && (OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) - { - foundMisMatch = true; - } - - lvl++; - } - - if (level == 0) - level = lvl; - - if (foundMisMatch) - level = Math.Min(level, lvl); - } - - lastPath = p; - - if (ProcSetList.Count == 1) - { - level = NewPath.Length - 1; - } - } - - return level; - } - - /// - /// Attempt to open a file for the PDF output. - /// If the file cannot be opened because it is in use, try adding a suffix - /// If the file cannot be opened for some other reason, display an error message - /// - /// - /// - private bool CreateResultsPDF(iTextSharp.text.Document document, int typ) - { - int topMargin = 36; - - switch (typ) - { - case (int)ReportType.LibraryDocUsage: - topMargin = 80; // Add some space for the Report Header for the Library Document Report - break; - } - - bool result = false; - string suffix = string.Empty; - int i = 0; - - // Try to open a file for creating the PDF. - while (result == false) - { - string fileName = _FileName.ToLower().Replace(".pdf", suffix + ".pdf"); - - try - { - _MyPdfWriter = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); - _MyPdfWriter.PageEvent = new MyPageHelper(_ByLine); // JSJ - 7/8/2011 - - document.SetMargins(36, 36, topMargin, 36); - document.Open(); - - _FileName = fileName; - - result = true; - } - catch (System.IO.IOException exIO) - { - if (exIO.Message.Contains("because it is being used by another process")) - { - suffix = string.Format("_{0}", ++i);// If this file is in use, increment the suffix and try again - } - else // If some other error, display a message and don't print the results - { - ShowException(exIO); - return false; - } - } - catch (Exception ex) - { - ShowException(ex); - return false; // Could not open the output file - } - } - - return true; - } - - /// - /// Use Cells within Cells to see if I can limit the way Cells break from Page to Page - /// - /// - private void BuildSearchResultsTable(iTextSharp.text.Document document) - { - float[] headerwidths = { 20, 80 }; - PdfPTable datatable = new PdfPTable(1); - PdfPTable colHeader = new PdfPTable(headerwidths); - //datatable.FooterRows = 1; - datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - datatable.LockedWidth = true; - - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); - PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); - cell.HorizontalAlignment = Element.ALIGN_CENTER; - cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light cyan - datatable.AddCell(cell); - - // C2019-013 add sorted by information if sorting is used - cell = new PdfPCell(new Phrase(TypesSelected + ((SortedBy.Length > 0) ? string.Format("\n{0}", SortedBy) : string.Empty), f3)); - cell.HorizontalAlignment = Element.ALIGN_LEFT; - cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light cyan - datatable.AddCell(cell); - - BuildSearchResultsProcSetList(); - datatable.HeaderRows = 4 + (ProcSetList.Count == 1 ? 1 : 0); - int splitAt = FindSpitLevel(); // find the split level of the common path - for all procedure sets that use these library documents - - Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // new Color(0xD0, 0xF0, 0xD0); - datatable.DefaultCell.Padding = 0; // this removes a white space after the header was set to 4; - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; - AddCell(colHeader, "Step", f2, subHeaderColor); - AddCell(colHeader, "Text", f2, subHeaderColor); - - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - string lastPath = string.Empty; - Color AnnoColor = new Color(0xFF, 0xFF, 0xC0); // yellow - Color TextColor = Color.WHITE; - Color WordSectColor = new Color(0xE8, 0xE8, 0xE8);// light grey - Color StepSectColor = new Color(0xE7, 0xFF, 0xE7); // lighter green - PdfPTable subTable = new PdfPTable(headerwidths); - string lastProcNum = string.Empty; - string lastDVPath = string.Empty; - string lastSectNumAndTitle = string.Empty; - List processedItems = new List(); - - foreach (ItemInfo item in _ResultList) - { - if (!processedItems.Contains(item.ItemID)) - { - processedItems.Add(item.ItemID); - - if (lastDVPath != item.SearchDVPath) - { - datatable.AddCell(subTable); - subTable = new PdfPTable(headerwidths); - AddMainPathGroup(datatable, item.SearchDVPath, splitAt, f2, new Color(0xB0, 0xF0, 0xF0), 0);// little brighter cyan - datatable.AddCell(colHeader); - lastProcNum = string.Empty; - lastSectNumAndTitle = string.Empty; // C2020-019 reset we are processing a different procedure set - } - - lastDVPath = item.SearchDVPath; - string curProcNum = GetCurProcNum(item.SearchPath); - - if (subTable.Rows.Count > 0) // prevent first page from being blank - { - datatable.AddCell(subTable); - subTable = new PdfPTable(headerwidths); - } - - if (curProcNum != lastProcNum) - { - lastSectNumAndTitle = string.Empty; // C2020-019 reset we are processing a different procedure - } - - lastProcNum = curProcNum; - - // B2020-006: When doing a section, don't remove the last item or the procedure title won't print (if section is only item found w/ search string) - string stepPath = AddGroup(subTable, item.SearchPath ?? item.ShortPath, lastPath, f2, item.IsSection ? false : true, new Color(0xC0, 0xFF, 0xC0), true); // light green for procedure number and title - - // C2020-019 add section number and title if is different from last item and it is not a Word Section (item will be a section if search item was found in a Word section) - string curSectNumTitle = GetCurSectionNumTitle(item); - - if (curSectNumTitle != string.Empty && curSectNumTitle != lastSectNumAndTitle && !item.IsSection) - { - AddColSpanCell(subTable, curSectNumTitle, f2, StepSectColor, 2, 0); - lastSectNumAndTitle = curSectNumTitle; - } - - lastPath = item.SearchPath ?? item.ShortPath; - stepPath = BuildStepTab(item); - AddCell(subTable, stepPath, f2, (item.IsSection ? WordSectColor : TextColor)); - AddCell(subTable, item.DisplayText, f2, (item.IsSection ? WordSectColor : TextColor)); - - if (ShowAnnotations && item.ItemAnnotationCount > 0) - { - foreach (AnnotationInfo ai in item.ItemAnnotations) - { - AddCell(subTable, ai.MyAnnotationType.Name, f2, AnnoColor); - AddCell(subTable, ai.SearchText, f2, AnnoColor); - } - } - } - } - - datatable.AddCell(subTable); - document.Add(datatable); - } - - private void AddCell(PdfPTable datatable, string str, iTextSharp.text.Font fnt, Color bgColor) - { - iTextSharp.text.Font fntBold = new Font(fnt.BaseFont, fnt.Size, Font.BOLD, Color.RED); - - Phrase p = BuildPhrase2(str, fnt, fntBold); - PdfPCell cell = new PdfPCell(p); - cell.PaddingBottom = 4; - cell.BackgroundColor = bgColor; - - datatable.AddCell(cell); - } - - private void AddColSpanCell(PdfPTable datatable, string str, iTextSharp.text.Font fnt, Color bgColor, int span, int txtAlign) - { - iTextSharp.text.Font fntBold = new Font(fnt.BaseFont, fnt.Size, Font.BOLD, Color.RED); - - Phrase p = BuildPhrase2(str, fnt, fntBold); - PdfPCell cell = new PdfPCell(p); - cell.PaddingBottom = 4; - cell.BackgroundColor = bgColor; - cell.Colspan = span; - cell.HorizontalAlignment = txtAlign; - - datatable.AddCell(cell); - } - - private Phrase BuildPhrase(string str, Font fnt, Font fntBold) - { - Phrase p = new Phrase(); - - if (_SearchString != null) - { - while (str.ToLower().Contains(_SearchString.ToLower())) - { - int iStart = str.ToLower().IndexOf(_SearchString.ToLower()); - - if (iStart > 0) - { - p.Add(new Phrase(str.Substring(0, iStart), fnt)); - } - - Phrase p2 = new Phrase(str.Substring(iStart, _SearchString.Length), fntBold); - p.Add(p2); - - str = str.Substring(iStart + _SearchString.Length); - } - } - - if (str.Length > 0) - p.Add(new Phrase(str, fnt)); - - return p; - } - - private Phrase BuildPhrase2(string str, Font fnt, Font fntBold) - { - Phrase p = new Phrase(); - int lastIndex = 0; - - if ((_SearchString ?? string.Empty) != string.Empty) - { - Regex reg = new Regex(RegexSearchString, RegexOptions.Multiline | RegexOptions.IgnoreCase); - - foreach (Match m in reg.Matches(str)) - { - if (m.Index > 0) - p.Add(new Phrase(str.Substring(lastIndex, m.Index - lastIndex), fnt)); - - Chunk chk = new Chunk(m.Value, fnt); - chk.SetBackground(Color.YELLOW); - p.Add(chk); - - lastIndex = m.Index + m.Length; - } - } - - p.Add(new Phrase(str.Substring(lastIndex), fnt)); - - return p; - } - - private void BuildLibDocUsageReport(iTextSharp.text.Document document) - { - // Adjusted from 20,80 to 25,75 to account for long Procedure Numbers - float[] headerwidths = { 25, 75 }; - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - BuildLibDocProcSetList(); - - int splitAt = FindSpitLevel() - 1; // find the split level of the common path - for all procedure sets that use these library documents - string lastDvPath = string.Empty; - Color AnnoBackgroundColor = new Color(0xFF, 0xFF, 0xC0); - Color TextBackgroundColor = Color.WHITE; - Color NotUsedBackgroundColor = Color.WHITE; - MyPageHelper pghlp = _MyPdfWriter.PageEvent as MyPageHelper; - pghlp.HeaderTable = LibDocTable(document, headerwidths, f2, null); - - foreach (DocumentInfo di in _LibDocList) - { - PdfPTable subtable; - subtable = BuildSubTable(document, headerwidths); - - AddGroupLibDoc(subtable, di.DocumentTitle, string.Empty, f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title - - if (di.DocumentConfig.LibDoc_Comment != null && di.DocumentConfig.LibDoc_Comment.Length > 0) - { - AddCell(subtable, "Comment", f2, AnnoBackgroundColor); - AddCell(subtable, di.DocumentConfig.LibDoc_Comment, f2, AnnoBackgroundColor); // lib doc comment - } - - if (di.DocumentEntries == null || di.DocumentEntries.Count == 0) - { - AddGroupLibDoc(subtable, "* No References To This Library Document *", string.Empty, f2, false, TextBackgroundColor, false); // Library Document Title - } - else - { - subtable.HeaderRows = 2; - System.Collections.ArrayList LibDocUsageList = GetSortedItemInfoList(di.LibraryDocumentUsageList); - lastDvPath = string.Empty; - - foreach (ItemInfo item in LibDocUsageList)//di.LibraryDocumentUsageList) - { - if (item.SearchDVPath != lastDvPath) - { - if (lastDvPath != string.Empty) - { - document.Add(subtable); - subtable = BuildSubTable(document, headerwidths); - subtable.HeaderRows = 2; - AddGroupLibDoc(subtable, di.DocumentTitle, string.Empty, f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title - } - - AddSubPathGroup(subtable, lastDvPath, item.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 2);//new Color(0xC0, 0xFF, 0xC0)); - } - - lastDvPath = item.SearchDVPath; - string ProcNumber = item.MyProcedure.ProcedureConfig.Number; - ProcNumber = ProcNumber.Replace(@"\u8209?", "-"); // repace unicode with dash char - ProcNumber = ProcNumber.Replace(@"\u160?", " "); // replace Hard Space with normal Space - ProcNumber = ProcNumber.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash - AddCell(subtable, ProcNumber, f2, TextBackgroundColor); - AddCell(subtable, item.DisplayNumber + " - " + item.DisplayText, f2, TextBackgroundColor); - } - - } - - document.Add(subtable); - } - } - - private PdfPTable LibDocTable(iTextSharp.text.Document document, float[] headerwidths, iTextSharp.text.Font f2, DocumentInfo di) - { - PdfPTable datatable = new PdfPTable(1);// (headerwidths); - PdfPTable colheader = new PdfPTable(headerwidths); - datatable.HeaderRows = 2; - datatable.KeepTogether = false; - datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - datatable.LockedWidth = true; - - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); - PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); - cell.HorizontalAlignment = Element.ALIGN_CENTER; - //cell.Colspan = 2; - - cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); - datatable.AddCell(cell); - - Color subHeaderColor = new Color(0xD0, 0xF0, 0xD0); - datatable.DefaultCell.Padding = 4; - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; - AddCell(colheader, "Procedure", f2, subHeaderColor); - AddCell(colheader, "Section", f2, subHeaderColor); - datatable.AddCell(colheader); - - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - - return datatable; - } - - private void AddROUsages(ItemInfo item, Dictionary> roUse) - { - if (item != null && !string.IsNullOrEmpty(item.FoundROID)) - { - string roid = item.FoundROID; - - if (roUse.ContainsKey(roid)) - { - ((List)roUse[roid]).Add(item); - } - else - { - List itmIfoLst = new List(); - itmIfoLst.Add(item); - roUse.Add(roid, itmIfoLst); - } - } - } - - private void PutROusageForProcedure(PdfPTable curTable, Dictionary> rosused, float[] headerwidths) - { - //if (rosused.Count == 0) return; // nothing to process - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - - foreach (string roKey in rosused.Keys) - { - PdfPTable rotable = new PdfPTable(headerwidths); - string rotitle = string.Empty; - - foreach (ItemInfo itm in rosused[roKey]) - { - if (string.IsNullOrEmpty(rotitle)) - { - rotitle = GetROTitleAndGroup(roKey, itm); - - if (!string.IsNullOrEmpty(rotitle)) - { - PdfPCell ROTitleCell = new PdfPCell(new Phrase(rotitle, f2)); - ROTitleCell.Colspan = 2; - ROTitleCell.HorizontalAlignment = Element.ALIGN_LEFT; - - if (rotitle.StartsWith("Missing RO")) - { - ROTitleCell.BackgroundColor = Color.PINK; - } - else - { - ROTitleCell.BackgroundColor = new Color(0xDC, 0xE7, 0xC9); //new Color(0xD0, 0xF0, 0xD0);//ligt green //new Color(0xC8, 0xC8, 0x91);//(0xAF, 0xD8, 0xD8);//(0xF5, 0xE4, 0xA0); - } - - rotable.AddCell(ROTitleCell); // put RO value and description - } - } - - string stepnum = string.Empty; - string sectitle = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayText : string.Empty; - - if (itm.IsSection) - { - stepnum = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : string.Empty; - } - else - { - stepnum = BuildStepTab(itm); - } - - AddCell(rotable, stepnum, f2, Color.WHITE); - AddCell(rotable, itm.DisplayText, f2, Color.WHITE); - - } - - curTable.AddCell(rotable); - } - } - - private void BuildROUsageTableByProcedure(iTextSharp.text.Document document) - { - Dictionary> roUse = new Dictionary>(); - float[] headerwidths = { 20, 80 }; - PdfPTable datatable = new PdfPTable(1); - PdfPTable colHeader = new PdfPTable(headerwidths); - //datatable.FooterRows = 1; - datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - datatable.LockedWidth = true; - - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); - PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); - cell.HorizontalAlignment = Element.ALIGN_CENTER; - //cell.Colspan = 2; - cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light blue - datatable.AddCell(cell); - - BuildSearchResultsProcSetList(); - datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); - int splitAt = FindSpitLevel(); // find the split level of the common path - - Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // light blue //new Color(0xD0, 0xF0, 0xD0);//ligt green - datatable.DefaultCell.Padding = 4; - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; - - // This puts "Step" and "Text" column headers at the bottom of the page - AddCell(colHeader, "Step", f2, subHeaderColor); - AddCell(colHeader, "Text", f2, subHeaderColor); - datatable.AddCell(colHeader); - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - Color AnnoColor = new Color(0xFF, 0xFF, 0xC0); - Color TextColor = Color.WHITE; - Color SectColor = new Color(0xE0, 0xFF, 0xE0);//new Color(0xC0, 0xFF, 0xC0);//Color.LIGHT_GRAY; - PdfPTable subTable = new PdfPTable(headerwidths); - datatable.AddCell(subTable); - - string lastProcNum = string.Empty; - string lastSection = string.Empty; - //CSM B2021-043 Step numbering is out of order in RO usage report if RO values exist on steps 10 or higher. - //setting this to something other than empty - otherwise will not print first initial header - string lastDVPath = "start"; - if (_ResultList.Count > 0) - { - foreach (ItemInfo item in _ResultList) - { - bool differentProcSet = false; - bool differentRO = false; - // Check Doc Version path - // if more than one procedure set is in the report data, then - // we will output the procedure set title inside the grouping of each RO - // otherwise, if we are reporting on only one procedure set, print the - // procedure set title at the top of the report (once). - if (lastDVPath != "" && lastDVPath != item.SearchDVPath) - { - //CSM B2021-043 Step numbering is out of order in RO usage report if RO values exist on steps 10 or higher. - //was placing last item from the precious section in the new section - //place it before starting the new section and then clear items - PutROusageForProcedure(datatable, roUse, headerwidths); - roUse.Clear(); - - subTable = new PdfPTable(headerwidths); - AddMainPathGroup(datatable, item.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); - lastProcNum = string.Empty; - lastSection = string.Empty; - } - - lastDVPath = item.SearchDVPath; - //check for different procedure number - string curProcNum = GetCurProcNum(item.SearchPath); - string curSection = GetCurSectionNumTitle(item); - - if (!string.IsNullOrEmpty(lastProcNum) && (curProcNum != lastProcNum)) - { - if (roUse.Count > 0) - { - PutROusageForProcedure(datatable, roUse, headerwidths); - roUse.Clear(); - } - - lastSection = string.Empty; - } - - if (!string.IsNullOrEmpty(lastSection) && (curSection != lastSection)) - { - if (roUse.Count > 0) - { - PutROusageForProcedure(datatable, roUse, headerwidths); - roUse.Clear(); - } - } - - AddROUsages(item, roUse); // add the used ro to the list for this procedure - AddProcedureSectionGroup(datatable, curProcNum, lastProcNum, curSection, lastSection, f2, new Color(0xC0, 0xFF, 0xC0)); - - lastProcNum = curProcNum; - lastSection = curSection; - } - } - else - { // B2022-093 put out a message if no RO Usages were found - cell = new PdfPCell(new Phrase("No RO Usage Information Found", f3)); - cell.HorizontalAlignment = Element.ALIGN_LEFT; - //cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light blue - datatable.AddCell(cell); - } - PutROusageForProcedure(datatable, roUse, headerwidths); - - document.Add(datatable); - } - - private void AddProcROUse(ItemInfo item, Dictionary> procRoUse) - { - string dictKey = GetCurProcNum(item.SearchPath) + " " + GetCurSectionNumTitle(item); - - if (!string.IsNullOrEmpty(dictKey)) - { - if (procRoUse.ContainsKey(dictKey)) - { - ((List)procRoUse[dictKey]).Add(item); - } - else - { - List itmIfoLst = new List(); - itmIfoLst.Add(item); - procRoUse.Add(dictKey, itmIfoLst); - } - } - } - - private void PutStepListForProcedure(PdfPTable rotable, Dictionary sortedStepList) - { - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - - foreach (ItemInfo itm in sortedStepList.Values) - { - string stepnum = (itm.IsSection && itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : stepnum = BuildStepTab(itm);// C2018-003 fixed use of getting the active section - AddCell(rotable, stepnum, f2, Color.WHITE); - AddCell(rotable, itm.DisplayText, f2, Color.WHITE); - } - - sortedStepList.Clear(); - } - - private void PutROusageForROID(PdfPTable curTable, Dictionary> procRoUse, float[] headerwidths, int splitAt, bool moreThanOneProcSet) - { - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - - Dictionary sortedStepList = new Dictionary(); - string lastProcKey = string.Empty; - string lastProcNumTitle = string.Empty; - string lastDVPath = string.Empty; - string curProcNumTitle = string.Empty; - - foreach (string procKey in procRoUse.Keys) - { - PdfPTable rotable = new PdfPTable(headerwidths); - - foreach (ItemInfo itm in procRoUse[procKey]) - { - bool didProcSetTitle = false; - // Check Doc Version path - // where we are reporting on more than one procedure set - // output the procedure set title within the RO value grouping on the report - if (moreThanOneProcSet && lastDVPath != itm.SearchDVPath) - { - AddMainPathGroup(curTable, itm.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); - didProcSetTitle = true; - } - else - { - didProcSetTitle = false; - } - - lastDVPath = itm.SearchDVPath; - - if (didProcSetTitle || procKey != lastProcKey) - { - if (sortedStepList.Count > 0) - { - PutStepListForProcedure(rotable, sortedStepList); - } - - string procNumTitleSect = string.Empty; - curProcNumTitle = GetCurProcNum(itm.SearchPath); - - if (lastProcNumTitle == string.Empty || lastProcNumTitle != curProcNumTitle) - { - procNumTitleSect = curProcNumTitle + "\r\n"; - lastProcNumTitle = curProcNumTitle; - } - - procNumTitleSect += " " + GetCurSectionNumTitle(itm); - procNumTitleSect = procNumTitleSect.Replace(@"\u8209?", "-"); // repace unicode with dash char - procNumTitleSect = procNumTitleSect.Replace(@"\u160?", " "); // replace Hard Space with normal Space - procNumTitleSect = procNumTitleSect.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash - PdfPCell ProcTitleCell = new PdfPCell(new Phrase(procNumTitleSect, f2)); - ProcTitleCell.Colspan = 2; - ProcTitleCell.HorizontalAlignment = Element.ALIGN_LEFT; - ProcTitleCell.BackgroundColor = new Color(0xDC, 0xE7, 0xC9); //new Color(0xD0, 0xF0, 0xD0);//ligt green //new Color(0xC8, 0xC8, 0x91);//(0xAF, 0xD8, 0xD8);//(0xF5, 0xE4, 0xA0); - rotable.AddCell(ProcTitleCell); // put RO value and description - lastProcKey = procKey; - } - - string stepnum = (itm.IsSection && itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : BuildStepTab(itm);// C2018-003 fixed use of getting the active section - string itemkey = stepnum + " " + itm.ItemID.ToString(); // add ItemId to stepnum, sometimes we have idential stepnum text for different steps (ex: blank section numbers) - - if (!sortedStepList.ContainsKey(itemkey)) - { - sortedStepList.Add(itemkey, itm); - } - } - - if (sortedStepList.Count > 0) - { - PutStepListForProcedure(rotable, sortedStepList); - } - - curTable.AddCell(rotable); - } - } - - private string GetROTitleAndGroup(string roid, ItemInfo itm) - { - string rotitle = string.Empty; - - ROFSTLookup myrofstlookup = (itm == null) ? _ROFSTLookup : itm.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(itm.MyDocVersion); - - List roTitleList = myrofstlookup.GetROTitleAndGroupPath(roid, _IncludeMissingROs, _ConvertCaretToDelta); - - if (roTitleList != null && roTitleList.Count > 0) - { - for (int cnt = 0; cnt < roTitleList.Count; cnt++) - { - if (cnt == roTitleList.Count - 1) // Last roTitle in list, don't add a NewLine character after the value - rotitle += roTitleList[cnt]; - else - rotitle += roTitleList[cnt] + "\n "; - } - } - - return rotitle; - } - - private void AddROHeaderGroup(PdfPTable datatable, string curROID, ItemInfo itm, Font f2, Color bgColor) - { - string headerText = GetROTitleAndGroup(curROID, itm); - - if (!string.IsNullOrEmpty(headerText) && headerText.Length > 0) - { - PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)); - - cell.Colspan = 2; - cell.BackgroundColor = (headerText.StartsWith("Missing RO")) ? Color.PINK : bgColor; - cell.BorderWidthTop = 1; - - datatable.AddCell(cell); - } - } - - private void BuildROUsageTableByRO(iTextSharp.text.Document document) - { - Dictionary> procRoUse = new Dictionary>(); - - float[] headerwidths = { 20, 80 }; - PdfPTable datatable = new PdfPTable(1); - PdfPTable colHeader = new PdfPTable(headerwidths); - //datatable.FooterRows = 1; - datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - datatable.LockedWidth = true; - - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); - PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); - cell.HorizontalAlignment = Element.ALIGN_CENTER; - cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light blue - datatable.AddCell(cell); - - BuildSearchResultsProcSetList(); - datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); - int splitAt = FindSpitLevel(); // find the split level of the common path - - Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // light blue //new Color(0xD0, 0xF0, 0xD0);//ligt green - datatable.DefaultCell.Padding = 4; - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; - // This puts "Step" and "Text" column headers at the bottom of the page - AddCell(colHeader, "Step", f2, subHeaderColor); - AddCell(colHeader, "Text", f2, subHeaderColor); - datatable.AddCell(colHeader); - - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - Color AnnoColor = new Color(0xFF, 0xFF, 0xC0); - Color TextColor = Color.WHITE; - Color SectColor = new Color(0xE0, 0xFF, 0xE0);//new Color(0xC0, 0xFF, 0xC0);//Color.LIGHT_GRAY; - PdfPTable subTable = new PdfPTable(headerwidths); - datatable.AddCell(subTable); - - string lastDVPath = string.Empty; - string lastROID = string.Empty; - bool moreThanOneProcSet = false; - bool printedSetTitle = false; - bool printedROHeader = false; - ItemInfo lastItem = null; - - if (_ResultList.Count == 0) - { - PdfPCell cell2 = new PdfPCell(new Phrase("Selected RO is not used", f2)); - - cell2.Colspan = 0; - cell2.BorderWidthTop = 1; - datatable.AddCell(cell2); - document.Add(datatable); - - return; - } - - foreach (ItemInfo item in _ResultList) - { - bool differentProcSet = false; - bool differentRO = false; - - // Check Doc Version path - // if more than one procedure set is in the report data, then - // we will output the procedure set title inside the grouping of each RO - // otherwise, if we are reporting on only one procedure set, print the - // procedure set title at the top of the report (once). - if (!string.IsNullOrEmpty(lastDVPath) && lastDVPath != item.SearchDVPath) - { - moreThanOneProcSet = true; - differentProcSet = true; - } - - lastDVPath = item.SearchDVPath; - - // Check for different ROID - string curROID = item.FoundROID; - differentRO = (!string.IsNullOrEmpty(lastROID) && !string.IsNullOrEmpty(curROID) && curROID.Substring(0, 12) != lastROID.Substring(0, 12)); - - if (procRoUse.Count > 0 && (differentProcSet || differentRO)) - { - if (!moreThanOneProcSet && !printedSetTitle) - { - AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); - printedSetTitle = true; - } - - if (!printedROHeader) - { - AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); - printedROHeader = true; - } - - PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); - procRoUse.Clear(); - - differentProcSet = false; - } - - if (differentRO) - { - printedROHeader = false; - } - - AddProcROUse(item, procRoUse); - - lastROID = curROID; - lastItem = item; - } - - if (!moreThanOneProcSet && !printedSetTitle) - AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); - - if (!printedROHeader) - AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); - - PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); - - document.Add(datatable); - } - - private void BuildSearchResultsProcSetList() - { - ProcSetList = new System.Collections.ArrayList(); - foreach (ItemInfo item in _ResultList) - { - if (!ProcSetList.Contains(item.SearchDVPath)) - ProcSetList.Add(item.SearchDVPath); - } - } - - private void BuildLibDocProcSetList() - { - ProcSetList = new System.Collections.ArrayList(); - foreach (DocumentInfo di in _LibDocList) - { - if (di.LibraryDocumentUsageList != null && di.LibraryDocumentUsageList.Count > 0) - foreach (ItemInfo item in di.LibraryDocumentUsageList) - { - if (!ProcSetList.Contains(item.SearchDVPath)) - ProcSetList.Add(item.SearchDVPath); - } - } - } - - private ArrayList GetSortedItemInfoList(ItemInfoList orgIFL) - { - System.Collections.ArrayList libDocProcSetList = new System.Collections.ArrayList(); - System.Collections.ArrayList rtnIFL = new System.Collections.ArrayList(); - foreach (ItemInfo item in orgIFL) - { - if (!libDocProcSetList.Contains(item.SearchDVPath)) - libDocProcSetList.Add(item.SearchDVPath); - } - foreach (string pset in libDocProcSetList) - { - foreach (ItemInfo item in orgIFL) - { - if (item.SearchDVPath.Equals(pset)) - rtnIFL.Add(item); - } - } - return rtnIFL; - } - - private void BuildCompleteROReport(iTextSharp.text.Document document) - { - CompleteROReport compRORpt = new CompleteROReport(_MyPdfWriter, document, _RODataFile, _ConvertCaretToDelta, _IncludeEmptyROFields); - - compRORpt.F10 = pdf.GetFont("Courier New", 10, 0, Color.BLACK); - compRORpt.F10Bold = pdf.GetFont("Courier New", 10, 1, Color.BLACK); - compRORpt.F12 = pdf.GetFont("Courier New", 12, 0, Color.BLACK); - compRORpt.F12Bold = pdf.GetFont("Courier New", 12, 1, Color.BLACK); - // C2017-036 Get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - compRORpt.F14 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - - //B2022 - 083: Support Conditional RO Values - compRORpt.ROFstID = _ROFSTLookup.RofstID; - - compRORpt.Run(); - } - - private string GetROTitleAndGroupsForSummary(List roTitleList, List prevROTitleList) - { - string rotitle = string.Empty; - string indent = string.Empty; - - for (int icnt = 0; icnt < roTitleList.Count; icnt++) - { - indent += " "; - - if (icnt == roTitleList.Count - 1) - { - rotitle += indent + roTitleList[icnt]; // this should be the ro description - break; //break out of for loop - } - - if (prevROTitleList == null || (icnt < roTitleList.Count && icnt < prevROTitleList.Count && prevROTitleList[icnt] != roTitleList[icnt])) - { - if (rotitle == string.Empty && prevROTitleList != null) - rotitle = "\n"; - - rotitle += indent + roTitleList[icnt] + "\n"; - } - } - - return rotitle; - } - - private List AddROHeaderGroupForSummary(PdfPTable datatable, string curROID, List prevROTitleList, Font f2, Color bgColor) - { - List roTitleList = _ROFSTLookup.GetROTitleAndGroupPath(curROID, _IncludeMissingROs, _ConvertCaretToDelta); - string headerText = GetROTitleAndGroupsForSummary(roTitleList, prevROTitleList); - - if (headerText.Length > 0) - { - Paragraph pgh = new Paragraph(headerText, f2); - PdfPCell cell = new PdfPCell(pgh); - - cell.FollowingIndent = 72; - cell.Colspan = 2; - cell.BorderColor = Color.WHITE; - cell.BackgroundColor = Color.WHITE; - cell.BorderWidthTop = 1; - - datatable.AddCell(cell); - } - - return roTitleList; - } - - private void BuildROSummaryReport(iTextSharp.text.Document document) - { - float[] headerwidths = { 10, 20, 80 }; - PdfPTable datatable = new PdfPTable(1); - datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - datatable.LockedWidth = true; - - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); - iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); - iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 1, Color.BLACK); - - PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)); - - cell.HorizontalAlignment = Element.ALIGN_CENTER; - //cell.Colspan = 2; - cell.BackgroundColor = Color.WHITE;//new Color(0xD0, 0xF0, 0xF0); // light blue - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); - - string roFSTDateTime = "RO.FST Last Created: " + _ROFSTLookup.GetRoFSTdts().ToLongDateString() + " @ " + _ROFSTLookup.GetRoFSTdts().ToShortTimeString() + "\n "; - cell = new PdfPCell(new Phrase(roFSTDateTime, f2)); - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); - - datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); - datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; - string lastROID = string.Empty; - List prevROTitleList = null; - int lastDBindex = -1; - - foreach (string curROID in _ROList) - { - string[] tmp = curROID.TrimEnd(',').Split(':'); //curROID.Split(':');// this is the RO FST id number (for plants with multiple RO FSTs) - string rolst = (tmp.Length == 2) ? tmp[1] : tmp[0]; - string[] roIdslst = rolst.Split(','); - - foreach (string cROID in roIdslst) - { - if (string.IsNullOrEmpty(cROID)) - break; - - if (cROID.Length == 4) - ProcessROdb(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); - else - ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); - } - } - - document.Add(datatable); - } - - private void ProcessROdb(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, string cROID) - { - ROFSTLookup.rodbi roDBI = _ROFSTLookup.GetRODatabase(cROID, true, true); - - if (roDBI.children != null && roDBI.children.Length > 0) - { - for (int i = 0; i < roDBI.children.Length; i++) - { - ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, roDBI.children[i]); - } - } - else - { - ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); - - cell = new PdfPCell(new Phrase(" ", f2)); - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); - cell = new PdfPCell(new Phrase("-- No Information Entered --", f2)); - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); - } - } - - private void ProcessROChild(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, ROFSTLookup.rochild cld) - { - if (cld.children == null || cld.children.Length <= 0) // leaf node - { - ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); - } - else if (cld.children[0].ParentID == 0) // multiple return value - { - ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); - } - else - { - for (int i = 0; i < cld.children.Length; i++) - { - ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.children[i]); - } - } - } - - private void ProcessROID(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, string cROID) - { - int curDBindex = _ROFSTLookup.GetRODatabaseTitleIndex(cROID); - - if (lastDBindex == -1 || curDBindex != lastDBindex) - { - if (prevROTitleList != null) - { - // add blank line to separate groups on the report - cell = new PdfPCell(new Phrase(" ", f2)); - cell.BorderColor = Color.WHITE; - datatable.AddCell(cell); - } - - AddMainRODatabaseTitle(datatable, curDBindex, f3, Color.WHITE); - lastDBindex = curDBindex; - } - - if (string.IsNullOrEmpty(lastROID) || cROID != lastROID) - prevROTitleList = AddROHeaderGroupForSummary(datatable, cROID, prevROTitleList, f2, new Color(0xC0, 0xFF, 0xC0)); - - lastROID = cROID; - } - - #endregion - - #region Private Static Methods - - private static PdfPTable BuildSubTable(iTextSharp.text.Document document, float[] headerwidths) - { - PdfPTable subtable = new PdfPTable(headerwidths); - - subtable.HeaderRows = 1; - subtable.KeepTogether = true; - subtable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; - subtable.LockedWidth = true; - subtable.DefaultCell.Padding = 4; - - return subtable; - } - - private static void ShowException(Exception ex) - { - Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); - StringBuilder msg = new StringBuilder(); - string sep = string.Empty; - string indent = string.Empty; - - while (ex != null) - { - msg.Append(string.Format("{0}{1}{2}:\r\n{1}{3}", sep, indent, ex.GetType().Name, ex.Message)); - ex = ex.InnerException; - sep = "\r\n"; - indent += " "; - } - - System.Windows.Forms.MessageBox.Show(msg.ToString(), "Error during PDF creation for search:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); - } - - public static string BuildStepTab(ItemInfo item) - { - if (item == null) - return string.Empty; - - string sret = string.Empty; - - switch (item.MyContent.Type / 10000) - { - case 0: //procedure - sret = ProcedureInfo.Get(item.ItemID).MyTab.CleanText; - break; - - case 1: // section - sret = SectionInfo.Get(item.ItemID).MyTab.CleanText; - break; - - case 2: // step - ItemInfo pitem = item; - bool hasDelim = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter != null; - List DelimList = null; - DelimList = new List(); - - if (!hasDelim) - { - SeqTabFmtList seqtabs = item.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SeqTabFmtList; - - foreach (SeqTabFmt seqtab in seqtabs) - { - string delim = seqtab.PrintTabFormat.Replace("{seq}", string.Empty); - - if (!DelimList.Contains(delim)) - { - DelimList.Add(delim.Trim()); - } - } - } - else - { - string stpdelms = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter; - - foreach (char c in stpdelms) - { - if (!DelimList.Contains(c.ToString())) - { - DelimList.Add(c.ToString()); - } - } - } - - // B2016-160 Support transitions to sections - while (!pitem.IsSection && !pitem.IsHigh) - { - StepInfo stpinfo = StepInfo.Get(pitem.ItemID); - string thisTab = stpinfo.MyTab.CleanText; - - if (IncludesParentToHLS(stpinfo)) - { - if (!thisTab.Contains("\u25CF")) //Remove Bullet - { - return thisTab; - } - else - { - thisTab = null; - } - } - - string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.ToString(); - - // remove delimiters of '.' and ')' in tab. - if (!string.IsNullOrEmpty(thisTab)) - { - // get list of delimiters to remove from the format: - foreach (string rmvDelim in DelimList) - { - thisTab = thisTab.Replace(rmvDelim, string.Empty); - } - } - - if (!string.IsNullOrEmpty(thisTab)) - { - thisTab = thisTab.Trim(); - } - - // if the tab is null or - // if the the tab is not a letter or number OR - // the tab is an AND or OR type and is the letter "o" - // then reset the tab an empty string so that the type name along with the count of that type - // (ex. "AND 2", "OR 3") - if (string.IsNullOrEmpty(thisTab) || (thisTab != string.Empty && (!(char.IsLetterOrDigit(thisTab[0])) || ((pitem.IsAnd || pitem.IsOr || pitem.IsCaution || pitem.IsNote) && thisTab.Contains("o"))))) - { - thisTab = string.Empty; - } - - if (pitem.IsRNOPart) - { - if (string.IsNullOrEmpty(thisTab)) - { - sret = "RNO." + sret; //"RNO." + sret; - } - else - { - thisTab = thisTab.Trim(" ".ToCharArray()); - - if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) - { - thisTab = thisTab + "."; - } - - sret = "RNO." + thisTab + sret; //"RNO." + thisTab + sret; - } - } - else if (pitem.IsCaution || pitem.IsNote) - { - // add the Caution or Note count to the tab (ex "Caution 1", "Note 2") - if (string.IsNullOrEmpty(thisTab)) - { - sret = "{" + typeName + " " + pitem.Ordinal.ToString() + "}"; - } - else - { - thisTab = thisTab.Trim(" ".ToCharArray()); - sret = thisTab + " " + pitem.Ordinal.ToString() + sret; - } - } - else - { - if (!string.IsNullOrEmpty(thisTab)) - { - thisTab = thisTab.Trim(" ".ToCharArray()); - - if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) - { - thisTab = thisTab + "."; - } - } - else - { - thisTab = "{" + typeName + " " + pitem.Ordinal.ToString() + "}."; - } - - sret = thisTab + sret; - } - - pitem = pitem.ActiveParent as ItemInfo; - - if (pitem == null) - break; - } - - // add hls tab if it's not already in the tab. - if (pitem.IsHigh) - { - StepInfo stpinfo = StepInfo.Get(pitem.ItemID); - - string hlsTab = stpinfo.MyTab.CleanTextNoSymbols; //StepInfo.Get(pitem.ItemID).MyTab.CleanTextNoSymbols; - string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.GetPDDisplayName(); //.ToString(); - // C2020-043: don't remove delimiters on tabs if this step's tab has the parent tab included. - bool hasParent = false; - - if (IncludesParentToHLS(stpinfo) && !hlsTab.Contains("\u25CF")) - { - hlsTab = hlsTab.Trim(" ".ToCharArray()).TrimEnd(".".ToCharArray()); - hasParent = true; - } - - if (string.IsNullOrEmpty(hlsTab)) - { - hlsTab = "{" + typeName + " " + pitem.Ordinal.ToString() + "}."; - } - else if (!hasParent && !sret.StartsWith(hlsTab.Trim(" ".ToCharArray()))) - { - foreach (string rmvDelim in DelimList) - { - hlsTab = hlsTab.Replace(rmvDelim, string.Empty); - } - - hlsTab = hlsTab.Trim(" ".ToCharArray()); - - if (!hlsTab.EndsWith(".") && !hlsTab.EndsWith(")")) - { - hlsTab = hlsTab + "."; - } - } - - sret = hlsTab + sret; - } - - break; - } - - return sret.Trim(" .)".ToCharArray()); - } - - private static bool IncludesParentToHLS(StepInfo stpinfo) - { - if (stpinfo.IsHigh) - return true; - - StepInfo parent = StepInfo.Get((stpinfo.ActiveParent as ItemInfo).ItemID); - - if (stpinfo.MyTab.CleanText.StartsWith(parent.MyTab.CleanText.Trim()) && stpinfo.MyTab.CleanText.Length > parent.MyTab.CleanText.Length) - { - return IncludesParentToHLS(parent); - } - - return false; - } - - #endregion - } - - - public class MyPageHelper : PdfPageEventHelper - { - #region Fields - - private PdfPTable _HeaderTable = null; - protected PdfTemplate total; - protected BaseFont helv; - private int ptSize = 10; // text point size of page number and page total - string _ByLine = "PROMS"; - - #endregion - - #region Properties - - public PdfPTable HeaderTable - { - get { return _HeaderTable; } - set { _HeaderTable = value; } - } - - #endregion - - #region Constructors - - public MyPageHelper(string byLine) - { - _ByLine = byLine; - } - - #endregion - - #region Public Methods - - public override void OnOpenDocument(PdfWriter writer, iTextSharp.text.Document document) - { - total = writer.DirectContent.CreateTemplate(100, 100); - total.BoundingBox = new Rectangle(-20, -20, 100, 100); - helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); - } - - public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document) - { - PdfContentByte cb = writer.DirectContent; - - cb.SaveState(); - - if (HeaderTable != null) - HeaderTable.WriteSelectedRows(0, 2, 36, document.Top + 44, cb); - String text = "Page " + writer.PageNumber + " of "; - float textBase = document.Bottom - 19;//20; - cb.BeginText(); - cb.SetFontAndSize(helv, ptSize); - - float posCenter = document.Left + ((document.Right - document.Left) / 2) - (helv.GetWidthPoint(text + "XX", ptSize) / 2); - cb.SetTextMatrix(posCenter, textBase); - cb.ShowText(text); - cb.EndText(); - cb.AddTemplate(total, posCenter + helv.GetWidthPoint(text, ptSize), textBase); - cb.RestoreState(); - - AddVolianFooter(writer, document); - AddDateFooter(writer, document); - } - - public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) - { - total.BeginText(); - total.SetFontAndSize(helv, ptSize); - total.SetTextMatrix(0, 0); - total.ShowText((writer.PageNumber - 1).ToString()); - total.EndText(); - - base.OnCloseDocument(writer, document); - } - - #endregion - - #region Private Methods - - private void AddVolianFooter(PdfWriter writer, iTextSharp.text.Document document) - { - PdfContentByte cb = writer.DirectContent; - cb.SaveState(); - String text = _ByLine;//"PROMS Search Results"; - float textBase = document.Bottom - 19;//20; - float textSize = helv.GetWidthPoint(text, ptSize); - cb.BeginText(); - cb.SetFontAndSize(helv, ptSize); - cb.SetTextMatrix(document.Left, textBase); - cb.ShowText(text); - cb.EndText(); - cb.RestoreState(); - } - - private void AddDateFooter(PdfWriter writer, iTextSharp.text.Document document) - { - PdfContentByte cb = writer.DirectContent; - cb.SaveState(); - String text = DateTime.Today.ToShortDateString(); - float textBase = document.Bottom - 19;//20; - float textSize = helv.GetWidthPoint(text, ptSize); - float posRight = document.Right - helv.GetWidthPoint(text, ptSize); - cb.BeginText(); - cb.SetFontAndSize(helv, ptSize); - cb.SetTextMatrix(posRight, textBase); - cb.ShowText(text); - cb.EndText(); - cb.RestoreState(); - } - - #endregion - } + // B2022-026 New code for RO Memory reduction - now use SQL tables instead of building dictionarys to get RO values + public class PDFReport + { + #region Enums + + public enum ReportType + { + SearchResults = 0, + LibraryDocUsage = 1, + ReferencedObjectsUsage = 2, + TransitionUsage = 3, + ReferencedObjectSummary = 4, + ReferencedObjectComplete = 5 + } + + #endregion + + #region Fields + + private PdfWriter _MyPdfWriter; + private string _SearchString; + private readonly int _ReportType = 0; + private readonly string _ByLine; + private readonly bool _SortUsageByProcedure = false; + private readonly string _RODataFile = string.Empty; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List _ROList; + private readonly ROFSTLookup _ROFSTLookup; + private readonly bool _IncludeMissingROs = false; + private readonly bool _ConvertCaretToDelta = true; + private readonly bool _IncludeEmptyROFields = false; + + private readonly string _PaperSize = "Letter"; // C2020-002 paper size is now set in the format files + private string _RegexSearchString = null; + private ArrayList ProcSetList; + + #endregion + + #region Properties + + public ICollection ResultList { get; set; } + + public string FileName { get; set; } + + public string ReportTitle { get; set; } + + public string TypesSelected { get; set; } + + public bool ShowAnnotations { get; set; } = true; + + public string SearchString + { + get { return _SearchString; } + set { _SearchString = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(value); } + } + + public string SortedBy { get; set; } + + public DocumentInfoList LibDocList { get; set; } + + private string RegexSearchString + { + get + { + if (_RegexSearchString == null) + { + _RegexSearchString = _SearchString; + + // Make it match the smallest matching string + _RegexSearchString = _RegexSearchString.Replace("*", ".*?"); + + // If search string starts with a wildcard use the beginning of line token (^) + if (_RegexSearchString.StartsWith(".*?")) + { + _RegexSearchString = "^" + _RegexSearchString; + } + + // If search string ends with a wildcard use the end of line token ($) + if (_RegexSearchString.EndsWith(".*?")) + { + _RegexSearchString += "$"; + } + + _RegexSearchString = _RegexSearchString.Replace("[", @"\["); + _RegexSearchString = _RegexSearchString.Replace("]", @"\]"); + _RegexSearchString = _RegexSearchString.Replace("(", @"\("); + _RegexSearchString = _RegexSearchString.Replace(")", @"\)"); + } + + return _RegexSearchString; + } + } + + #endregion + + #region Constructors + + /// + /// Search Results Report + /// + /// + /// + /// + /// + /// + /// + public PDFReport(string reportTitle, string typesSelected, ICollection resultList, string fileName, string paperSize, string sortedBy) + { + ResultList = resultList; + FileName = fileName; + ReportTitle = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(reportTitle); + TypesSelected = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(typesSelected); + _ReportType = (int)ReportType.SearchResults; + _ByLine = "PROMS Search Results"; + _PaperSize = paperSize; + SortedBy = sortedBy; // C2019--13 pass in sorted by information + + } + + /// + /// Library Document Report + /// + /// + /// + /// + /// + public PDFReport(string reportTitle, DocumentInfoList libDocList, string fileName, string paperSize) + { + LibDocList = libDocList; + FileName = fileName; + ReportTitle = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(reportTitle); + _ReportType = (int)ReportType.LibraryDocUsage; + _ByLine = "Generated By PROMS"; + _PaperSize = paperSize; + } + + /// + /// RO Usage + /// + /// + /// + /// + /// + /// + /// + public PDFReport(string reportTitle, ICollection resultList, string fileName, bool sortUsageByProcedure, bool includeMissingROs, string paperSize) + { + ResultList = resultList; + FileName = fileName; + ReportTitle = VEPROMS.CSLA.Library.ItemInfo.ConvertToDisplayText(reportTitle); + _ReportType = (int)ReportType.ReferencedObjectsUsage; + _ByLine = "Generated By PROMS"; + _SortUsageByProcedure = sortUsageByProcedure; + _IncludeMissingROs = includeMissingROs; + _PaperSize = paperSize; + } + + /// + /// RO Complete RO Report + /// + /// + /// + /// + /// + /// + /// + /// + public PDFReport(string reportTitle, string roDataFile, string outfile, ROFSTLookup fstlookup, bool convertCaretToDelta, bool includeEmptyROFields, string paperSize) + { + FileName = outfile; + ReportTitle = reportTitle; + _ReportType = (int)ReportType.ReferencedObjectComplete; + _ByLine = "Complete Referenced Objects Report"; + _RODataFile = roDataFile; + _ConvertCaretToDelta = convertCaretToDelta; + _ROFSTLookup = fstlookup; + _IncludeEmptyROFields = includeEmptyROFields; + _PaperSize = paperSize; + } + + /// + /// RO Summary Report + /// + /// + /// + /// + /// + /// + public PDFReport(string reportTitle, string outfile, ROFSTLookup fstlookup, List roList, string paperSize) + { + FileName = outfile; + ReportTitle = reportTitle; + _ReportType = (int)ReportType.ReferencedObjectSummary; + _ByLine = "RO Summary Report"; + _ROFSTLookup = fstlookup; + _ROList = roList; + _PaperSize = paperSize; + } + + #endregion + + #region Public Methods + + public void AddMainRODatabaseTitle(PdfPTable datatable, int dbTitleIndex, Font f2, Color bgColor) + { + string dbTitle = _ROFSTLookup.GetRODatabaseTitle(dbTitleIndex); + + PdfPCell cell = new PdfPCell(new Phrase(dbTitle, f2)) + { + BorderColor = Color.WHITE, + Colspan = 2, + BackgroundColor = bgColor + }; + datatable.AddCell(cell); + } + + public void AddMainPathGroup(PdfPTable datatable, string dvPath, int splitLevel, Font f2, Color bgColor, int colSpan) + { + int level = 0; + StringBuilder sb = new StringBuilder(); + string[] NewPath = dvPath.Split("\x7".ToCharArray()); + string sep = string.Empty; + int n = NewPath.Length; + + for (int j = 1; j < n && j < splitLevel; j++) + { + sb.Append($"{sep}{"".PadLeft(2 * level)}{NewPath[j].Replace("\x11", " ")}").Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); + sep = "\r\n"; + level++; + } + + if (sb.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)) + { + Colspan = colSpan, + BackgroundColor = bgColor, + BorderWidthTop = 1 + }; + + datatable.AddCell(cell); + } + } + + public void AddSubPathGroup(PdfPTable datatable, string oldDVPath, string dvPath, int splitLevel, Font f2, Color bgColor, int colSpan) + { + int level = 0; + StringBuilder sb = new StringBuilder(); + string[] NewPath = dvPath.Split("\x7".ToCharArray()); + string[] OldPath = oldDVPath.Split("\x7".ToCharArray()); + string sep = string.Empty; + int n = NewPath.Length - 1; + + for (int i = 0; i < n; i++) + { + if (OldPath[i] != NewPath[i]) + { + splitLevel = Math.Max(splitLevel, i); + break; + } + } + + if (splitLevel < n) + { + for (int j = splitLevel; j < n; j++) + { + sb.Append($"{sep}{"".PadLeft(2 * level)}{NewPath[j].Replace("\x11", " ")}").Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); + sep = "\r\n"; + level++; + } + + if (sb.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)) + { + Colspan = colSpan, + BackgroundColor = bgColor, + BorderWidthTop = 1 + }; + + datatable.AddCell(cell); + } + } + } + + public void Build() + { + iTextSharp.text.Document document = new iTextSharp.text.Document(PDFPageSize.UsePaperSize(_PaperSize), 36, 36, 36, 36); // C2020-002 paper size is now set in the format files + + if (!CreateResultsPDF(document, _ReportType)) + return; + + try + { + switch (_ReportType) // set in the PDFReport constructor + { + case (int)ReportType.SearchResults: + BuildSearchResultsTable(document); + break; + + case (int)ReportType.LibraryDocUsage: + BuildLibDocUsageReport(document); + break; + + case (int)ReportType.ReferencedObjectsUsage: + if (_SortUsageByProcedure) + BuildROUsageTableByProcedure(document); + else + BuildROUsageTableByRO(document); + break; + + case (int)ReportType.ReferencedObjectComplete: + BuildCompleteROReport(document); + break; + + case (int)ReportType.ReferencedObjectSummary: + BuildROSummaryReport(document); + break; + } + } + catch (Exception ex) + { + document.Add(new Paragraph("Error:")); + + while (ex != null) + { + document.Add(new Paragraph(ex.GetType().Name)); + document.Add(new Paragraph(ex.Message)); + ex = ex.InnerException; + } + } + finally + { + if (document.IsOpen()) + { + //document.Add(new Phrase("End of Search Results",FontFactory.GetFont("Arial",4))); // B2019-089 commented out - used for debug + document.Add(new Phrase(" ", FontFactory.GetFont("Arial", 4))); // B2019-089 - assure output has at least a blank space to prevent error on close + document.Close(); + System.Diagnostics.Process.Start(FileName); + } + } + } + + #endregion + + #region Private Methods + + private string AddGroup(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) + { + int level = 0; + string retval = string.Empty; + StringBuilder sb = new StringBuilder(); + string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); + string[] NewPath = dvPath.Split("\x7".ToCharArray()); + string sep = string.Empty; + bool foundMisMatch = false; + + // n-1 Exclude the "Working Draft" entry from the list + int n = NewPath.Length - 1; + int jstart = (skipFirst) ? 1 : 0; + + if (StripLast) + { + retval = NewPath[--n]; + if (retval.Contains("\x11")) + { + retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number + } + } + + if (n == 0) + { + // B2020-006: 'clean-up' the output string by making string replaces as in 'else' below. + sb.Append(dvPath.Replace("\x11", " ").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\")); + } + else + { + for (int j = jstart; j < n; j++) + { + if (!string.IsNullOrEmpty(NewPath[j]) && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) + { + // B2020-006: Add hard space '\u160?' + sb.Append($"{sep}{"".PadLeft(2 * level)}{NewPath[j].Replace("\x11", " ")}").Replace(@"\u8209?", "-").Replace(@"\u160?", " ").Replace(@"\u9586?", @"\"); + sep = "\r\n"; + foundMisMatch = true; + } + + level++; + } + } + + if (sb.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)) + { + Colspan = 2, + BackgroundColor = bgColor, + BorderWidthTop = 1 + }; + datatable.AddCell(cell); + } + + return retval; + } + + private string AddGroupLibDoc(PdfPTable datatable, string dvPath, string lastDvPath, Font f2, bool StripLast, Color bgColor, bool skipFirst) + { + int level = 0; + string retval = string.Empty; + StringBuilder sb = new StringBuilder(); + string[] OldPath = lastDvPath.Split("\x7".ToCharArray()); + string[] NewPath = dvPath.Split("\x7".ToCharArray()); + string sep = string.Empty; + bool foundMisMatch = false; + int n = NewPath.Length - 1; + int jstart = (skipFirst) ? 1 : 0; + + if (StripLast) + { + retval = NewPath[--n]; + if (retval.Contains("\x11")) + { + retval = retval.Substring(0, retval.IndexOf("\x11")); // this is the step number + } + } + + //If no colons output the entire text + if (n == 0) + { + sb.Append(dvPath); + } + else + { + for (int j = jstart; j < n; j++) + { + if (!string.IsNullOrEmpty(NewPath[j]) && (foundMisMatch || OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) + { + sb.Append($"{sep}{"".PadLeft(2 * level)}{NewPath[j].Replace("\x11", " ")}").Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); + sep = "\r\n"; + foundMisMatch = true; + } + + level++; + } + } + + if (sb.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(sb.ToString(), f2)) + { + Colspan = 2, + BackgroundColor = bgColor, + BorderWidthTop = 1 + }; + datatable.AddCell(cell); + } + + return retval; + } + + private void AddProcedureSectionGroup(PdfPTable datatable, string curProc, string lastProc, string curSect, string lastSect, Font f2, Color bgColor) + { + string headerText = string.Empty; + + if (curProc != lastProc) + headerText = $"{curProc}\r\n"; + + if (curSect != lastSect) + headerText += $" {curSect}"; + + if (headerText.Length > 0) + { + headerText = headerText.Replace(@"\u8209?", "-");// repace unicode with dash char + headerText = headerText.Replace(@"\u160?", " "); // replace Hard Space with normal Space + headerText = headerText.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash + + PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)) + { + Colspan = 2, + BackgroundColor = bgColor, + BorderWidthTop = 1 + }; + datatable.AddCell(cell); + } + } + + private string GetCurProcNum(string path) + { + string[] NewPath = path.Split("\x7".ToCharArray()); + string pnumtitle = NewPath[1]; + pnumtitle = pnumtitle.Replace('\x11', ' '); + + return pnumtitle; + } + + private string GetCurSectionNumTitle(ItemInfo itm) + { + string rtnstr = string.Empty; + + if (itm.ActiveSection != null) + { + rtnstr = itm.ActiveSection.DisplayNumber; + if (rtnstr.Length > 0) rtnstr += " "; + rtnstr += itm.ActiveSection.DisplayText; + } + + return rtnstr; // string containing section and subsection number/titles + } + + private int FindSpitLevel() + { + int level = 0; + string lastPath = string.Empty; + + foreach (string p in ProcSetList) + { + string[] NewPath = p.Split("\x7".ToCharArray()); + + if (lastPath != string.Empty) + { + string[] OldPath = lastPath.Split("\x7".ToCharArray()); + int n = NewPath.Length; + int lvl = 0; + bool foundMisMatch = false; + + for (int j = 0; j < n && !foundMisMatch; j++) + { + if (NewPath[j] != string.Empty && (OldPath.Length < j + 1 || NewPath[j] != OldPath[j])) + { + foundMisMatch = true; + } + + lvl++; + } + + if (level == 0) + level = lvl; + + if (foundMisMatch) + level = Math.Min(level, lvl); + } + + lastPath = p; + + if (ProcSetList.Count == 1) + { + level = NewPath.Length - 1; + } + } + + return level; + } + + /// + /// Attempt to open a file for the PDF output. + /// If the file cannot be opened because it is in use, try adding a suffix + /// If the file cannot be opened for some other reason, display an error message + /// + /// + /// + private bool CreateResultsPDF(iTextSharp.text.Document document, int typ) + { + int topMargin = 36; + + switch (typ) + { + case (int)ReportType.LibraryDocUsage: + topMargin = 80; // Add some space for the Report Header for the Library Document Report + break; + } + + bool result = false; + string suffix = string.Empty; + int i = 0; + + // Try to open a file for creating the PDF. + while (result == false) + { + string fileName = FileName.ToLower().Replace(".pdf", $"{suffix}.pdf"); + + try + { + _MyPdfWriter = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); + _MyPdfWriter.PageEvent = new MyPageHelper(_ByLine); // JSJ - 7/8/2011 + + document.SetMargins(36, 36, topMargin, 36); + document.Open(); + + FileName = fileName; + + result = true; + } + catch (System.IO.IOException exIO) + { + if (exIO.Message.Contains("because it is being used by another process")) + { + suffix = string.Format("_{0}", ++i);// If this file is in use, increment the suffix and try again + } + else // If some other error, display a message and don't print the results + { + ShowException(exIO); + return false; + } + } + catch (Exception ex) + { + ShowException(ex); + return false; // Could not open the output file + } + } + + return true; + } + + /// + /// Use Cells within Cells to see if I can limit the way Cells break from Page to Page + /// + /// + private void BuildSearchResultsTable(iTextSharp.text.Document document) + { + float[] headerwidths = { 20, 80 }; + PdfPTable datatable = new PdfPTable(1); + PdfPTable colHeader = new PdfPTable(headerwidths); + //datatable.FooterRows = 1; + datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; + datatable.LockedWidth = true; + + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)) + { + HorizontalAlignment = Element.ALIGN_CENTER, + BackgroundColor = new Color(0xD0, 0xF0, 0xF0) // light cyan + }; + datatable.AddCell(cell); + + // C2019-013 add sorted by information if sorting is used + cell = new PdfPCell(new Phrase(TypesSelected + ((SortedBy.Length > 0) ? string.Format("\n{0}", SortedBy) : string.Empty), f3)) + { + HorizontalAlignment = Element.ALIGN_LEFT, + BackgroundColor = new Color(0xD0, 0xF0, 0xF0) // light cyan + }; + datatable.AddCell(cell); + + BuildSearchResultsProcSetList(); + datatable.HeaderRows = 4 + (ProcSetList.Count == 1 ? 1 : 0); + int splitAt = FindSpitLevel(); // find the split level of the common path - for all procedure sets that use these library documents + + Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // new Color(0xD0, 0xF0, 0xD0); + datatable.DefaultCell.Padding = 0; // this removes a white space after the header was set to 4; + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; + AddCell(colHeader, "Step", f2, subHeaderColor); + AddCell(colHeader, "Text", f2, subHeaderColor); + + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; + string lastPath = string.Empty; + Color AnnoColor = new Color(0xFF, 0xFF, 0xC0); // yellow + Color TextColor = Color.WHITE; + Color WordSectColor = new Color(0xE8, 0xE8, 0xE8);// light grey + Color StepSectColor = new Color(0xE7, 0xFF, 0xE7); // lighter green + PdfPTable subTable = new PdfPTable(headerwidths); + string lastProcNum = string.Empty; + string lastDVPath = string.Empty; + string lastSectNumAndTitle = string.Empty; + List processedItems = new List(); + + foreach (ItemInfo item in ResultList) + { + if (!processedItems.Contains(item.ItemID)) + { + processedItems.Add(item.ItemID); + + if (lastDVPath != item.SearchDVPath) + { + datatable.AddCell(subTable); + subTable = new PdfPTable(headerwidths); + AddMainPathGroup(datatable, item.SearchDVPath, splitAt, f2, new Color(0xB0, 0xF0, 0xF0), 0);// little brighter cyan + datatable.AddCell(colHeader); + lastProcNum = string.Empty; + lastSectNumAndTitle = string.Empty; // C2020-019 reset we are processing a different procedure set + } + + lastDVPath = item.SearchDVPath; + string curProcNum = GetCurProcNum(item.SearchPath); + + if (subTable.Rows.Count > 0) // prevent first page from being blank + { + datatable.AddCell(subTable); + subTable = new PdfPTable(headerwidths); + } + + if (curProcNum != lastProcNum) + { + lastSectNumAndTitle = string.Empty; // C2020-019 reset we are processing a different procedure + } + + lastProcNum = curProcNum; + + // B2020-006: When doing a section, don't remove the last item or the procedure title won't print (if section is only item found w/ search string) + string stepPath = AddGroup(subTable, item.SearchPath ?? item.ShortPath, lastPath, f2, !item.IsSection, new Color(0xC0, 0xFF, 0xC0), true); // light green for procedure number and title + + // C2020-019 add section number and title if is different from last item and it is not a Word Section (item will be a section if search item was found in a Word section) + string curSectNumTitle = GetCurSectionNumTitle(item); + + if (curSectNumTitle != string.Empty && curSectNumTitle != lastSectNumAndTitle && !item.IsSection) + { + AddColSpanCell(subTable, curSectNumTitle, f2, StepSectColor, 2, 0); + lastSectNumAndTitle = curSectNumTitle; + } + + lastPath = item.SearchPath ?? item.ShortPath; + stepPath = BuildStepTab(item); + AddCell(subTable, stepPath, f2, (item.IsSection ? WordSectColor : TextColor)); + AddCell(subTable, item.DisplayText, f2, (item.IsSection ? WordSectColor : TextColor)); + + if (ShowAnnotations && item.ItemAnnotationCount > 0) + { + foreach (AnnotationInfo ai in item.ItemAnnotations) + { + AddCell(subTable, ai.MyAnnotationType.Name, f2, AnnoColor); + AddCell(subTable, ai.SearchText, f2, AnnoColor); + } + } + } + } + + datatable.AddCell(subTable); + document.Add(datatable); + } + + private void AddCell(PdfPTable datatable, string str, iTextSharp.text.Font fnt, Color bgColor) + { + + Phrase p = BuildPhrase2(str, fnt); + PdfPCell cell = new PdfPCell(p) + { + PaddingBottom = 4, + BackgroundColor = bgColor + }; + + datatable.AddCell(cell); + } + + private void AddColSpanCell(PdfPTable datatable, string str, iTextSharp.text.Font fnt, Color bgColor, int span, int txtAlign) + { + Phrase p = BuildPhrase2(str, fnt); + PdfPCell cell = new PdfPCell(p) + { + PaddingBottom = 4, + BackgroundColor = bgColor, + Colspan = span, + HorizontalAlignment = txtAlign + }; + + datatable.AddCell(cell); + } + private Phrase BuildPhrase2(string str, Font fnt) + { + Phrase p = new Phrase(); + int lastIndex = 0; + + if ((_SearchString ?? string.Empty) != string.Empty) + { + Regex reg = new Regex(RegexSearchString, RegexOptions.Multiline | RegexOptions.IgnoreCase); + + foreach (Match m in reg.Matches(str)) + { + if (m.Index > 0) + p.Add(new Phrase(str.Substring(lastIndex, m.Index - lastIndex), fnt)); + + Chunk chk = new Chunk(m.Value, fnt); + chk.SetBackground(Color.YELLOW); + p.Add(chk); + + lastIndex = m.Index + m.Length; + } + } + + p.Add(new Phrase(str.Substring(lastIndex), fnt)); + + return p; + } + + private void BuildLibDocUsageReport(iTextSharp.text.Document document) + { + // Adjusted from 20,80 to 25,75 to account for long Procedure Numbers + float[] headerwidths = { 25, 75 }; + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + BuildLibDocProcSetList(); + + int splitAt = FindSpitLevel() - 1; // find the split level of the common path - for all procedure sets that use these library documents + Color AnnoBackgroundColor = new Color(0xFF, 0xFF, 0xC0); + Color TextBackgroundColor = Color.WHITE; + MyPageHelper pghlp = _MyPdfWriter.PageEvent as MyPageHelper; + pghlp.HeaderTable = LibDocTable(document, headerwidths, f2); + + foreach (DocumentInfo di in LibDocList) + { + PdfPTable subtable; + subtable = BuildSubTable(document, headerwidths); + + AddGroupLibDoc(subtable, di.DocumentTitle, string.Empty, f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title + + if (di.DocumentConfig.LibDoc_Comment != null && di.DocumentConfig.LibDoc_Comment.Length > 0) + { + AddCell(subtable, "Comment", f2, AnnoBackgroundColor); + AddCell(subtable, di.DocumentConfig.LibDoc_Comment, f2, AnnoBackgroundColor); // lib doc comment + } + + if (di.DocumentEntries == null || di.DocumentEntries.Count == 0) + { + AddGroupLibDoc(subtable, "* No References To This Library Document *", string.Empty, f2, false, TextBackgroundColor, false); // Library Document Title + } + else + { + subtable.HeaderRows = 2; + System.Collections.ArrayList LibDocUsageList = GetSortedItemInfoList(di.LibraryDocumentUsageList); + string lastDvPath = string.Empty; + + foreach (ItemInfo item in LibDocUsageList)//di.LibraryDocumentUsageList) + { + if (item.SearchDVPath != lastDvPath) + { + if (lastDvPath != string.Empty) + { + document.Add(subtable); + subtable = BuildSubTable(document, headerwidths); + subtable.HeaderRows = 2; + AddGroupLibDoc(subtable, di.DocumentTitle, string.Empty, f2, false, new Color(0xC0, 0xFF, 0xC0), false); // Library Document Title + } + + AddSubPathGroup(subtable, lastDvPath, item.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 2);//new Color(0xC0, 0xFF, 0xC0)); + } + + lastDvPath = item.SearchDVPath; + string ProcNumber = item.MyProcedure.ProcedureConfig.Number; + ProcNumber = ProcNumber.Replace(@"\u8209?", "-"); // repace unicode with dash char + ProcNumber = ProcNumber.Replace(@"\u160?", " "); // replace Hard Space with normal Space + ProcNumber = ProcNumber.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash + AddCell(subtable, ProcNumber, f2, TextBackgroundColor); + AddCell(subtable, $"{item.DisplayNumber} - {item.DisplayText}", f2, TextBackgroundColor); + } + + } + + document.Add(subtable); + } + } + + private PdfPTable LibDocTable(iTextSharp.text.Document document, float[] headerwidths, iTextSharp.text.Font f2) + { + PdfPTable datatable = new PdfPTable(1);// (headerwidths); + PdfPTable colheader = new PdfPTable(headerwidths); + datatable.HeaderRows = 2; + datatable.KeepTogether = false; + datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; + datatable.LockedWidth = true; + + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)) + { + HorizontalAlignment = Element.ALIGN_CENTER, + BackgroundColor = new Color(0xD0, 0xF0, 0xF0) + }; + datatable.AddCell(cell); + + Color subHeaderColor = new Color(0xD0, 0xF0, 0xD0); + datatable.DefaultCell.Padding = 4; + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; + AddCell(colheader, "Procedure", f2, subHeaderColor); + AddCell(colheader, "Section", f2, subHeaderColor); + datatable.AddCell(colheader); + + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; + + return datatable; + } + + private void AddROUsages(ItemInfo item, Dictionary> roUse) + { + if (item != null && !string.IsNullOrEmpty(item.FoundROID)) + { + string roid = item.FoundROID; + + if (roUse.ContainsKey(roid)) + { + ((List)roUse[roid]).Add(item); + } + else + { + List itmIfoLst = new List + { + item + }; + roUse.Add(roid, itmIfoLst); + } + } + } + + private void PutROusageForProcedure(PdfPTable curTable, Dictionary> rosused, float[] headerwidths) + { + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + + foreach (string roKey in rosused.Keys) + { + PdfPTable rotable = new PdfPTable(headerwidths); + string rotitle = string.Empty; + + foreach (ItemInfo itm in rosused[roKey]) + { + if (string.IsNullOrEmpty(rotitle)) + { + rotitle = GetROTitleAndGroup(roKey, itm); + + if (!string.IsNullOrEmpty(rotitle)) + { + PdfPCell ROTitleCell = new PdfPCell(new Phrase(rotitle, f2)) + { + Colspan = 2, + HorizontalAlignment = Element.ALIGN_LEFT + }; + + if (rotitle.StartsWith("Missing RO")) + { + ROTitleCell.BackgroundColor = Color.PINK; + } + else + { + ROTitleCell.BackgroundColor = new Color(0xDC, 0xE7, 0xC9); //new Color(0xD0, 0xF0, 0xD0);//ligt green //new Color(0xC8, 0xC8, 0x91);//(0xAF, 0xD8, 0xD8);//(0xF5, 0xE4, 0xA0); + } + + rotable.AddCell(ROTitleCell); // put RO value and description + } + } + + string stepnum = string.Empty; + string sectitle = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayText : string.Empty; + + if (itm.IsSection) + { + stepnum = (itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : string.Empty; + } + else + { + stepnum = BuildStepTab(itm); + } + + AddCell(rotable, stepnum, f2, Color.WHITE); + AddCell(rotable, itm.DisplayText, f2, Color.WHITE); + + } + + curTable.AddCell(rotable); + } + } + + private void BuildROUsageTableByProcedure(iTextSharp.text.Document document) + { + Dictionary> roUse = new Dictionary>(); + float[] headerwidths = { 20, 80 }; + PdfPTable datatable = new PdfPTable(1); + PdfPTable colHeader = new PdfPTable(headerwidths); + datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; + datatable.LockedWidth = true; + + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK); + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)) + { + HorizontalAlignment = Element.ALIGN_CENTER, + //cell.Colspan = 2; + BackgroundColor = new Color(0xD0, 0xF0, 0xF0) // light blue + }; + datatable.AddCell(cell); + + BuildSearchResultsProcSetList(); + datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); + int splitAt = FindSpitLevel(); // find the split level of the common path + + Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // light blue //new Color(0xD0, 0xF0, 0xD0);//ligt green + datatable.DefaultCell.Padding = 4; + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; + + // This puts "Step" and "Text" column headers at the bottom of the page + AddCell(colHeader, "Step", f2, subHeaderColor); + AddCell(colHeader, "Text", f2, subHeaderColor); + datatable.AddCell(colHeader); + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; + PdfPTable subTable = new PdfPTable(headerwidths); + datatable.AddCell(subTable); + + string lastProcNum = string.Empty; + string lastSection = string.Empty; + //CSM B2021-043 Step numbering is out of order in RO usage report if RO values exist on steps 10 or higher. + //setting this to something other than empty - otherwise will not print first initial header + string lastDVPath = "start"; + if (ResultList.Count > 0) + { + foreach (ItemInfo item in ResultList) + { + // Check Doc Version path + // if more than one procedure set is in the report data, then + // we will output the procedure set title inside the grouping of each RO + // otherwise, if we are reporting on only one procedure set, print the + // procedure set title at the top of the report (once). + if (lastDVPath != "" && lastDVPath != item.SearchDVPath) + { + //CSM B2021-043 Step numbering is out of order in RO usage report if RO values exist on steps 10 or higher. + //was placing last item from the precious section in the new section + //place it before starting the new section and then clear items + PutROusageForProcedure(datatable, roUse, headerwidths); + roUse.Clear(); + + subTable = new PdfPTable(headerwidths); + AddMainPathGroup(datatable, item.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); + lastProcNum = string.Empty; + lastSection = string.Empty; + } + + lastDVPath = item.SearchDVPath; + //check for different procedure number + string curProcNum = GetCurProcNum(item.SearchPath); + string curSection = GetCurSectionNumTitle(item); + + if (!string.IsNullOrEmpty(lastProcNum) && (curProcNum != lastProcNum)) + { + if (roUse.Count > 0) + { + PutROusageForProcedure(datatable, roUse, headerwidths); + roUse.Clear(); + } + + lastSection = string.Empty; + } + + if (!string.IsNullOrEmpty(lastSection) && (curSection != lastSection)) + { + if (roUse.Count > 0) + { + PutROusageForProcedure(datatable, roUse, headerwidths); + roUse.Clear(); + } + } + + AddROUsages(item, roUse); // add the used ro to the list for this procedure + AddProcedureSectionGroup(datatable, curProcNum, lastProcNum, curSection, lastSection, f2, new Color(0xC0, 0xFF, 0xC0)); + + lastProcNum = curProcNum; + lastSection = curSection; + } + } + else + { // B2022-093 put out a message if no RO Usages were found + cell = new PdfPCell(new Phrase("No RO Usage Information Found", f3)) + { + HorizontalAlignment = Element.ALIGN_LEFT + }; + //cell.BackgroundColor = new Color(0xD0, 0xF0, 0xF0); // light blue + datatable.AddCell(cell); + } + PutROusageForProcedure(datatable, roUse, headerwidths); + + document.Add(datatable); + } + + private void AddProcROUse(ItemInfo item, Dictionary> procRoUse) + { + string dictKey = $"{GetCurProcNum(item.SearchPath)} {GetCurSectionNumTitle(item)}"; + + if (!string.IsNullOrEmpty(dictKey)) + { + if (procRoUse.ContainsKey(dictKey)) + { + ((List)procRoUse[dictKey]).Add(item); + } + else + { + List itmIfoLst = new List + { + item + }; + procRoUse.Add(dictKey, itmIfoLst); + } + } + } + + private void PutStepListForProcedure(PdfPTable rotable, Dictionary sortedStepList) + { + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + + foreach (ItemInfo itm in sortedStepList.Values) + { + string stepnum = (itm.IsSection && itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : BuildStepTab(itm);// C2018-003 fixed use of getting the active section + AddCell(rotable, stepnum, f2, Color.WHITE); + AddCell(rotable, itm.DisplayText, f2, Color.WHITE); + } + + sortedStepList.Clear(); + } + + private void PutROusageForROID(PdfPTable curTable, Dictionary> procRoUse, float[] headerwidths, int splitAt, bool moreThanOneProcSet) + { + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + + Dictionary sortedStepList = new Dictionary(); + string lastProcKey = string.Empty; + string lastProcNumTitle = string.Empty; + string lastDVPath = string.Empty; + string curProcNumTitle; + + foreach (string procKey in procRoUse.Keys) + { + PdfPTable rotable = new PdfPTable(headerwidths); + + foreach (ItemInfo itm in procRoUse[procKey]) + { + bool didProcSetTitle = false; + // Check Doc Version path + // where we are reporting on more than one procedure set + // output the procedure set title within the RO value grouping on the report + if (moreThanOneProcSet && lastDVPath != itm.SearchDVPath) + { + AddMainPathGroup(curTable, itm.SearchDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); + didProcSetTitle = true; + } + else + { + didProcSetTitle = false; + } + + lastDVPath = itm.SearchDVPath; + + if (didProcSetTitle || procKey != lastProcKey) + { + if (sortedStepList.Count > 0) + { + PutStepListForProcedure(rotable, sortedStepList); + } + + string procNumTitleSect = string.Empty; + curProcNumTitle = GetCurProcNum(itm.SearchPath); + + if (lastProcNumTitle == string.Empty || lastProcNumTitle != curProcNumTitle) + { + procNumTitleSect = $"{curProcNumTitle}\r\n"; + lastProcNumTitle = curProcNumTitle; + } + + procNumTitleSect += " " + GetCurSectionNumTitle(itm); + procNumTitleSect = procNumTitleSect.Replace(@"\u8209?", "-"); // repace unicode with dash char + procNumTitleSect = procNumTitleSect.Replace(@"\u160?", " "); // replace Hard Space with normal Space + procNumTitleSect = procNumTitleSect.Replace(@"\u9586?", @"\"); // replace backslash symbol with a backslash + PdfPCell ProcTitleCell = new PdfPCell(new Phrase(procNumTitleSect, f2)) + { + Colspan = 2, + HorizontalAlignment = Element.ALIGN_LEFT, + BackgroundColor = new Color(0xDC, 0xE7, 0xC9) //new Color(0xD0, 0xF0, 0xD0);//ligt green //new Color(0xC8, 0xC8, 0x91);//(0xAF, 0xD8, 0xD8);//(0xF5, 0xE4, 0xA0); + }; + rotable.AddCell(ProcTitleCell); // put RO value and description + lastProcKey = procKey; + } + + string stepnum = (itm.IsSection && itm.ActiveSection != null) ? itm.ActiveSection.DisplayNumber : BuildStepTab(itm);// C2018-003 fixed use of getting the active section + string itemkey = $"{stepnum} {itm.ItemID}"; // add ItemId to stepnum, sometimes we have idential stepnum text for different steps (ex: blank section numbers) + + if (!sortedStepList.ContainsKey(itemkey)) + { + sortedStepList.Add(itemkey, itm); + } + } + + if (sortedStepList.Count > 0) + { + PutStepListForProcedure(rotable, sortedStepList); + } + + curTable.AddCell(rotable); + } + } + + private string GetROTitleAndGroup(string roid, ItemInfo itm) + { + string rotitle = string.Empty; + + ROFSTLookup myrofstlookup = (itm == null) ? _ROFSTLookup : itm.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(itm.MyDocVersion); + + List roTitleList = myrofstlookup.GetROTitleAndGroupPath(roid, _IncludeMissingROs, _ConvertCaretToDelta); + + if (roTitleList != null && roTitleList.Count > 0) + { + for (int cnt = 0; cnt < roTitleList.Count; cnt++) + { + if (cnt == roTitleList.Count - 1) // Last roTitle in list, don't add a NewLine character after the value + rotitle += roTitleList[cnt]; + else + rotitle += $"{roTitleList[cnt]}\n "; + } + } + + return rotitle; + } + + private void AddROHeaderGroup(PdfPTable datatable, string curROID, ItemInfo itm, Font f2, Color bgColor) + { + string headerText = GetROTitleAndGroup(curROID, itm); + + if (!string.IsNullOrEmpty(headerText) && headerText.Length > 0) + { + PdfPCell cell = new PdfPCell(new Phrase(headerText, f2)) + { + Colspan = 2, + BackgroundColor = (headerText.StartsWith("Missing RO")) ? Color.PINK : bgColor, + BorderWidthTop = 1 + }; + + datatable.AddCell(cell); + } + } + + private void BuildROUsageTableByRO(iTextSharp.text.Document document) + { + Dictionary> procRoUse = new Dictionary>(); + + float[] headerwidths = { 20, 80 }; + PdfPTable datatable = new PdfPTable(1); + PdfPTable colHeader = new PdfPTable(headerwidths); + //datatable.FooterRows = 1; + datatable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; + datatable.LockedWidth = true; + + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)) + { + HorizontalAlignment = Element.ALIGN_CENTER, + BackgroundColor = new Color(0xD0, 0xF0, 0xF0) // light blue + }; + datatable.AddCell(cell); + + BuildSearchResultsProcSetList(); + datatable.HeaderRows = 2;//3 + (ProcSetList.Count == 1 ? 1 : 0); + int splitAt = FindSpitLevel(); // find the split level of the common path + + Color subHeaderColor = new Color(0xD0, 0xF0, 0xF0); // light blue //new Color(0xD0, 0xF0, 0xD0);//ligt green + datatable.DefaultCell.Padding = 4; + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; + // This puts "Step" and "Text" column headers at the bottom of the page + AddCell(colHeader, "Step", f2, subHeaderColor); + AddCell(colHeader, "Text", f2, subHeaderColor); + datatable.AddCell(colHeader); + + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; + PdfPTable subTable = new PdfPTable(headerwidths); + datatable.AddCell(subTable); + + string lastDVPath = string.Empty; + string lastROID = string.Empty; + bool moreThanOneProcSet = false; + bool printedSetTitle = false; + bool printedROHeader = false; + ItemInfo lastItem = null; + + if (ResultList.Count == 0) + { + PdfPCell cell2 = new PdfPCell(new Phrase("Selected RO is not used", f2)) + { + Colspan = 0, + BorderWidthTop = 1 + }; + datatable.AddCell(cell2); + document.Add(datatable); + + return; + } + + foreach (ItemInfo item in ResultList) + { + bool differentProcSet = false; + bool differentRO = false; + + // Check Doc Version path + // if more than one procedure set is in the report data, then + // we will output the procedure set title inside the grouping of each RO + // otherwise, if we are reporting on only one procedure set, print the + // procedure set title at the top of the report (once). + if (!string.IsNullOrEmpty(lastDVPath) && lastDVPath != item.SearchDVPath) + { + moreThanOneProcSet = true; + differentProcSet = true; + } + + lastDVPath = item.SearchDVPath; + + // Check for different ROID + string curROID = item.FoundROID; + differentRO = (!string.IsNullOrEmpty(lastROID) && !string.IsNullOrEmpty(curROID) && curROID.Substring(0, 12) != lastROID.Substring(0, 12)); + + if (procRoUse.Count > 0 && (differentProcSet || differentRO)) + { + if (!moreThanOneProcSet && !printedSetTitle) + { + AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); + printedSetTitle = true; + } + + if (!printedROHeader) + { + AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); + printedROHeader = true; + } + + PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); + procRoUse.Clear(); + + differentProcSet = false; + } + + if (differentRO) + { + printedROHeader = false; + } + + AddProcROUse(item, procRoUse); + + lastROID = curROID; + lastItem = item; + } + + if (!moreThanOneProcSet && !printedSetTitle) + AddMainPathGroup(datatable, lastDVPath, splitAt, f2, Color.LIGHT_GRAY, 0); + + if (!printedROHeader) + AddROHeaderGroup(datatable, lastROID, lastItem, f2, new Color(0xC0, 0xFF, 0xC0)); + + PutROusageForROID(datatable, procRoUse, headerwidths, splitAt, moreThanOneProcSet); + + document.Add(datatable); + } + + private void BuildSearchResultsProcSetList() + { + ProcSetList = new System.Collections.ArrayList(); + foreach (ItemInfo item in ResultList) + { + if (!ProcSetList.Contains(item.SearchDVPath)) + ProcSetList.Add(item.SearchDVPath); + } + } + + private void BuildLibDocProcSetList() + { + ProcSetList = new System.Collections.ArrayList(); + foreach (DocumentInfo di in LibDocList) + { + if (di.LibraryDocumentUsageList != null && di.LibraryDocumentUsageList.Count > 0) + foreach (ItemInfo item in di.LibraryDocumentUsageList) + { + if (!ProcSetList.Contains(item.SearchDVPath)) + ProcSetList.Add(item.SearchDVPath); + } + } + } + + private ArrayList GetSortedItemInfoList(ItemInfoList orgIFL) + { + System.Collections.ArrayList libDocProcSetList = new System.Collections.ArrayList(); + System.Collections.ArrayList rtnIFL = new System.Collections.ArrayList(); + foreach (ItemInfo item in orgIFL) + { + if (!libDocProcSetList.Contains(item.SearchDVPath)) + libDocProcSetList.Add(item.SearchDVPath); + } + foreach (string pset in libDocProcSetList) + { + foreach (ItemInfo item in orgIFL) + { + if (item.SearchDVPath.Equals(pset)) + rtnIFL.Add(item); + } + } + return rtnIFL; + } + + private void BuildCompleteROReport(iTextSharp.text.Document document) + { + CompleteROReport compRORpt = new CompleteROReport(_MyPdfWriter, document, _RODataFile, _ConvertCaretToDelta, _IncludeEmptyROFields) + { + F10 = pdf.GetFont("Courier New", 10, 0, Color.BLACK), + F10Bold = pdf.GetFont("Courier New", 10, 1, Color.BLACK), + F12 = pdf.GetFont("Courier New", 12, 0, Color.BLACK), + F12Bold = pdf.GetFont("Courier New", 12, 1, Color.BLACK), + // C2017-036 Get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + F14 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK), + + //B2022 - 083: Support Conditional RO Values + ROFstID = _ROFSTLookup.RofstID + }; + + compRORpt.Run(); + } + + private string GetROTitleAndGroupsForSummary(List roTitleList, List prevROTitleList) + { + string rotitle = string.Empty; + string indent = string.Empty; + + for (int icnt = 0; icnt < roTitleList.Count; icnt++) + { + indent += " "; + + if (icnt == roTitleList.Count - 1) + { + rotitle += indent + roTitleList[icnt]; // this should be the ro description + break; //break out of for loop + } + + if (prevROTitleList == null || (icnt < roTitleList.Count && icnt < prevROTitleList.Count && prevROTitleList[icnt] != roTitleList[icnt])) + { + if (rotitle == string.Empty && prevROTitleList != null) + rotitle = "\n"; + + rotitle += $"{indent}{roTitleList[icnt]}\n"; + } + } + + return rotitle; + } + + private List AddROHeaderGroupForSummary(PdfPTable datatable, string curROID, List prevROTitleList, Font f2) + { + List roTitleList = _ROFSTLookup.GetROTitleAndGroupPath(curROID, _IncludeMissingROs, _ConvertCaretToDelta); + string headerText = GetROTitleAndGroupsForSummary(roTitleList, prevROTitleList); + + if (headerText.Length > 0) + { + Paragraph pgh = new Paragraph(headerText, f2); + PdfPCell cell = new PdfPCell(pgh) + { + FollowingIndent = 72, + Colspan = 2, + BorderColor = Color.WHITE, + BackgroundColor = Color.WHITE, + BorderWidthTop = 1 + }; + + datatable.AddCell(cell); + } + + return roTitleList; + } + + private void BuildROSummaryReport(iTextSharp.text.Document document) + { + PdfPTable datatable = new PdfPTable(1) + { + TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin, + LockedWidth = true + }; + + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + iTextSharp.text.Font f1 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 14, 1, Color.BLACK); + iTextSharp.text.Font f2 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK); + iTextSharp.text.Font f3 = pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 1, Color.BLACK); + + PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, f1)) + { + HorizontalAlignment = Element.ALIGN_CENTER, + //cell.Colspan = 2; + BackgroundColor = Color.WHITE,//new Color(0xD0, 0xF0, 0xF0); // light blue + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); + + string roFSTDateTime = $"RO.FST Last Created: {_ROFSTLookup.GetRoFSTdts().ToLongDateString()} @ {_ROFSTLookup.GetRoFSTdts().ToShortTimeString()}\n "; + cell = new PdfPCell(new Phrase(roFSTDateTime, f2)) + { + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); + + datatable.HeaderRows = 2; + datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; + string lastROID = string.Empty; + List prevROTitleList = null; + int lastDBindex = -1; + + foreach (string curROID in _ROList) + { + string[] tmp = curROID.TrimEnd(',').Split(':'); //curROID.Split(':');// this is the RO FST id number (for plants with multiple RO FSTs) + string rolst = (tmp.Length == 2) ? tmp[1] : tmp[0]; + string[] roIdslst = rolst.Split(','); + + foreach (string cROID in roIdslst) + { + if (string.IsNullOrEmpty(cROID)) + break; + + if (cROID.Length == 4) + ProcessROdb(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); + else + ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); + } + } + + document.Add(datatable); + } + + private void ProcessROdb(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, string cROID) + { + ROFSTLookup.rodbi roDBI = _ROFSTLookup.GetRODatabase(cROID, true, true); + + if (roDBI.children != null && roDBI.children.Length > 0) + { + for (int i = 0; i < roDBI.children.Length; i++) + { + ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, roDBI.children[i]); + } + } + else + { + ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cROID); + + cell = new PdfPCell(new Phrase(" ", f2)) + { + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); + cell = new PdfPCell(new Phrase("-- No Information Entered --", f2)) + { + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); + } + } + + private void ProcessROChild(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, ROFSTLookup.rochild cld) + { + if (cld.children == null || cld.children.Length <= 0) // leaf node + { + ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); + } + else if (cld.children[0].ParentID == 0) // multiple return value + { + ProcessROID(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.roid); + } + else + { + for (int i = 0; i < cld.children.Length; i++) + { + ProcessROChild(datatable, f2, f3, ref cell, ref lastROID, ref prevROTitleList, ref lastDBindex, cld.children[i]); + } + } + } + + private void ProcessROID(PdfPTable datatable, iTextSharp.text.Font f2, iTextSharp.text.Font f3, ref PdfPCell cell, ref string lastROID, ref List prevROTitleList, ref int lastDBindex, string cROID) + { + int curDBindex = _ROFSTLookup.GetRODatabaseTitleIndex(cROID); + + if (lastDBindex == -1 || curDBindex != lastDBindex) + { + if (prevROTitleList != null) + { + // add blank line to separate groups on the report + cell = new PdfPCell(new Phrase(" ", f2)) + { + BorderColor = Color.WHITE + }; + datatable.AddCell(cell); + } + + AddMainRODatabaseTitle(datatable, curDBindex, f3, Color.WHITE); + lastDBindex = curDBindex; + } + + if (string.IsNullOrEmpty(lastROID) || cROID != lastROID) + prevROTitleList = AddROHeaderGroupForSummary(datatable, cROID, prevROTitleList, f2); + + lastROID = cROID; + } + + #endregion + + #region Private Static Methods + + private static PdfPTable BuildSubTable(iTextSharp.text.Document document, float[] headerwidths) + { + PdfPTable subtable = new PdfPTable(headerwidths) + { + HeaderRows = 1, + KeepTogether = true, + TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin, + LockedWidth = true + }; + subtable.DefaultCell.Padding = 4; + + return subtable; + } + + private static void ShowException(Exception ex) + { + Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); + StringBuilder msg = new StringBuilder(); + string sep = string.Empty; + string indent = string.Empty; + + while (ex != null) + { + msg.Append(string.Format("{0}{1}{2}:\r\n{1}{3}", sep, indent, ex.GetType().Name, ex.Message)); + ex = ex.InnerException; + sep = "\r\n"; + indent += " "; + } + + System.Windows.Forms.MessageBox.Show(msg.ToString(), "Error during PDF creation for search:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); + } + + public static string BuildStepTab(ItemInfo item) + { + if (item == null) + return string.Empty; + + string sret = string.Empty; + + switch (item.MyContent.Type / 10000) + { + case 0: //procedure + sret = ProcedureInfo.Get(item.ItemID).MyTab.CleanText; + break; + + case 1: // section + sret = SectionInfo.Get(item.ItemID).MyTab.CleanText; + break; + + case 2: // step + ItemInfo pitem = item; + bool hasDelim = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter != null; + List DelimList = new List(); + + if (!hasDelim) + { + SeqTabFmtList seqtabs = item.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.SeqTabFmtList; + + foreach (SeqTabFmt seqtab in seqtabs) + { + string delim = seqtab.PrintTabFormat.Replace("{seq}", string.Empty); + + if (!DelimList.Contains(delim)) + { + DelimList.Add(delim.Trim()); + } + } + } + else + { + string stpdelms = item.ActiveFormat.PlantFormat.FormatData.TransData.StepSubstepDelimeter; + + foreach (char c in stpdelms) + { + if (!DelimList.Contains(c.ToString())) + { + DelimList.Add(c.ToString()); + } + } + } + + // B2016-160 Support transitions to sections + while (!pitem.IsSection && !pitem.IsHigh) + { + StepInfo stpinfo = StepInfo.Get(pitem.ItemID); + string thisTab = stpinfo.MyTab.CleanText; + + if (IncludesParentToHLS(stpinfo)) + { + if (!thisTab.Contains("\u25CF")) //Remove Bullet + { + return thisTab; + } + else + { + thisTab = null; + } + } + + string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.ToString(); + + // remove delimiters of '.' and ')' in tab. + if (!string.IsNullOrEmpty(thisTab)) + { + // get list of delimiters to remove from the format: + foreach (string rmvDelim in DelimList) + { + thisTab = thisTab.Replace(rmvDelim, string.Empty); + } + } + + if (!string.IsNullOrEmpty(thisTab)) + { + thisTab = thisTab.Trim(); + } + + // if the tab is null or + // if the the tab is not a letter or number OR + // the tab is an AND or OR type and is the letter "o" + // then reset the tab an empty string so that the type name along with the count of that type + // (ex. "AND 2", "OR 3") + if (string.IsNullOrEmpty(thisTab) || (thisTab != string.Empty && (!(char.IsLetterOrDigit(thisTab[0])) || ((pitem.IsAnd || pitem.IsOr || pitem.IsCaution || pitem.IsNote) && thisTab.Contains("o"))))) + { + thisTab = string.Empty; + } + + if (pitem.IsRNOPart) + { + if (string.IsNullOrEmpty(thisTab)) + { + sret = "RNO." + sret; //"RNO." + sret; + } + else + { + thisTab = thisTab.Trim(" ".ToCharArray()); + + if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) + { + thisTab += "."; + } + + sret = $"RNO.{thisTab}{sret}"; //"RNO." + thisTab + sret; + } + } + else if (pitem.IsCaution || pitem.IsNote) + { + // add the Caution or Note count to the tab (ex "Caution 1", "Note 2") + if (string.IsNullOrEmpty(thisTab)) + { + sret = $"{{{typeName} {pitem.Ordinal}}}"; + } + else + { + thisTab = thisTab.Trim(" ".ToCharArray()); + sret = $"{thisTab} {pitem.Ordinal}{sret}"; + } + } + else + { + if (!string.IsNullOrEmpty(thisTab)) + { + thisTab = thisTab.Trim(" ".ToCharArray()); + + if (!thisTab.EndsWith(".") && !thisTab.EndsWith(")")) + { + thisTab += "."; + } + } + else + { + thisTab = $"{{{typeName} {pitem.Ordinal}}}."; + } + + sret = thisTab + sret; + } + + pitem = pitem.ActiveParent as ItemInfo; + + if (pitem == null) + break; + } + + // add hls tab if it's not already in the tab. + if (pitem.IsHigh) + { + StepInfo stpinfo = StepInfo.Get(pitem.ItemID); + + string hlsTab = stpinfo.MyTab.CleanTextNoSymbols; //StepInfo.Get(pitem.ItemID).MyTab.CleanTextNoSymbols; + string typeName = stpinfo.FormatStepData.StepEditData.TypeMenu.MenuItem;//stpinfo.FormatStepData.GetPDDisplayName(); //.ToString(); + // C2020-043: don't remove delimiters on tabs if this step's tab has the parent tab included. + bool hasParent = false; + + if (IncludesParentToHLS(stpinfo) && !hlsTab.Contains("\u25CF")) + { + hlsTab = hlsTab.Trim(" ".ToCharArray()).TrimEnd(".".ToCharArray()); + hasParent = true; + } + + if (string.IsNullOrEmpty(hlsTab)) + { + hlsTab = $"{{{typeName} {pitem.Ordinal}}}."; + } + else if (!hasParent && !sret.StartsWith(hlsTab.Trim(" ".ToCharArray()))) + { + foreach (string rmvDelim in DelimList) + { + hlsTab = hlsTab.Replace(rmvDelim, string.Empty); + } + + hlsTab = hlsTab.Trim(" ".ToCharArray()); + + if (!hlsTab.EndsWith(".") && !hlsTab.EndsWith(")")) + { + hlsTab += "."; + } + } + + sret = hlsTab + sret; + } + + break; + } + + return sret.Trim(" .)".ToCharArray()); + } + + private static bool IncludesParentToHLS(StepInfo stpinfo) + { + if (stpinfo.IsHigh) + return true; + + StepInfo parent = StepInfo.Get((stpinfo.ActiveParent as ItemInfo).ItemID); + + if (stpinfo.MyTab.CleanText.StartsWith(parent.MyTab.CleanText.Trim()) && stpinfo.MyTab.CleanText.Length > parent.MyTab.CleanText.Length) + { + return IncludesParentToHLS(parent); + } + + return false; + } + + #endregion + } + + + public class MyPageHelper : PdfPageEventHelper + { + #region Fields + + protected PdfTemplate total; + protected BaseFont helv; + private readonly int ptSize = 10; // text point size of page number and page total + readonly string _ByLine = "PROMS"; + + #endregion + + #region Properties + + public PdfPTable HeaderTable { get; set; } = null; + + #endregion + + #region Constructors + + public MyPageHelper(string byLine) + { + _ByLine = byLine; + } + + #endregion + + #region Public Methods + + public override void OnOpenDocument(PdfWriter writer, iTextSharp.text.Document document) + { + total = writer.DirectContent.CreateTemplate(100, 100); + total.BoundingBox = new Rectangle(-20, -20, 100, 100); + helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); + } + + public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document) + { + PdfContentByte cb = writer.DirectContent; + + cb.SaveState(); + + HeaderTable?.WriteSelectedRows(0, 2, 36, document.Top + 44, cb); + String text = $"Page {writer.PageNumber} of "; + float textBase = document.Bottom - 19;//20; + cb.BeginText(); + cb.SetFontAndSize(helv, ptSize); + + float posCenter = document.Left + ((document.Right - document.Left) / 2) - (helv.GetWidthPoint($"{text}XX", ptSize) / 2); + cb.SetTextMatrix(posCenter, textBase); + cb.ShowText(text); + cb.EndText(); + cb.AddTemplate(total, posCenter + helv.GetWidthPoint(text, ptSize), textBase); + cb.RestoreState(); + + AddVolianFooter(writer, document); + AddDateFooter(writer, document); + } + + public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) + { + total.BeginText(); + total.SetFontAndSize(helv, ptSize); + total.SetTextMatrix(0, 0); + total.ShowText((writer.PageNumber - 1).ToString()); + total.EndText(); + + base.OnCloseDocument(writer, document); + } + + #endregion + + #region Private Methods + + private void AddVolianFooter(PdfWriter writer, iTextSharp.text.Document document) + { + PdfContentByte cb = writer.DirectContent; + cb.SaveState(); + String text = _ByLine;//"PROMS Search Results"; + float textBase = document.Bottom - 19;//20; + cb.BeginText(); + cb.SetFontAndSize(helv, ptSize); + cb.SetTextMatrix(document.Left, textBase); + cb.ShowText(text); + cb.EndText(); + cb.RestoreState(); + } + + private void AddDateFooter(PdfWriter writer, iTextSharp.text.Document document) + { + PdfContentByte cb = writer.DirectContent; + cb.SaveState(); + String text = DateTime.Today.ToShortDateString(); + float textBase = document.Bottom - 19;//20; + float posRight = document.Right - helv.GetWidthPoint(text, ptSize); + cb.BeginText(); + cb.SetFontAndSize(helv, ptSize); + cb.SetTextMatrix(posRight, textBase); + cb.ShowText(text); + cb.EndText(); + cb.RestoreState(); + } + + #endregion + } } diff --git a/PROMS/Volian.Print.Library/PDFTransitionReport.cs b/PROMS/Volian.Print.Library/PDFTransitionReport.cs index fe283a83..79f0919c 100644 --- a/PROMS/Volian.Print.Library/PDFTransitionReport.cs +++ b/PROMS/Volian.Print.Library/PDFTransitionReport.cs @@ -5,7 +5,7 @@ using VEPROMS.CSLA.Library; using iTextSharp.text.pdf; using iTextSharp.text; using System.IO; -using System.Text.RegularExpressions; +using System.Linq; namespace Volian.Print.Library { @@ -13,27 +13,14 @@ namespace Volian.Print.Library public class PDFTransitionReport { public event TransitionReportEvent TransitionProcessed; - private void OnTransitionProcessed(object sender, EventArgs args) - { - if (TransitionProcessed != null) TransitionProcessed(sender, args); - } - public event TransitionReportEvent ProcedureProcessed; - private void OnProcedureProcessed(object sender, EventArgs args) - { - if (ProcedureProcessed != null) ProcedureProcessed(sender, args); - } - public event TransitionReportEvent DocVersionProcessed; - private void OnDocVersionProcessed(object sender, EventArgs args) - { - if (DocVersionProcessed != null) DocVersionProcessed(sender, args); - } - private string _FileName; - public string FileName - { - get { return _FileName; } - set { _FileName = value; } - } - private PdfPCell _CurrentPageNumberCell = null; + private void OnTransitionProcessed(object sender, EventArgs args) => TransitionProcessed?.Invoke(sender, args); + public event TransitionReportEvent ProcedureProcessed; + private void OnProcedureProcessed(object sender, EventArgs args) => ProcedureProcessed?.Invoke(sender, args); + public event TransitionReportEvent DocVersionProcessed; + private void OnDocVersionProcessed(object sender, EventArgs args) => DocVersionProcessed?.Invoke(sender, args); + + public string FileName { get; set; } + private PdfPCell _CurrentPageNumberCell = null; private int _CurrentPageNumber = 1; public int CurrentPageNumber { @@ -51,41 +38,27 @@ namespace Volian.Print.Library } } } - private FolderInfo folderInfo; + private readonly FolderInfo folderInfo; private ProcedureInfo procedureInfo; private TransitionInfoList transitionInfoList; - private int _TransitionInfoCount; - public int TransitionInfoCount - { - get { return _TransitionInfoCount; } - set { _TransitionInfoCount = value; } - } - private List _MyDocVersionList; - public List MyDocVersionList - { - get { return _MyDocVersionList; } - set { _MyDocVersionList = value; } - } - private int _ProcedureCount; - public int ProcedureCount - { - get { return _ProcedureCount; } - set { _ProcedureCount = value; } - } - private string _PaperSize = "Letter"; + + public int TransitionInfoCount { get; set; } + public List MyDocVersionList { get; set; } + public int ProcedureCount { get; set; } + private readonly string _PaperSize = "Letter"; public PDFTransitionReport(FolderInfo fi, string fileName) { - _FileName = fileName; + FileName = fileName; folderInfo = fi; if (fi.ActiveFormat != null) _PaperSize = fi.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize; // C2020-002 paper size is now set in the format files } public PDFTransitionReport(ProcedureInfo pi, string fileName) { - _FileName = fileName; + FileName = fileName; procedureInfo = pi; transitionInfoList = TransitionInfoList.GetTransitionReportData(procedureInfo.MyDocVersion.VersionID, procedureInfo.ItemID); - _TransitionInfoCount = transitionInfoList.Count; + TransitionInfoCount = transitionInfoList.Count; _PaperSize = pi.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize; // C2020-002 paper size is now set in the format files } public void BuildTransitionReport() @@ -100,13 +73,13 @@ namespace Volian.Print.Library if (MyDocVersionList.Count == 1) { DocVersionInfo dvi = MyDocVersionList[0]; - foreach (ProcedureInfo pi in dvi.Procedures) + foreach (ProcedureInfo pi in dvi.Procedures.OfType()) { procedureInfo = pi; transitionInfoList = TransitionInfoList.GetTransitionReportData(dvi.VersionID, procedureInfo.ItemID); if (transitionInfoList.Count > 0) { - _TransitionInfoCount = transitionInfoList.Count; + TransitionInfoCount = transitionInfoList.Count; OnProcedureProcessed(this, new EventArgs()); BuildProcedureReport(document); } @@ -122,11 +95,11 @@ namespace Volian.Print.Library { ProcedureCount = dvi.Procedures.Count; OnDocVersionProcessed(this, new EventArgs()); - foreach (ProcedureInfo pi in dvi.Procedures) + foreach (ProcedureInfo pi in dvi.Procedures.OfType()) { procedureInfo = pi; transitionInfoList = TransitionInfoList.GetTransitionReportData(dvi.VersionID, procedureInfo.ItemID); - _TransitionInfoCount = transitionInfoList.Count; + TransitionInfoCount = transitionInfoList.Count; OnProcedureProcessed(this, new EventArgs()); BuildProcedureReport(document); } @@ -140,7 +113,6 @@ namespace Volian.Print.Library } catch (Exception ex) { - StringBuilder msg = new StringBuilder(); document.Add(new Paragraph("Error:")); while (ex != null) { @@ -160,11 +132,13 @@ namespace Volian.Print.Library } PdfOutline outline = null; ProcedureInfo lastProcedureInfo = null; - private PdfPTable BuildProcedurePDFTable(Dictionary levels, Dictionary fonts, int cols, int paddingBottom, int level, iTextSharp.text.Document doc) + private PdfPTable BuildProcedurePDFTable(Dictionary levels, Dictionary fonts, int cols, int paddingBottom, int level) { - PdfPTable t = new PdfPTable(cols); - t.HeaderRows = 4; - t.DefaultCell.Padding = 4; + PdfPTable t = new PdfPTable(cols) + { + HeaderRows = 4 + }; + t.DefaultCell.Padding = 4; t.WidthPercentage = 100; float[] widths; if(level == 1 || level == 2 || level == 4) @@ -172,52 +146,66 @@ namespace Volian.Print.Library else widths = new float[] { 33f, 47f, 20f }; t.SetWidths(widths); - //report title - Phrase h = new Phrase(); - h.Font = fonts[1]; - if (folderInfo != null) + //report title + Phrase h = new Phrase + { + Font = fonts[1] + }; + if (folderInfo != null) h.Add(string.Format("Procedure Set {0} Transition Report", folderInfo.Name)); else h.Add("Transition Report"); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols-1; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.DarkGoldenrod); - t.AddCell(c); - //date generated - h = new Phrase(); - h.Font = fonts[4]; - h.Add(DateTime.Now.ToString("dddd MMMM d, yyyy @ h:mm tt")); - c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_RIGHT; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.DarkGoldenrod); - t.AddCell(c); - //procedure title - h = new Phrase(); - h.Font = fonts[2]; - h.Add(string.Format("{0} - {1}", procedureInfo.DisplayNumber, procedureInfo.DisplayText)); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols - 1, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.DarkGoldenrod) + }; + t.AddCell(c); + //date generated + h = new Phrase + { + Font = fonts[4] + }; + h.Add(DateTime.Now.ToString("dddd MMMM d, yyyy @ h:mm tt")); + c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_RIGHT, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.DarkGoldenrod) + }; + t.AddCell(c); + //procedure title + h = new Phrase + { + Font = fonts[2] + }; + h.Add(string.Format("{0} - {1}", procedureInfo.DisplayNumber, procedureInfo.DisplayText)); PdfDestination dest = new PdfDestination(PdfDestination.FITH, cb.PdfDocument.PageSize.Height); if (lastProcedureInfo != procedureInfo) { outline = new PdfOutline(cb.RootOutline, dest, procedureInfo.DisplayNumber, false); lastProcedureInfo = procedureInfo; } - c = new PdfPCell(h); - c.Colspan = cols-1; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.Goldenrod); - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = cols - 1, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.Goldenrod) + }; + t.AddCell(c); //page number _CurrentPageNumberCell = BuildCell(1, string.Format("Page {0}",CurrentPageNumber), fonts[4], new Color(System.Drawing.Color.Goldenrod)); _CurrentPageNumberCell.PaddingBottom = paddingBottom; t.AddCell(_CurrentPageNumberCell); - //transition category - h = new Phrase(); - h.Font = fonts[3]; - if (transitionInfoList.Count == 0) + //transition category + h = new Phrase + { + Font = fonts[3] + }; + if (transitionInfoList.Count == 0) h.Add("N/A"); else { @@ -225,75 +213,97 @@ namespace Volian.Print.Library dest = new PdfDestination(PdfDestination.FITH, cb.PdfDocument.PageSize.Height); new PdfOutline(outline, dest, levels[level]); } - c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.Khaki); - t.AddCell(c); - //add column headers - h = new Phrase(); - h.Font = fonts[4]; - h.Add("From Procedure Location"); - c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.PaleGoldenrod); - t.AddCell(c); - h = new Phrase(); - h.Font = fonts[4]; - h.Add("From Procedure Text"); - c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.PaleGoldenrod); - t.AddCell(c); - h = new Phrase(); - h.Font = fonts[4]; - h.Add("To Procedure Location"); - c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_CENTER; - c.PaddingBottom = paddingBottom; - c.BackgroundColor = new Color(System.Drawing.Color.PaleGoldenrod); - t.AddCell(c); + c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.Khaki) + }; + t.AddCell(c); + //add column headers + h = new Phrase + { + Font = fonts[4] + }; + h.Add("From Procedure Location"); + c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.PaleGoldenrod) + }; + t.AddCell(c); + h = new Phrase + { + Font = fonts[4] + }; + h.Add("From Procedure Text"); + c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.PaleGoldenrod) + }; + t.AddCell(c); + h = new Phrase + { + Font = fonts[4] + }; + h.Add("To Procedure Location"); + c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_CENTER, + PaddingBottom = paddingBottom, + BackgroundColor = new Color(System.Drawing.Color.PaleGoldenrod) + }; + t.AddCell(c); return t; } PdfContentByte cb; private void BuildProcedureReport(iTextSharp.text.Document doc) { Dictionary tranTypes = FormatInfo.GetTransitionTypesByFormatID(procedureInfo.ActiveFormat.FormatID); - Dictionary levels = new Dictionary(); - levels.Add(1, "Internal Transitions"); - levels.Add(2, "External From Transitions"); - levels.Add(3, "External To Transitions"); - levels.Add(4, "Outside From Transitions"); - levels.Add(5, "Outside To Transitions"); - Dictionary fonts = new Dictionary(); - // C2017-036 get best available proportional font for symbols that looks close to Arial - // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 - fonts.Add(1, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK)); - fonts.Add(2, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK)); - fonts.Add(3, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 8, 0, Color.BLACK)); - fonts.Add(4, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 8, 0, Color.BLACK)); + Dictionary levels = new Dictionary + { + { 1, "Internal Transitions" }, + { 2, "External From Transitions" }, + { 3, "External To Transitions" }, + { 4, "Outside From Transitions" }, + { 5, "Outside To Transitions" } + }; + Dictionary fonts = new Dictionary + { + // C2017-036 get best available proportional font for symbols that looks close to Arial + // Note that Microsoft no longer supplies Arial Unicode MS as of Word16 + { 1, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 12, 0, Color.BLACK) }, + { 2, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 10, 0, Color.BLACK) }, + { 3, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 8, 0, Color.BLACK) }, + { 4, pdf.GetFont(Volian.Base.Library.vlnFont.ReportsFont, 8, 0, Color.BLACK) } + }; int lastLevel = transitionInfoList.Count > 0 ? transitionInfoList[0].Level : 0; //set level to first transition level #region buildtable int cols = 3; int paddingBottom = 6; if (folderInfo != null) doc.NewPage(); - PdfPTable t = BuildProcedurePDFTable(levels, fonts, cols, paddingBottom, lastLevel, doc); + PdfPTable t = BuildProcedurePDFTable(levels, fonts, cols, paddingBottom, lastLevel); #endregion //gather data if (transitionInfoList.Count == 0) { - Phrase h = new Phrase(); - h.Font = fonts[4]; - h.Add("This procedure contains no transitions"); - PdfPCell c = new PdfPCell(h); - c.Colspan = cols; - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - t.AddCell(c); + Phrase h = new Phrase + { + Font = fonts[4] + }; + h.Add("This procedure contains no transitions"); + PdfPCell c = new PdfPCell(h) + { + Colspan = cols, + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + t.AddCell(c); } else { @@ -308,37 +318,49 @@ namespace Volian.Print.Library doc.Add(t); doc.NewPage(); lastLevel = ti.Level; - t = BuildProcedurePDFTable(levels, fonts, cols, paddingBottom, lastLevel, doc); + t = BuildProcedurePDFTable(levels, fonts, cols, paddingBottom, lastLevel); } } - //add from path - Phrase h = new Phrase(); - h.Font = fonts[4]; - h.Add(StripProcInfo(ti.PathFrom, procedureInfo)); - PdfPCell c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - if (lastLevel > 1 && (!tranTypes[ti.TranType].Contains("{Proc") && !tranTypes[ti.TranType].Contains("other procedure"))) c.BackgroundColor = new Color(System.Drawing.Color.LightCoral); + //add from path + Phrase h = new Phrase + { + Font = fonts[4] + }; + h.Add(StripProcInfo(ti.PathFrom, procedureInfo)); + PdfPCell c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + if (lastLevel > 1 && (!tranTypes[ti.TranType].Contains("{Proc") && !tranTypes[ti.TranType].Contains("other procedure"))) c.BackgroundColor = new Color(System.Drawing.Color.LightCoral); t.AddCell(c); - //add from text - h = new Phrase(); - h.Font = fonts[4]; - ItemInfo myItemInfo = ti.MyContent.ContentItems[0]; + //add from text + h = new Phrase + { + Font = fonts[4] + }; + ItemInfo myItemInfo = ti.MyContent.ContentItems[0]; h.Add(GetTextPath(myItemInfo, 0)); - c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - if (lastLevel > 1 && (!tranTypes[ti.TranType].Contains("{Proc") && !tranTypes[ti.TranType].Contains("other procedure"))) c.BackgroundColor = new Color(System.Drawing.Color.LightCoral); + c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + if (lastLevel > 1 && (!tranTypes[ti.TranType].Contains("{Proc") && !tranTypes[ti.TranType].Contains("other procedure"))) c.BackgroundColor = new Color(System.Drawing.Color.LightCoral); t.AddCell(c); - //add to text - h = new Phrase(); - h.Font = fonts[4]; - myItemInfo = ti.MyItemToID; + //add to text + h = new Phrase + { + Font = fonts[4] + }; + myItemInfo = ti.MyItemToID; h.Add(GetTextPath(myItemInfo, ti.Level)); - c = new PdfPCell(h); - c.HorizontalAlignment = Element.ALIGN_LEFT; - c.PaddingBottom = paddingBottom; - if (lastLevel > 1 && (!tranTypes[ti.TranType].Contains("{Proc") && !tranTypes[ti.TranType].Contains("other procedure"))) c.BackgroundColor = new Color(System.Drawing.Color.LightCoral); + c = new PdfPCell(h) + { + HorizontalAlignment = Element.ALIGN_LEFT, + PaddingBottom = paddingBottom + }; + if (lastLevel > 1 && (!tranTypes[ti.TranType].Contains("{Proc") && !tranTypes[ti.TranType].Contains("other procedure"))) c.BackgroundColor = new Color(System.Drawing.Color.LightCoral); t.AddCell(c); } } @@ -357,16 +379,16 @@ namespace Volian.Print.Library { StringBuilder sb = new StringBuilder(); if (myItemInfo.IsProcedure) - return myItemInfo.MyProcedure.DisplayNumber + " " + myItemInfo.MyProcedure.DisplayText; + return $"{myItemInfo.MyProcedure.DisplayNumber} {myItemInfo.MyProcedure.DisplayText}"; if (myItemInfo.IsSection) { if (level > 1) - return myItemInfo.MyProcedure.DisplayNumber + " " + myItemInfo.MyProcedure.DisplayText + "\r\n " + myItemInfo.DisplayText; + return $"{myItemInfo.MyProcedure.DisplayNumber} {myItemInfo.MyProcedure.DisplayText}\r\n {myItemInfo.DisplayText}"; else return myItemInfo.DisplayText; } if (myItemInfo.IsHigh) - return myItemInfo.ActiveSection.DisplayText + "\r\n " + myItemInfo.DisplayText; + return $"{myItemInfo.ActiveSection.DisplayText}\r\n {myItemInfo.DisplayText}"; else { string tmp = ""; @@ -393,10 +415,6 @@ namespace Volian.Print.Library } return sb.ToString(); } - public void BuildTransitionReport(FolderInfo fi) - { - System.Windows.Forms.MessageBox.Show("folder"); - } private bool CreateResultsPDF(iTextSharp.text.Document document) { bool result = false; @@ -404,26 +422,20 @@ namespace Volian.Print.Library int i = 0; // just for safety, the while loop expects to find a file extension // so make sure it has one before going into the loop - if (!_FileName.ToUpper().EndsWith(".PDF")) - _FileName += ".pdf"; + if (!FileName.ToUpper().EndsWith(".PDF")) + FileName += ".pdf"; // Try to open a file for creating the PDF. while (result == false) { - string fileName = _FileName; - // Bug fix: B2013-086 - // the folder path part of _FileName contained a folder name with a period - // resulting is an invalid file location/file name. - // Changed the IndexOf call to the LastIndexOf - //int loc = fileName.IndexOf("."); + string fileName = FileName; int loc = fileName.LastIndexOf("."); if (loc > -1) { string fname = fileName.Substring(0, loc); - fileName = fname + suffix + ".pdf"; + fileName = $"{fname}{suffix}.pdf"; } else - fileName = fileName + suffix + ".pdf"; - // string fileName = _FileName.ToLower().Replace(".pdf", suffix + ".pdf"); + fileName = $"{fileName}{suffix}.pdf"; try { PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); @@ -431,7 +443,7 @@ namespace Volian.Print.Library document.SetMargins(36, 36, 36, 36); document.Open(); cb = writer.DirectContent; - _FileName = fileName; + FileName = fileName; result = true; } catch (System.IO.IOException exIO) @@ -468,28 +480,25 @@ namespace Volian.Print.Library } System.Windows.Forms.MessageBox.Show(msg.ToString(), "Error during PDF creation for search:", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } - private PdfPCell BlankCell(int colSpan) - { - PdfPCell c = new PdfPCell(); - c.Colspan = colSpan; - c.Border = 0; - return c; - } private PdfPCell BuildCell(int colspan, string txt, Font f, iTextSharp.text.Color clr) { - Phrase h = new Phrase(); - h.Font = f; - h.Add(txt); - PdfPCell c = new PdfPCell(h); - c.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; - c.Colspan = colspan; - c.BackgroundColor = clr; - return c; + Phrase h = new Phrase + { + Font = f + }; + h.Add(txt); + PdfPCell c = new PdfPCell(h) + { + HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT, + Colspan = colspan, + BackgroundColor = clr + }; + return c; } } public class MyPageEvent : PdfPageEventHelper { - private PDFTransitionReport _rpt = null; + private readonly PDFTransitionReport _rpt = null; public MyPageEvent(PDFTransitionReport rpt) { _rpt = rpt; diff --git a/PROMS/Volian.Print.Library/PageCount.cs b/PROMS/Volian.Print.Library/PageCount.cs index 884d6f33..40ad3ff6 100644 --- a/PROMS/Volian.Print.Library/PageCount.cs +++ b/PROMS/Volian.Print.Library/PageCount.cs @@ -1,40 +1,23 @@ -using System; using System.Collections.Generic; -using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; -using Volian.Svg.Library; namespace Volian.Print.Library { public class PageCount { - private bool _CanIncrement = true; - public bool CanIncrement - { - get { return _CanIncrement; } - set { _CanIncrement = value; } - } - private int Increment() + public bool CanIncrement { get; set; } = true; + private int Increment() { if (CanIncrement) Total++; CanIncrement = false; return Total; } - private int _Total; - public int Total - { - get { return _Total; } - set { _Total = value; } - } - private string _FinalPageMessage; - public string FinalPageMessage - { - get { return _FinalPageMessage; } - set { _FinalPageMessage = value; } - } - private PageCountTemplates _MyTemplates; // (for each page that has this key) + public int Total { get; set; } + + public string FinalPageMessage { get; set; } + private PageCountTemplates _MyTemplates; // (for each page that has this key) internal PageCountTemplates MyTemplates { get @@ -53,10 +36,10 @@ namespace Volian.Print.Library foreach (PageCountTemplate pct in MyTemplates) { cnt++; - string fstr = pct.Text.Replace("{OF}", _Total.ToString()); + string fstr = pct.Text.Replace("{OF}", Total.ToString()); if (pct.Text.Contains("{TOCPAGE}")) { - fstr = pct.Text.Replace("{TOCPAGE}", _Total.ToString()); + fstr = pct.Text.Replace("{TOCPAGE}", Total.ToString()); } if (fstr.Contains("{FINALPAGE}")) { @@ -140,45 +123,21 @@ namespace Volian.Print.Library public class PageCountTemplate { - private string _Text; - public string Text // "Page 1 of {OF}" - { - get { return _Text; } - set { _Text = value; } - } - private System.Drawing.Font _MyFont; - public System.Drawing.Font MyFont - { - get { return _MyFont; } - set { _MyFont = value; } - } - private int _Alignment; // iTextSharp Element. - public int Alignment - { - get { return _Alignment; } - set { _Alignment = value; } - } - private System.Drawing.Color _MyColor; - public System.Drawing.Color MyColor - { - get { return _MyColor; } - set { _MyColor = value; } - } - private PdfTemplate _MyTemplate; - public PdfTemplate MyTemplate - { - get { return _MyTemplate; } - set { _MyTemplate = value; } - } - public PageCountTemplate(PdfWriter pdfWriter, string text, System.Drawing.Font myFont, int alignment, System.Drawing.Color color) + public string Text // "Page 1 of {OF}" + { get; set; } + public System.Drawing.Font MyFont { get; set; } + public int Alignment { get; set; } + public System.Drawing.Color MyColor { get; set; } + public PdfTemplate MyTemplate { get; set; } + public PageCountTemplate(PdfWriter pdfWriter, string text, System.Drawing.Font myFont, int alignment, System.Drawing.Color color) { // Create Template can be called with a small, i.e. 1, width/height because when // it is actually drawn, the bounding box overrides the CreateTemplate values. - _MyTemplate = pdfWriter.DirectContent.CreateTemplate(1, 1); - _Text = text; - _MyFont = myFont; - _MyColor = color; - _Alignment = alignment; + MyTemplate = pdfWriter.DirectContent.CreateTemplate(1, 1); + Text = text; + MyFont = myFont; + MyColor = color; + Alignment = alignment; } } public class PageCountTemplates : List diff --git a/PROMS/Volian.Print.Library/Pagination.cs b/PROMS/Volian.Print.Library/Pagination.cs index 3460f87c..cd7995b9 100644 --- a/PROMS/Volian.Print.Library/Pagination.cs +++ b/PROMS/Volian.Print.Library/Pagination.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using VEPROMS.CSLA.Library; using Volian.Base.Library; using iTextSharp.text.pdf; @@ -10,53 +9,29 @@ namespace Volian.Print.Library { public partial class vlnParagraph { - private string _PageBreakReason = null; - public string PageBreakReason - { - get { return _PageBreakReason; } - set { _PageBreakReason = value; } - } - private bool _CompressPartOfStep = false; - public bool CompressPartOfStep - { - get { return _CompressPartOfStep; } - set { _CompressPartOfStep = value; } - } - private bool _CompressFirstPartOfStep = false; - public bool CompressFirstPartOfStep - { - get { return _CompressFirstPartOfStep; } - set { _CompressFirstPartOfStep = value; } - } - private bool _BreakHighLevelStepWithSection = false; - public bool BreakHighLevelStepWithSection - { - get { return _BreakHighLevelStepWithSection; } - set { _BreakHighLevelStepWithSection = value; } - } - /// - /// This variable is used to match 16 bit pagination - /// - private bool _Match16BitPagination = false; - private bool _CompressFoldout = false; - public bool CompressFoldout - { - get { return _CompressFoldout; } - set { _CompressFoldout = value; } - } - /// - /// Dtermines if the current step is preceded by a Page Break - /// - /// - /// - /// - /// - /// 0 - No page break - /// 1 - Break on High Level Step - /// 2 - Break within a Step - /// 3 - Break on High Level Step (SevenLinesPerInch) - /// - private int Paginate(float yLocation, float yTopMargin, float yBottomMargin) + public string PageBreakReason { get; set; } = null; + public bool CompressPartOfStep { get; set; } = false; + public bool CompressFirstPartOfStep { get; set; } = false; + public bool BreakHighLevelStepWithSection { get; set; } = false; + /// + /// This variable is used to match 16 bit pagination + /// + private readonly bool _Match16BitPagination = false; + + public bool CompressFoldout { get; set; } = false; + /// + /// Dtermines if the current step is preceded by a Page Break + /// + /// + /// + /// + /// + /// 0 - No page break + /// 1 - Break on High Level Step + /// 2 - Break within a Step + /// 3 - Break on High Level Step (SevenLinesPerInch) + /// + private int Paginate(float yLocation, float yTopMargin, float yBottomMargin) { // Check if paginate on a separate section, if within a section. Top level section pagination happens in PromsPrinter float yPageSize = yTopMargin - yBottomMargin; @@ -85,15 +60,15 @@ namespace Volian.Print.Library if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.SupInfoPdfPrint) { int retval = 0; - SectionInfo supInfoSect = MyItemInfo.ActiveSection as SectionInfo; // C2018-003 fixed use of getting the active section - if (supInfoSect != null && supInfoSect.StepSectPageBreaksForSupInfo != null && supInfoSect.StepSectPageBreaksForSupInfo.Contains(MyItemInfo.ItemID)) - { - MyPromsPrinter.SupInfoPdfPageCount++; - retval = 1; - } - // Printing the supplemental information pages to a pdf: add an item to the dictionary that says what page in the supinfo pdf - // this item can be found on. - if (MyItemInfo.IsSupInfoPart) + // C2018-003 fixed use of getting the active section + if (MyItemInfo.ActiveSection is SectionInfo supInfoSect && supInfoSect.StepSectPageBreaksForSupInfo != null && supInfoSect.StepSectPageBreaksForSupInfo.Contains(MyItemInfo.ItemID)) + { + MyPromsPrinter.SupInfoPdfPageCount++; + retval = 1; + } + // Printing the supplemental information pages to a pdf: add an item to the dictionary that says what page in the supinfo pdf + // this item can be found on. + if (MyItemInfo.IsSupInfoPart) { MyPromsPrinter.SupInfoPdfPage.Add(MyItemInfo.ItemID, MyPromsPrinter.SupInfoPdfPageCount); } @@ -141,37 +116,36 @@ namespace Volian.Print.Library if (MyItemInfo.MyParent.IsHigh && MyItemInfo.IsNote && (MyItemInfo.MyParent.Cautions == null || MyItemInfo.MyParent.Cautions.Count == 0) && MyItemInfo.MyPrevious == null) return 1; // if this is a substep that has a preferredpage break, and it has caution/note that is where the page break had to go if (MyItemInfo.IsSubStep && ChildrenAbove != null && ChildrenAbove.Count > 0) return 0; - // B2017-228: The following flags a break within the step. Before returning a '2' (flags break within step), clear it out of the - // ParaBreaks. Without the 'RemoveAt', a page break will occur after this step also. - string reason = "Unknown"; - if (MyPageHelper.ParaBreaks != null && MyPageHelper.ParaBreaks.Count > 0 && this == MyPageHelper.ParaBreaks[0]) + if (MyPageHelper.ParaBreaks != null && MyPageHelper.ParaBreaks.Count > 0 && this == MyPageHelper.ParaBreaks[0]) { MyPageHelper.ParaBreaks.RemoveAt(0); - reason = AddReason("Partial Step - Case 1"); - ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak); + // B2017-228: The following flags a break within the step. Before returning a '2' (flags break within step), clear it out of the + // ParaBreaks. Without the 'RemoveAt', a page break will occur after this step also. + string reason = AddReason("Partial Step - Case 1"); + ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak); } return 2; } } } - // if the EndForSingle format flag is set to false, then we do not print an End message if the section - // is a single column section. - //bool _skipEndMessage = MyPageHelper.MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; - SectionInfo si = MyItemInfo.ActiveSection as SectionInfo; // C2018-003 fixed use of getting the active section - bool _skipEndMessage = si != null && si.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; + // if the EndForSingle format flag is set to false, then we do not print an End message if the section + // is a single column section. + //bool _skipEndMessage = MyPageHelper.MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; + // C2018-003 fixed use of getting the active section + bool _skipEndMessage = MyItemInfo.ActiveSection is SectionInfo si && si.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; - // TODO: This does not account for a long step as the last step that would exceed more than one page and - // that has an end message that needs to be accounted for in determining pagination. To do that the last - // child should be the only paragraph that accounts for the End message. - // - // If last step & there should be an end message, pagination tests need to account for the 3 lines the end - // message uses. The 3 is for a line above, the end message line & the line below (in case there is a border/box line). + // TODO: This does not account for a long step as the last step that would exceed more than one page and + // that has an end message that needs to be accounted for in determining pagination. To do that the last + // child should be the only paragraph that accounts for the End message. + // + // If last step & there should be an end message, pagination tests need to account for the 3 lines the end + // message uses. The 3 is for a line above, the end message line & the line below (in case there is a border/box line). - // The 3 was changed to 2 for the end line & the line below. The blank line below the step gives the blank - // line above the end message, thus 2 not 3. This change was made on July 20, 2011 by RHM & KBR. The - // procedure in questions was VEWCNEMG\EMGAPP.PRC, ES-01, Step 8. - //float yEndMsg = !_skipEndMessage && !MyItemInfo.IsSection && MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.NextItem == null && (MyItemInfo.MyDocStyle.End.Message ?? "") != "" ? 2 * SixLinesPerInch : 0; - float yEndMsg = (!_skipEndMessage && !MyItemInfo.IsSection && MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.NextItem == null)? GetEndMessageHeight(MyItemInfo.MyDocStyle) : 0; // B2018-068 account for mult-line End Messages + // The 3 was changed to 2 for the end line & the line below. The blank line below the step gives the blank + // line above the end message, thus 2 not 3. This change was made on July 20, 2011 by RHM & KBR. The + // procedure in questions was VEWCNEMG\EMGAPP.PRC, ES-01, Step 8. + //float yEndMsg = !_skipEndMessage && !MyItemInfo.IsSection && MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.NextItem == null && (MyItemInfo.MyDocStyle.End.Message ?? "") != "" ? 2 * SixLinesPerInch : 0; + float yEndMsg = (!_skipEndMessage && !MyItemInfo.IsSection && MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.NextItem == null)? GetEndMessageHeight() : 0; // B2018-068 account for mult-line End Messages // also consider if there is a phone list at the bottom of the page, add the amount of space the phone // list requires onto yEndMsg to make it easier to figure out pagination (include an extra line for the @@ -196,9 +170,9 @@ namespace Volian.Print.Library // location of a pagebreak. ParaBreaks contains the paragraphs that break within a step. if (MyPageHelper.ParaBreaks.Count > 0) { - string reason = "Unknown"; - // if on current step and it is also the substep that will cause a pagebreak, i.e. the top substep in pagebreaks[[0]: - if (this == MyPageHelper.ParaBreaks[0]) + string reason; + // if on current step and it is also the substep that will cause a pagebreak, i.e. the top substep in pagebreaks[[0]: + if (this == MyPageHelper.ParaBreaks[0]) { MyPageHelper.ParaBreaks.RemoveAt(0); reason = AddReason("Partial Step - Case 1"); @@ -230,14 +204,7 @@ namespace Volian.Print.Library // B2018-065 Calvert's continue message was not including the substep number in AOP-1A Attachment 1, added AERandRNO check else if (!MyPageHelper.ParaBreaks[0].PageBreakOnStep && this.YTopMost >= MyPageHelper.ParaBreaks[0].YTopMost && AERandRNO(this.MyItemInfo, MyPageHelper.ParaBreaks[0].MyItemInfo)) { - //vlnParagraph removed = MyPageHelper.ParaBreaks[0];// 2018-081 Remember where the page break was going to be MyPageHelper.ParaBreaks.RemoveAt(0); - //if (MyParent == removed && MyItemInfo.IsRNOPart && MyParent.MyItemInfo.IsHigh)// B2018-081 If The High Level Step was going to break from the High Level RNO - //{ - // reason = AddReason("Partial Step - Case 4B"); - // ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak); - // return 0; - //} reason = AddReason("Partial Step - Case 4"); ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak); return 2; // break on this item within a step @@ -276,9 +243,8 @@ namespace Volian.Print.Library // flag SectionPageBreak is set to true to flag that a pagebreak should not be done // on that first step. StepConfig sc = firstChild.MyItemInfo.MyConfig as StepConfig; - ManualPageBreak = MyPageHelper.OriginalPageBreak ? (sc == null ? false : sc.Step_ManualPagebreak) : - sc == null ? false : - (MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks == null)? sc.Step_NewManualPagebreak : false; + ManualPageBreak = MyPageHelper.OriginalPageBreak ? (sc != null && sc.Step_ManualPagebreak) : + sc != null && ((MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks == null) && sc.Step_NewManualPagebreak); // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. if (sc != null && sc.Step_NewManualPagebreak && MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks != null && !MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks.Contains(firstChild.MyItemInfo.ItemID)) MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks.Add(firstChild.MyItemInfo.ItemID); @@ -290,10 +256,7 @@ namespace Volian.Print.Library } // can the title and the first step fit? // add the first child's size + (the section title's size) - //if (ySizeIncludingFirst > (yLocation - yBottomMargin - SixLinesPerInch)) return 1; - //if (ySizeIncludingFirst > (yLocation - yBottomMargin) && ySizeIncludingFirst < yPageSize) vlnParagraph firstStepChild = firstChild; - //while (firstStepChild.MyItemInfo.IsSection && firstStepChild.ChildrenBelow.Count > 0) firstStepChild = firstStepChild.ChildrenBelow[0]; if (firstStepChild.MyItemInfo.IsNumbered) while (firstStepChild.ChildrenBelow.Count > 0 && (firstStepChild.MyItemInfo.IsSection || firstStepChild.MyItemInfo.IsHigh)) { @@ -308,13 +271,12 @@ namespace Volian.Print.Library firstStepChild = firstStepChild.MyParent.ChildrenBelow[firstStepChild.MyParent.ChildrenBelow.Count - 1]; float ySizeIncludingFirstStep = firstStepChild.YSize + (firstStepChild.YTopMost - YTopMost); float ySizeBtmCtnMess = GetBottomContinueMessageSize(MyItemInfo.MyDocStyle); - float ySizeBtmEndMess = GetBottomEndMessageSize(MyItemInfo.MyDocStyle); + float ySizeBtmEndMess = GetBottomEndMessageSize(); bool firstSubstepExceedsSpaceAvailable = ySizeIncludingFirstStep > (yWithinMargins - ySizeBtmCtnMess -ySizeBtmEndMess); if (KeepStepsOnPage && firstSubstepExceedsSpaceAvailable && !isFirstChild) KeepStepsOnPage = false; if (ySizeIncludingFirst == YSize) KeepStepsOnPage = false; - //float ySectionEndMsg = !_skipEndMessage && MyItemInfo.IsSection && MyItemInfo.Steps != null && MyItemInfo.Steps.Count == 1 && (MyItemInfo.MyDocStyle.End.Message ?? "") != "" ? 2 * SixLinesPerInch : 0; - float ySectionEndMsg = (!_skipEndMessage && MyItemInfo.IsSection && MyItemInfo.Steps != null && MyItemInfo.Steps.Count == 1) ? GetEndMessageHeight(MyItemInfo.MyDocStyle) : 0; // B2018-068 account for mult-line End Messages + float ySectionEndMsg = (!_skipEndMessage && MyItemInfo.IsSection && MyItemInfo.Steps != null && MyItemInfo.Steps.Count == 1) ? GetEndMessageHeight() : 0; // B2018-068 account for mult-line End Messages if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) { float vpHeight = SixLinesPerInch; @@ -401,11 +363,10 @@ namespace Volian.Print.Library return 1; } - //MyPageHelper.HLSText = MyItemInfo.DisplayText; // save the High Level Step Text //Console.WriteLine("{0} Paginate", MyPageHelper.HLSText); StepConfig sc1 = MyItemInfo.MyConfig as StepConfig; - ManualPageBreak = MyPageHelper.OriginalPageBreak ? (sc1 == null ? false : sc1.Step_ManualPagebreak) : - sc1 == null ? false : (MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks == null) ? sc1.Step_NewManualPagebreak : false; + ManualPageBreak = MyPageHelper.OriginalPageBreak ? (sc1 != null && sc1.Step_ManualPagebreak) : + sc1 != null && ((MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks == null) && sc1.Step_NewManualPagebreak); // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. if (sc1 != null && sc1.Step_NewManualPagebreak && MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks != null && !MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks.Contains(MyItemInfo.ItemID)) MyPageHelper.MyPromsPrinter.RemoveManualPageBreaks.Add(MyItemInfo.ItemID); @@ -423,7 +384,6 @@ namespace Volian.Print.Library string firstStep = "No"; if (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null) firstStep = "Yes"; - //if (!ManualPageBreak && mySize + yEndMsg <= yWithinMargins) // Don't Paginate if there is enough room, will fit on page // Pagination Fix - Break1LineShort1 float yExtra = (yWithinMargins == yPageSize ? 0 : SixLinesPerInch - MyItemInfo.MyDocStyle.Layout.FooterLength) ?? 0; // Adjust yExtra and mySize for Component List items. @@ -452,12 +412,11 @@ namespace Volian.Print.Library // B2017-254 Fixed Pagination Logic when checking to see if the current item is the last high level step if (MyItemInfo.IsHigh && mySize >= (2 * SixLinesPerInch) && MyItemInfo.MyDocStyle.Layout.FooterLength > 0 && (MyItemInfo.MyDocStyle.End.Message == null || MyItemInfo.MyDocStyle.End.Message == "") && MyItemInfo.NextItem == null && (MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) && (MyItemInfo.RNOs == null || MyItemInfo.RNOs.Count == 0)) mySize -= SixLinesPerInch; - //// Account for extra lines in the end message (flag < 0) - float adjMsgY = 0; - if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null && MyItemInfo.MyDocStyle.End.Flag < 0) // Adjust this many lines down the page. + if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null && MyItemInfo.MyDocStyle.End.Flag < 0) // Adjust this many lines down the page. { - adjMsgY = (float)-MyItemInfo.MyDocStyle.End.Flag * SixLinesPerInch; - if (yEndMsg != 0) yEndMsg += adjMsgY; + //// Account for extra lines in the end message (flag < 0) + float adjMsgY = (float)-MyItemInfo.MyDocStyle.End.Flag * SixLinesPerInch; + if (yEndMsg != 0) yEndMsg += adjMsgY; } // F2023-015 check if on the first step of a sub-section that starts on its own page (separate pagination) // Beaver Valley as two sub-sections that are printed continuously followed by a third sub-section printed separate. @@ -489,7 +448,6 @@ namespace Volian.Print.Library ShowPageBreak(-1, "HLS will fit on page", firstStep, YSize, yPageSize, yWithinMargins,ManualPageBreak); return 0; } - // !MyItemInfo.IsHigh - if (MyItemInfo.IsRNOPart && MyParent.XOffset < XOffset) return 0; // Don't paginate on an RNO to the right // YSize includes a blank line after the step which we don't want to include in the page break test, thus the // YSize - SixLinesPerInch: @@ -504,8 +462,6 @@ namespace Volian.Print.Library if (MyItemInfo.IsStep && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex != null && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex >= 0 && (MyItemInfo.RNOs == null || MyItemInfo.RNOs.Count == 0)) mySize += (2 * SixLinesPerInch); - //if (firstStep == "No") - // ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); if (MyPageHelper.DidFirstPageDocStyle && MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Where & E_DocStyleUse.UseOnAllButFirstPage) > 0)// C2018-003 fixed use of getting the active section yPageSizeNextPage = GetYPageSizeUseOnAllButFirstPage(); @@ -532,33 +488,28 @@ namespace Volian.Print.Library // Keep figure (the only figure, i.e. count==1) with its parent. if (ChildrenBelow.Count == 1 && ChildrenBelow[0].MyItemInfo.IsFigure) KeepStepsOnPage = false; - float sectionSpace = 0; - if (doSectionTitleContinued) - { - if (SectionShowTitles) - { - vlnParagraph paraSect = MyParent; - while (!paraSect.MyItemInfo.IsSection) paraSect = paraSect.MyParent; - if (paraSect.ContinueHeight > 24) - sectionSpace = paraSect.ContinueHeight; - else - sectionSpace = 2 * SixLinesPerInch; - // sectionSpace = 3 * SixLinesPerInch;// this should actuall use the physical size of the continue messsage. - // Fixing this caused problems with pagination ex Calvert Unit 2 IO-1l section 6.1.B step 2 - //if (MyItemInfo.ActiveSection.DisplayText.Length < 40) sectionSpace = SixLinesPerInch; - yPageSizeNextPage -= sectionSpace; - yExtra -= sectionSpace; - //yExtra2 -= sectionSpace; // This was removed for Calvert STP O-73H-2 Section 6.3.O.4 and 6.3.R.3 - } - } - // Added for section that was breaking from steps this code was removed to fix B2020-112 - //if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert && yPageSizeNextPage < yWithinMargins + 3 * 72 && MyItemInfo.MyPrevious == null) - // KeepStepsOnPage = true; - float mySize7LPI = mySize; // +SixLinesPerInch; + if (doSectionTitleContinued) + { + if (SectionShowTitles) + { + vlnParagraph paraSect = MyParent; + while (!paraSect.MyItemInfo.IsSection) paraSect = paraSect.MyParent; + float sectionSpace; + if (paraSect.ContinueHeight > 24) + sectionSpace = paraSect.ContinueHeight; + else + sectionSpace = 2 * SixLinesPerInch; + // this should actuall use the physical size of the continue messsage. + // Fixing this caused problems with pagination ex Calvert Unit 2 IO-1l section 6.1.B step 2 + yPageSizeNextPage -= sectionSpace; + yExtra -= sectionSpace; + } + } + float mySize7LPI = mySize; if (_Match16BitPagination) mySize7LPI += SixLinesPerInch; float tableSpaceAvailable = TableSpaceAvailable;// RHM20150525 - Table Scrunch float ySizeBtmCtnMess1 = GetBottomContinueMessageSize(MyItemInfo.MyDocStyle); - float ySizeBtmEndMess1 = GetBottomEndMessageSize(MyItemInfo.MyDocStyle); + float ySizeBtmEndMess1 = GetBottomEndMessageSize(); // B2017-154 Don't leave an orphan on the next page if the high level step and first sub-step will fit on the current page if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.NoOrphans1 && KeepStepsOnPage && ChildrenBelow.Count == 2)// Handle Orphans when there are two sub-steps and only one will fit. { @@ -604,7 +555,6 @@ namespace Volian.Print.Library // ySize7LPI includes a blank line after the step which we don't want to include in the page break test. else if (!KeepStepsOnPage && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CompressSteps - //&& (mySize7LPI - SixLinesPerInch + yEndMsg - tableSpaceAvailable) < (yPageSizeNextPage * SixLinesPerInch / _SevenLinesPerInch))// RHM20150525 - Table Scrunch // if this is the first step, then the step has to fit in the space that remains on the page // otherwise it needs to fit on a blank page // This was originally (10/12/2015) added for Farley Shared AOP 79 but was found to be unnecessary @@ -631,24 +581,9 @@ namespace Volian.Print.Library float myFirstPieceSize = GetFirstPieceSize(); //Case 0 if (_Match16BitPagination) myFirstPieceSize += 2 * SixLinesPerInch; // TODO: Put this line back to case 0, i.e. previous line. This fixes a 16-bit vs 32-bit pagination diff in EO30 Step 20. - //float myFirstPieceSize = GetFirstPieceSize() + 2 * SixLinesPerInch; //Case 10 - this is to match 16bit + //Case 10 - this is to match 16bit //is the amount of space left (yWithinMargins) is greater than 1/2 of the current page (yPageSize / 2): // VCS EOP-4.3 Step 15 - // ***** Adjust yWithinMargins for the bottom continue message - //DocStyle docstyle = MyItemInfo.MyDocStyle; - //string myBottomMsg = docstyle.Continue.Bottom.Message; - //float myBottomMsgSpace = ((myBottomMsg ?? "") != "") ? 2 * SixLinesPerInch : 0; - //switch (docstyle.Continue.Bottom.Location) - //{ - // case E_ContBottomLoc.BottomOfPage: // place continue message at bottom of page - // // The following format flag was added for FNP, without the flag (which stops the reset of BottomMsgSpace) - // // a number of FNP procedures had overwritten steps/bottom continue message. An example can be - // // found in FNP = SAMGS;FNP-1-SACRG-2, step 1. - // if (!docstyle.Continue.Bottom.NoOverrideSpace) - // myBottomMsgSpace = 0; - // break; - //} - //float yWithinMarginsCM = yWithinMargins - myBottomMsgSpace; //// **** Adjust yWithinMargins for the bottom continue message // B2018-080 Don't break if HLS and High Level RNO each have one line of text and there are substeps (keep single line HSL and High Level RNO with their substeps) AEP AOP Unit 1 016-004 steps 36 & 74 // B2018-081 The previous fix caused a different issue @@ -668,8 +603,6 @@ namespace Volian.Print.Library ySpaceOnFirstPage = yWithinMargins; // Accounts for Section Title Line //ShowPageBreak(8, CheckForCompression("First HLS has to split on current page"), firstStep, YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak); //} - //else - // ShowPageBreak(6, CheckForCompression("HLS will have to split on current page"), "Special", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak); //BuildPageBreakList(yWithinMargins + SixLinesPerInch, yPageSizeNextPage + yExtra2, KeepStepsOnPage); // Case 5 - Determine items where page break(s) occur // B2020-027: adjust for lines that may print on first page of section only, added MyPageHelper.PrintedSectionPage // B2020-108: The bug itself was related to keeping a table with its parent. However compression for some pages was @@ -695,7 +628,6 @@ namespace Volian.Print.Library // o888o if (firstStep == "Yes") { - //ySpaceOnFirstPage = yWithinMargins; // Accounts for Section Title Line ShowPageBreak(8, CheckForFirstCompression("First HLS has to split on current page"), firstStep, YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak); } else @@ -754,6 +686,7 @@ namespace Volian.Print.Library ShowPageBreak(3, CheckForFirstCompression("HLS will have to split on new page"), "Yes", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak); return 1; // Paginate on High Level Steps } + //For Debugging: //if (yWithinMargins > yPageSize / 2) //{ // Console.WriteLine("'PageBreak',4,'No','Not Half way down the page',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath); @@ -780,7 +713,7 @@ namespace Volian.Print.Library return hasAER && hasRNO; } // B2018-058 the the end message height accounting for multi-line end messages - private float GetEndMessageHeight(DocStyle docstyle) + private float GetEndMessageHeight() { float EndMsgHeight = 0; string endmsg = MyItemInfo.MyDocStyle.End.Message ?? ""; @@ -791,12 +724,12 @@ namespace Volian.Print.Library } return EndMsgHeight; } - private float GetBottomEndMessageSize(DocStyle docstyle) + private float GetBottomEndMessageSize() { float myBottomMsgSpace = 0; if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null && MyItemInfo.MyDocStyle.End.Flag < 0) // Adjust this many lines down the page. { - docstyle = MyItemInfo.MyDocStyle; + DocStyle docstyle = MyItemInfo.MyDocStyle; string myBottomMsg = docstyle.End.Message; myBottomMsgSpace = ((myBottomMsg ?? "") != "") ? 2 * SixLinesPerInch : 0; if (myBottomMsg != null && docstyle.End.Flag < 0) myBottomMsgSpace += (-(float)docstyle.End.Flag * SixLinesPerInch); @@ -806,20 +739,20 @@ namespace Volian.Print.Library private string CheckForFirstCompression(string reason) { if (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].CompressFirstPartOfStep) - return reason + " - 7 LPI"; + return $"{reason} - 7 LPI"; return reason; } private string CheckForCompression(string reason) { if (CompressPartOfStep) - return reason + " - 7 LPI"; + return $"{reason} - 7 LPI"; return reason; } private string AddReason(string prefix) { string retval = prefix; if (PageBreakReason != null) - retval += " - " + PageBreakReason; + retval += $" - {PageBreakReason}"; return retval; } private bool SectionShowTitles @@ -864,8 +797,6 @@ namespace Volian.Print.Library DebugText.WriteLine("*****PaginateError"); yPageStart = yTopMargin + YVeryTop; yLocation = yPageStart - YOffset; - //MyItemInfo.ItemID, YSize, yPageSize, yLocation - //_MyLog.ErrorFormat("<<< ERROR >>> Forced Pagination - ItemID = {0}\r\nLocation = '{1}'", MyItemInfo.ItemID, MyItemInfo.ShortPath); _MyLog.ErrorFormat("<<< ERROR >>> Forced Pagination\r\n==>'Forced Pagination',{0},'{1}','{2}'" , MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath); if (DebugPagination.IsOpen) DebugPagination.WriteLine("=====>,'Yes','Forced Pagination',{0},{1},,{3},'{4}'", MyItemInfo.ItemID, YSize, 0, yLocation, MyItemInfo.ShortPath); @@ -927,11 +858,8 @@ namespace Volian.Print.Library return _AlternateBreaks; } } - private void AddAlternateBreak(vlnParagraph vp) - { - AlternateBreaks.Add(vp); - } - private bool CheckAlternates(vlnParagraph vpBrk) + private void AddAlternateBreak(vlnParagraph vp) => AlternateBreaks.Add(vp); + private bool CheckAlternates(vlnParagraph vpBrk) { if (_AlternateBreaks == null) return false; foreach(vlnParagraph vp in AlternateBreaks) @@ -957,7 +885,7 @@ namespace Volian.Print.Library public float yPageSizeForPagination = -1; private void BuildPageBreakList(float ySpaceOnCurPage, float yPageSize, bool KeepStepsOnPage, float yEndMsg, bool doSectionTitleContinued, bool onNewPage) { - float topContinueHeight = 2 * SixLinesPerInch; + float topContinueHeight; //Defaults to: 2 * SixLinesPerInch; int profileDepth = ProfileTimer.Push(">>>> BuildPageBreakList"); // if this paragraph is flagged to pagebreakonstep (i.e. these are used by background documents // to get each hls/caution/note to be on its own page), then any of the children above should @@ -997,9 +925,8 @@ namespace Volian.Print.Library // the following logic was added to fix Pagination for VCS BDMG1 Step 4 if (ChildrenRight.Count > 0 && ChildrenRight[0].YOffset == YOffset) { - float myFirstPieceRNOSize = 0; - myFirstPieceRNOSize = ChildrenRight[0].GetFirstPieceSize(); - if(myFirstPieceRNOSize < ySpaceOnCurPage) + float myFirstPieceRNOSize = ChildrenRight[0].GetFirstPieceSize(); + if (myFirstPieceRNOSize < ySpaceOnCurPage) if (ChildrenBelow.Count > 0) { float myFirstPieceAERSize = ChildrenBelow[0].GetFirstPieceSize() + ChildrenBelow[0].YOffset - YOffset; @@ -1008,7 +935,6 @@ namespace Volian.Print.Library } } if (myFirstPieceSize < ySpaceOnCurPage) yLowerLimit = Math.Max(myFirstPieceSize + yStart, yLowerLimit); - //while ((YSize - yTop) >= ySpaceOnCurPage) // Pagination Fix Break1LineShort3b DocStyle docstyle = MyItemInfo.MyDocStyle; float myBottomMsgSpace = GetBottomContinueMessageSize(docstyle); @@ -1052,21 +978,12 @@ namespace Volian.Print.Library // The following code determines space required by the Checklist header (Wolf Creek) if a break occurs // Their 2 HLS that define the checklists have 'UseSmartTemplate'. float accountForSmartTemplateHeader = 0; - //if (MyItemInfo.InList(878)) Console.WriteLine("Here"); if (MyItemInfo.FormatStepData.UseSmartTemplate) { if (((MyItemInfo.MyDocStyle.End.Message ?? "") == "") || MyItemInfo.MyHLS.NextItem != null) ySpaceOnCurPage += SixLinesPerInch; accountForSmartTemplateHeader = Height - (2 * SixLinesPerInch); } - // This was added so that if a page break was immediately necessary the code would use the current step. - // However, a better solution was found and put in Paginate() - //if (YSize == Height + SixLinesPerInch && YSize + yEndMsg >= ySpaceOnCurPage) - //{ - // _MyLog.WarnFormat("Would have been unable to break {0},{1}",MyItemInfo.ItemID, MyItemInfo.ShortPath); - // MyPageHelper.ParaBreaks.Add(this); - // return; - //} // ooooo ooo . oooooooooo. oooo // `888b. `8' .o8 `888' `Y8b `888 // 8 `88b. 8 .ooooo. oooo ooo .o888oo 888 888 oooo d8b .ooooo. .oooo. 888 oooo @@ -1170,7 +1087,8 @@ namespace Volian.Print.Library myBottomMsgSpace, MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly, yTop); if (paraBreak2 != null && paraBreak != paraBreak2) { - yLoc = ySpaceOnCurPage - (paraBreak2.YOffset - (YTopMost + yTop - paraBreak2.Height)); + //For Debugging: + //yLoc = ySpaceOnCurPage - (paraBreak2.YOffset - (YTopMost + yTop - paraBreak2.Height)); if (paraBreak.YOffset == paraBreak2.YOffset + paraBreak2.Height) { //_MyLog.WarnFormat("Fix Break when no blank line {0},{1},{2}", paraBreak2.MyItemInfo.ShortPath, paraBreak2.MyItemInfo.ItemID,yLoc); @@ -1211,10 +1129,7 @@ namespace Volian.Print.Library } if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) // only do the following for Calvert Alarms { - //if (lastBreak != null && lastBreak.MyItemInfo.InList(42656,42923)) Console.WriteLine("here"); // Or Step whose parent fits on a page should break at the parent step - //if (MyItemInfo.InList(119826)) Console.WriteLine("here"); - //if (paraBreak.MyItemInfo.InList(40339)) float ySpaceOnNextPage = yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace; if (paraBreak.MyItemInfo.IsOr && paraBreak.MyParent.YSize < ySpaceOnNextPage) { @@ -1307,7 +1222,8 @@ namespace Volian.Print.Library if (firstLevel.MyParent.ChildrenBelow != null && firstLevel.MyParent.ChildrenBelow.Count > 0 && firstLevel.MyParent.ChildrenBelow[0] != firstLevel && firstLevel.YSize < yPageSize - (myTopMsgSpace + SixLinesPerInch)) { - vlnParagraph firstLevel1 = firstLevel; + //For Debugging: + //vlnParagraph firstLevel1 = firstLevel; if (firstLevel.ChildrenAbove != null && firstLevel.ChildrenAbove.Count > 0) // If the aerParent has caution or note firstLevel = firstLevel.ChildrenAbove[0];//, break on the caution or note. if (firstLevel != lastBreak && paraBreak != firstLevel) @@ -1320,14 +1236,10 @@ namespace Volian.Print.Library } // If the break is going to happen on a table, and the tables parent would fit on a page with the table // and the text in the parent includes the word table, then break on the parent - //if (lastBreak != paraBreak.MyParent && paraBreak.MyItemInfo.IsTable && paraBreak.YSize < ySpaceOnCurPage && paraBreak.MyParent.MyItemInfo.DisplayText.ToUpper().Contains("TABLE")) - // paraBreak = paraBreak.MyParent; //paraBreak.ShowPageBreak(999, paraBreak.MyItemInfo.ShortPath, "Yes",paraBreak.YTop, paraBreak.YSize, paraBreak.Height, false); //_MyLog.InfoFormat("Place to break\r\n==>'Place to Break',{0},'{1}','{2}'" //, paraBreak.MyItemInfo.ItemID, paraBreak.MyItemInfo.MyDocVersion.MyFolder.Name, paraBreak.MyItemInfo.ShortPath); // yTopNew is y Location of this page break. YTopMost is top of HLS, including any Cautions/Notes/Boxes/etc - //float yTopNew = paraBreak.YVeryTop - YTopMost; - //float yTopNew = paraBreak.YTopMost - YTopMost; if (JustATableThatWillFit(paraBreak, yPageSize - (myTopMsgSpace + yEndMsg))) paraBreak = paraBreak.ChildrenBelow[0]; // B2020-112: complicated AER/RNO. yEndMsg was accounted for twice -> put endmsg part back in, it broke wcn and didn't affect bge @@ -1412,14 +1324,6 @@ namespace Volian.Print.Library PageBreakOnStepList.RemoveAt(0); yTopNew = paraBreak.YTop - YTopMost; } - // The following code caused forced pagination for Catawba EOP BG - EP/1/A/5000/FR-C.1.SC..S16..N2..S4..S1. - //else if(PageBreakOnStepList[0].YSize - yTop <= ySpaceOnCurPage) - //{ - // DebugPagination.WriteLine("======>>>>> Other Condition"); - // paraBreak = PageBreakOnStepList[0]; - // PageBreakOnStepList.RemoveAt(0); - // yTopNew = paraBreak.YTop - YTopMost; - //} } RemoveProcessedParagraphs(myList, yTopNew - yTop); yTop = yTopNew; @@ -1440,13 +1344,6 @@ namespace Volian.Print.Library // B2017-252 Pagination Fix - RNP was not paginating correctly. Added logic to set ySPaceOnCurPage if ySpaceOnNextPage was larger if (!usedPageBreakOnStepList || ySpaceOnNextPage1 > ySpaceOnCurPage) ySpaceOnCurPage = ySpaceOnNextPage1; - //ySpaceOnCurPage = yPageSize - (myTopMsgSpace + SixLinesPerInch); // Allow for continue message and blank line. - //if (paraBreak.YTopMost != paraBreak.YVeryTop && MyPageHelper.TopMessage == null && MyPageHelper.BottomMessage == null) - // ySpaceOnCurPage = yPageSize; - //ySpaceOnCurPage = yPageSize; // Allow for continue message and blank line. - //DocStyle docstyle = MyItemInfo.MyDocStyle; - //string myMsg = docstyle.Continue.Bottom.Message; - //if ((myMsg ?? "") != "") ySpaceOnCurPage -= 2 * SixLinesPerInch; // Allow for continue message and blank line. yLowerLimit = ySpaceOnCurPage / 2; if (_Match16BitPagination) yLowerLimit -= 1.5F * SixLinesPerInch; // 276 for HLP yStart = 0; @@ -1505,7 +1402,6 @@ namespace Volian.Print.Library { // C2023-015: Pagination on a sub-step added. Do the code if supplemental info or if format supports sub-step pagination // C2023-018: Remove the supplemental info & alarm check, doing the possible page breaks on sub-steps - //if (!MyItemInfo.MyDocStyle.SupplementalInformation && !MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.AlarmPagination) return null; SortedList sdpara = null; foreach (int stepLevel in myList.Keys) // loop thru StepLevels, starting with lowest. { @@ -1534,8 +1430,7 @@ namespace Volian.Print.Library private float GetBottomContinueMessageSize(DocStyle docstyle) { - float myBottomMsgSpace = 0; - docstyle = MyItemInfo.MyDocStyle; + float myBottomMsgSpace; string myBottomMsg = docstyle.Continue.Bottom.Message; myBottomMsgSpace = ((myBottomMsg ?? "") != "") ? 2 * SixLinesPerInch : 0; if (myBottomMsg != null && myBottomMsg.Contains("par")) myBottomMsgSpace += SixLinesPerInch; @@ -1603,7 +1498,7 @@ namespace Volian.Print.Library float? yLocationMin=null; vlnParagraph minPara2 = null; float? yLocationMin2=null; - float yAddForBtmMsg = 0; + float yAddForBtmMsg; // useful for debugging pagination issues, lastbreak gets the paragraph at the top of the previous page, shows all // of the locations within 'range' on the next page. //if (lastBreak != null && lastBreak.MyItemInfo.InList(72481)) @@ -1670,16 +1565,9 @@ namespace Volian.Print.Library // Note that this bug fix for WCN was commented out. Harry Julian wanted this on 11/15/19. A new bug will be written for the WCN error. // B2019-173 reintroduced the 'IsHigh' portion and added IsRNOPart, the HLS & RNOPart print at same location on page so code needs // to account for either. second iteration of this fix removed IsRNOPart (see code in Paginate) - && !myParent.MyItemInfo.IsHigh) /*|| myPara.MyItemInfo.IsRNOPart)) */// B2018-104: don't return if my parent is a high level - a top continue message was printing + && !myParent.MyItemInfo.IsHigh) // B2018-104: don't return if my parent is a high level - a top continue message was printing { //_MyLog.WarnFormat("\r\nMyParentBreak {0},{1},{2},{3},{4}", myParent, myParent.YSize, yUpperLimit, myParent.ChildrenRight[0].YSize, spaceOnPage); - // Removed the following and moved logic to Paginate method for the second iteration of the bug fix. This code below AND the IsRNOPart above caused another - // pagination problem. The insert and subsequent removal of this code are both done under bug B22019-173. - // Initial code for B2019-173: make minPara2 the first step on next page - //if (minPara2 != null && minPara2.MyParent == myParent && minPara2 != lastBreak && minPara2.MyItemInfo.Ordinal == 1) - //{ - // return minPara2; - //} if (myParent != lastBreak) return myParent; } @@ -1736,17 +1624,11 @@ namespace Volian.Print.Library } } } - //while (myPara.MyParent.YTop == myPara.YTop) myPara = myPara.MyParent; while (myPara.MyParent != null && myPara.MyParent.YTop == myPara.YTop) myPara = myPara.MyParent; int everyNLines = myPara.MyItemInfo.MyPrevious != null && myPara.MyItemInfo.FormatStepData == null ? 1 : myPara.MyItemInfo.FormatStepData.StepLayoutData.EveryNLines ?? 1; bool inSameBox = InSameBox(myPara, minPara2); // if this note/caution is in same box as the break, don't break within the notes/cautions in the same box if (!inSameBox && myPara.ChildrenAbove.Count == 0 && wcnChkLstBorder - yLocation < yUpperLimit + yAddForBtmMsg || (everyNLines != 99 && (wcnChkLstBorder - yLocation == yUpperLimit + yAddForBtmMsg))) // Fix for OFN-RJ-23 - //if (-yLocation < yUpperLimit) // Before - //if (-yLocation < yWithinMargins && myList[stepLevel][yLocation].MyItemInfo.MyPrevious != null) { - //ItemInfo prev = myList[stepLevel][yLocation].MyItemInfo.MyPrevious; - //if (myList[stepLevel][yLocation].MyItemInfo.ItemID == 5609) Console.WriteLine("aer"); - //if (myList[stepLevel][yLocation].MyItemInfo.ItemID == 4312) Console.WriteLine("rno"); // The top of this step is more than 1/2 way down the page if ((-yLocation + yStart) >= yLowerLimit) if (myPara != lastBreak) @@ -1819,13 +1701,14 @@ namespace Volian.Print.Library return minPara ?? minPara2; } - // B2020-013 premature break in RNO column - Callaway OTO-AC-00002 step 2 - // B2020-016 bad pagination on RNOs for Robinson AOP-010 step 27 , AOP-024 Step 10, EOP E-0 step 10, EOP ECA-2.1 step 28 - // B2020-073 was not keeping all of RNO sub-step together - Comanche Peak FRC-0.1 (unit 1) Step 14 - // B2020-081 was breaking on an AER substep that has an long RNO - should keep AER substep and part of RNO on the page = D.C. Cook "Current (Post FLEX) U1 NOP NOT [EOPs]" set, ES-0.1 step 1. - // B2020-085 was breaking first child of second RNO (third IF in RNO) - should break on second child of second RNO - D.C. Cook AOP Unit 1 002-020 Step 15 - // B2020-099 was breaking on last sub-step of previous RNO - Calvert Approved Procedures; Abnormal Procedures – Unit 2; AOP-2A; Section VII; Step 11.RNO.11.1.c - private vlnParagraph HasSecondRNOThatWillFit(float yStart, float yLowerLimit, float yUpperLimit, StepLevelList myList, int stepLevel, float yTop) + // B2020-013 premature break in RNO column - Callaway OTO-AC-00002 step 2 + // B2020-016 bad pagination on RNOs for Robinson AOP-010 step 27 , AOP-024 Step 10, EOP E-0 step 10, EOP ECA-2.1 step 28 + // B2020-073 was not keeping all of RNO sub-step together - Comanche Peak FRC-0.1 (unit 1) Step 14 + // B2020-081 was breaking on an AER substep that has an long RNO - should keep AER substep and part of RNO on the page = D.C. Cook "Current (Post FLEX) U1 NOP NOT [EOPs]" set, ES-0.1 step 1. + // B2020-085 was breaking first child of second RNO (third IF in RNO) - should break on second child of second RNO - D.C. Cook AOP Unit 1 002-020 Step 15 + // B2020-099 was breaking on last sub-step of previous RNO - Calvert Approved Procedures; Abnormal Procedures – Unit 2; AOP-2A; Section VII; Step 11.RNO.11.1.c + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping myList and stepLevel for Debugging")] + private vlnParagraph HasSecondRNOThatWillFit(float yStart, float yLowerLimit, float yUpperLimit, StepLevelList myList, int stepLevel, float yTop) { // B2020-120: for calvert alarms/condition response table, don't run code for second rno if (this.ChildrenAbove != null && this.ChildrenAbove.Count > 0) if (HasCalvertMacro) return this; @@ -1856,12 +1739,6 @@ namespace Volian.Print.Library if ((chld.YTopMost + yStart + yTop - yTopParent) < yUpperLimit) return chld; // second RNO will fit, use this instead of myPara - // check to see if there is AER substep children that would be split if we pagination on the RNO - // B2020-150 commented out below. Found it is not needed for B2020-085 fix but it was what cause B2020-150 - //foreach (vlnParagraph chld in parent.ChildrenBelow) - // if (chld.YOffset < this.YOffset && YBottomMostExcludingRNO(chld) > this.YTopMost) // B2020-085 Does AER child start before myPara and length greater than myPara start - // return null; // the AER text positioning overlaps the RNO text positioning (caused AER sub-steps to be split onto next page (i.e. RO step) have pagination logic keep looking for place to break - return this; // current myPara is good } @@ -1903,7 +1780,8 @@ namespace Volian.Print.Library } return false; } - private static int MaxBreakLevel(float yLocation, StepLevelList myList, int maxLevel, vlnParagraph myParaBreak) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping yLocation for Debugging")] + private static int MaxBreakLevel(float yLocation, StepLevelList myList, int maxLevel, vlnParagraph myParaBreak) { foreach (int stepLevel in myList.Keys) foreach (float yLoc in myList[stepLevel].Keys) @@ -1935,27 +1813,7 @@ namespace Volian.Print.Library if (MyParent == null || MyParent.MyItemInfo.IsHigh) return false; return MyParent.HasAncestor(myParaBreak); } - //private void WalkStepLevel(float yTopMost) - //{ - // foreach (vlnParagraph child in ChildrenAbove) - // child.WalkStepLevel(yTopMost); - // foreach (vlnParagraph child in ChildrenLeft) - // child.WalkStepLevel(yTopMost); - // ShowStepLevel(yTopMost); - // foreach (vlnParagraph child in ChildrenRight) - // child.WalkStepLevel(yTopMost); - // foreach (vlnParagraph child in ChildrenBelow) - // child.WalkStepLevel(yTopMost); - //} - //private void ShowStepLevel(float yTopMost) - //{ - // ItemInfo item = MyItemInfo; - // ItemInfo parent = item.ActiveParent as ItemInfo; - // //if (para.MyItemInfo.ItemID == 205) - // // Console.Write(""); - // DebugPagination.WriteLine("'StepLevel',{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}", YVeryTop - yTopMost, YSize, YBottomMost - yTopMost, item.ItemID, item.DBSequence, item.StepLevel, item.MyContent.Type % 10000, - // parent.MyContent.Type % 10000, item.HasCautionOrNote ? 1 : 0, parent.Cautions == null ? 0 : 1); - //} + public float TableSpaceAvailable// RHM20150525 - Table Scrunch { get // B2019-111 Keep AER Table with parent when RNO extends past the end of the page. @@ -1992,18 +1850,7 @@ namespace Volian.Print.Library } public partial class VlnSvgPageHelper : SvgPageHelper { - private bool _OriginalPageBreak; // use 16bit page breaks. - public bool OriginalPageBreak - { - get { return _OriginalPageBreak; } - set { _OriginalPageBreak = value; } - } - // This handles Page Breaks within a Step - private List _ParaBreaks = new List(); - public List ParaBreaks - { - get { return _ParaBreaks; } - set { _ParaBreaks = value; } - } - } + public bool OriginalPageBreak { get; set; } + public List ParaBreaks { get; set; } = new List(); + } } diff --git a/PROMS/Volian.Print.Library/Placekeeper.cs b/PROMS/Volian.Print.Library/Placekeeper.cs index a206f917..4ee9d2df 100644 --- a/PROMS/Volian.Print.Library/Placekeeper.cs +++ b/PROMS/Volian.Print.Library/Placekeeper.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; using LBWordLibrary; using VEPROMS.CSLA.Library; using System.Text.RegularExpressions; @@ -10,12 +7,12 @@ namespace Volian.Print.Library { public class Placekeeper : IDisposable { - private LBApplicationClass _WordApp; - private LBDocumentClass _WordDoc; - private LBSelection _WordSel; + private readonly LBApplicationClass _WordApp; + private readonly LBDocumentClass _WordDoc; + private readonly LBSelection _WordSel; private LBTable _WordTbl; private const string TheQuickBrownFox = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."; - private VE_Font _pkFont; + private readonly VE_Font _pkFont; public Placekeeper() { _WordApp = new LBApplicationClass(); @@ -28,37 +25,11 @@ namespace Volian.Print.Library _WordApp.Visible = true; _WordApp.Activate(); } - //public Placekeeper(pkParagraph myPlacekeeper) - //{ - // _WordApp = new LBApplicationClass(); - // _WordDoc = _WordApp.Documents.Add(); - // _WordSel = _WordApp.Selection; - // _WordApp.Visible = true; - // AddTable(); - // AddHeader(); - // AddSectionHeader(myPlacekeeper.MyParagraph.MyItemInfo.DisplayNumber, myPlacekeeper.MyParagraph.MyItemInfo.DisplayText); - // foreach (pkParagraph pgh in myPlacekeeper.MyChildren) - // { - // AddHighLevelStep(pgh.MyParagraph.MyItemInfo.MyTab.CleanText, pgh.MyParagraph.MyItemInfo.DisplayText, pgh.MyParagraph.MyItemInfo.FormatStepType==9 ? "C" : "", pgh.MyParagraph.MyItemInfo.PageNumber.ToString()); - // if (pgh.MyChildren.Count > 0) - // { - // StartSubStep(); - // foreach (pkParagraph cpgh in pgh.MyChildren) - // { - // ContinueSubStep(cpgh.MyParagraph.MyItemInfo.DisplayText, 1); - // foreach (pkParagraph ccpgh in cpgh.MyChildren) - // ContinueSubStep(ccpgh.MyParagraph.MyItemInfo.DisplayText, 2); - // } - // FinishSubstep("", ""); - // } - // } - //} public Placekeeper(pkParagraphs myPlacekeepers, VE_Font pkFont) { _WordApp = new LBApplicationClass(); _WordDoc = _WordApp.Documents.Add(); _WordSel = _WordApp.Selection; - //_WordApp.Visible = true; _pkFont = pkFont; AddTable(); AddHeader(); @@ -97,7 +68,7 @@ namespace Volian.Print.Library if (cpgh.MyCautionsAndNotes.Count > 0) AddNotesOrCautions(cpgh,level, ref conAct); if (!conAct) - conAct = IsContinuousActionPlacekeeper(conAct, cpgh); + conAct = IsContinuousActionPlacekeeper(cpgh); ContinueSubStep(cpgh.MyParagraph.MyItemInfo.FormattedDisplayText, level); AddChildren(cpgh, level+1, ref conAct); } @@ -108,19 +79,14 @@ namespace Volian.Print.Library foreach (pkParagraph cpgh in pgh.MyCautionsAndNotes) { if (!conAct) - conAct = IsContinuousActionPlacekeeper(conAct, cpgh); + conAct = IsContinuousActionPlacekeeper(cpgh); ContinueNoteOrCaution(cpgh.MyParagraph.MyItemInfo, level); } } - private static bool IsContinuousActionPlacekeeper(bool conAct, pkParagraph pkPar) - { - StepConfig sc = pkPar.MyParagraph.MyItemInfo.MyConfig as StepConfig; - conAct = (sc.Step_Placekeeper.ToUpper() == "C"); - return conAct; - } + private static bool IsContinuousActionPlacekeeper(pkParagraph pkPar) => (pkPar.MyParagraph.MyItemInfo.MyConfig as StepConfig).Step_Placekeeper.ToUpper() == "C"; - private void ContinueNoteOrCaution(ItemInfo ii, int level) + private void ContinueNoteOrCaution(ItemInfo ii, int level) { string NoteCautionTab = "NOTE: "; if (ii.IsCaution) NoteCautionTab = "CAUTION: "; @@ -176,22 +142,17 @@ namespace Volian.Print.Library _WordTbl.TopPadding = 6F; _WordTbl.BottomPadding = 6F; LBColumn col = _WordTbl.Columns.First; - //col.SetWidth(12F, LBWdRulerStyle.wdAdjustNone); - //col = col.Next; col.SetWidth(72 * .91F, LBWdRulerStyle.wdAdjustNone); col = col.Next; col.SetWidth(72 * 4.1F, LBWdRulerStyle.wdAdjustNone); col = col.Next; - //col.SetWidth(72 * .81F, LBWdRulerStyle.wdAdjustNone); col.SetWidth(72 * .76F, LBWdRulerStyle.wdAdjustNone); col = col.Next; - //col.SetWidth(72 * .81F, LBWdRulerStyle.wdAdjustNone); col.SetWidth(72 * .76F, LBWdRulerStyle.wdAdjustNone); _WordTbl.Rows.AllowBreakAcrossPages = 0; } private void AddHeader() { - //Advance(); WriteCell("START", true, true); SetIndent(0.32F, -0F); WriteCell("FUNCTION", true, true); @@ -219,7 +180,6 @@ namespace Volian.Print.Library // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 - //System.Drawing.Font font = new System.Drawing.Font(_pkFont.Family, (float)_pkFont.Size); System.Drawing.Font font = VE_Font.GetWinSysFont(_pkFont.Family, (float)_pkFont.Size); iTextSharp.text.Font iFont = Volian.Svg.Library.VolianPdf.GetFont(font); float w = 0; @@ -227,8 +187,6 @@ namespace Volian.Print.Library { w += iFont.BaseFont.GetWidthPointKerned(c.ToString(), (float)_pkFont.Size); } - // indented text didn't always line up doing it this way - //float w = iFont.BaseFont.GetWidthPointKerned(txt, (float)_pkFont.Size); return w; } private void AddHighLevelStep(string number, string text, string done, string page) @@ -276,7 +234,6 @@ namespace Volian.Print.Library { Advance(2); SetIndent(.64F, -.31F); - //_WordSel.InsertSymbol(8226, _WordSel.Font, System.Reflection.Missing.Value, System.Reflection.Missing.Value); WriteCell("\u2022" + "\t" + text, false, true); SetAlignment(LBWdParagraphAlignment.wdAlignParagraphCenter, LBWdCellVerticalAlignment.wdCellAlignVerticalBottom); WriteCell(done, false, true); @@ -316,7 +273,7 @@ namespace Volian.Print.Library SetAlignment(LBWdParagraphAlignment.wdAlignParagraphCenter, LBWdCellVerticalAlignment.wdCellAlignVerticalBottom); WriteCell(page, false, false); } - static Regex rgx = new Regex(@"\\(b|ul|up[1-9]|dn0|up0|dn[1-9]|b0|ulnone)( |$|(?=\\))"); + static readonly Regex rgx = new Regex(@"\\(b|ul|up[1-9]|dn0|up0|dn[1-9]|b0|ulnone)( |$|(?=\\))"); private void WriteRTF(string text) { //if (text.Contains("\\")) @@ -381,13 +338,7 @@ namespace Volian.Print.Library { _WordSel.MoveRight(LBWdUnits.wdCell, count, false); } - private void Advance() - { - Advance(1); - } - public void Dispose() - { - _WordApp.Quit(false); - } - } + private void Advance() => Advance(1); + public void Dispose() => _WordApp.Quit(false); + } } diff --git a/PROMS/Volian.Print.Library/PromsPrinter.cs b/PROMS/Volian.Print.Library/PromsPrinter.cs index 791f8b81..0350a243 100644 --- a/PROMS/Volian.Print.Library/PromsPrinter.cs +++ b/PROMS/Volian.Print.Library/PromsPrinter.cs @@ -3,58 +3,39 @@ using System.Collections.Generic; using System.Text; using VEPROMS.CSLA.Library; using Volian.Svg.Library; -using iTextSharp.text.factories; using iTextSharp.text; using iTextSharp.text.pdf; using System.Text.RegularExpressions; using System.IO; -using System.Xml; using System.Windows.Forms; -using LBWordLibrary; using System.Drawing; -using System.Drawing.Imaging; -using Volian.Controls.Library; using Volian.Base.Library; using JR.Utils.GUI.Forms; +using System.Linq; namespace Volian.Print.Library { public delegate void PromsPrinterStatusEvent(object sender, PromsPrintStatusArgs args); public class PromsPrintStatusArgs { - private string _MyStatus; - public string MyStatus - { - get { return _MyStatus; } - } - private DateTime _When = DateTime.Now; - public DateTime When - { - get { return _When; } - } - private PromsPrinterStatusType _Type; - public PromsPrinterStatusType Type - { - get { return _Type; } - set { _Type = value; } - } - private int _Progress = 0; + private readonly string _MyStatus; + public string MyStatus => _MyStatus; + private readonly DateTime _When = DateTime.Now; + public DateTime When => _When; - public int Progress - { - get { return _Progress; } - set { _Progress = value; } - } - public PromsPrintStatusArgs(string myStatus, PromsPrinterStatusType type) + public PromsPrinterStatusType Type { get; set; } + + public int Progress { get; set; } = 0; + public PromsPrintStatusArgs(string myStatus, PromsPrinterStatusType type) { _MyStatus = myStatus; - _Type = type; + Type = type; } public PromsPrintStatusArgs(string myStatus, PromsPrinterStatusType type, int progress) { _MyStatus = myStatus; - _Type = type; - _Progress = progress; + Type = type; + Progress = progress; } } public enum PromsPrinterStatusType @@ -99,162 +80,48 @@ namespace Volian.Print.Library public E_SupInfoPrintType SupInfoPrintType = E_SupInfoPrintType.None; // used to link supinfo steps in pdf public int SupInfoPdfPageCount = -1; - private Dictionary _SupInfoPdfPage; - public Dictionary SupInfoPdfPage - { - get { return _SupInfoPdfPage; } - set { _SupInfoPdfPage = value; } - } - private bool _DoingFacingPage = false; // used to flag actual pdf generation of facing page within final print (so no section titles get printed) - public bool DoingFacingPage - { - get { return _DoingFacingPage; } - set { _DoingFacingPage = value; } - } - // used to save word sections with resolved ROs (for export file generated from approve) - private Dictionary _DocReplace; - public Dictionary DocReplace - { - get { return _DocReplace; } - set { _DocReplace = value; } - } - private bool _SaveLinks = false; - public bool SaveLinks - { - get { return _SaveLinks; } - set { _SaveLinks = value; } - } - // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. - // Use these 2 lists to track the items that will need to be saved after removing trailing newlines/spaces or - // manual page breaks, if the user selects to do that. - private List _RemoveTrailingHardReturnsAndSpaces = null; - public List RemoveTrailingHardReturnsAndSpaces - { - get { return _RemoveTrailingHardReturnsAndSpaces; } - set { _RemoveTrailingHardReturnsAndSpaces = value; } - } - private List _RemoveManualPageBreaks = null; - public List RemoveManualPageBreaks - { - get { return _RemoveManualPageBreaks; } - set { _RemoveManualPageBreaks = value; } - } - private string _Prefix = ""; // RHM20150506 Multiline ItemID TextBox - public string Prefix - { - get { return _Prefix; } - set { _Prefix = value; } - } + public Dictionary SupInfoPdfPage { get; set; } + public bool DoingFacingPage { get; set; } = false; + public Dictionary DocReplace { get; set; } + public bool SaveLinks { get; set; } = false; + public List RemoveTrailingHardReturnsAndSpaces { get; set; } = null; + public List RemoveManualPageBreaks { get; set; } = null; + public string Prefix { get; set; } = ""; - // B2024-062 Set to true when the procedure being printed has no content. - // When set to true, will prevent the "Try Again" dialog from appearing - // and simply exit the print function - private bool _EmptyProcedure = false; - public bool EmptyProcedure - { - get { return _EmptyProcedure; } - } - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + // B2024-062 Set to true when the procedure being printed has no content. + // When set to true, will prevent the "Try Again" dialog from appearing + // and simply exit the print function + private bool _EmptyProcedure = false; + public bool EmptyProcedure => _EmptyProcedure; + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public event PromsPrinterStatusEvent StatusChanged; - internal void OnStatusChanged(object sender, PromsPrintStatusArgs args) - { - if (StatusChanged != null) - StatusChanged(sender, args); - } - internal void OnStatusChanged(string myStatus, PromsPrinterStatusType type) - { - OnStatusChanged(this, new PromsPrintStatusArgs(myStatus, type)); - } - public void OnStatusChanged(string msg) - { - OnStatusChanged(this, new PromsPrintStatusArgs(msg, PromsPrinterStatusType.General)); - } - internal void OnStatusChanged(string myStatus, PromsPrinterStatusType type, int progress) - { - OnStatusChanged(this, new PromsPrintStatusArgs(myStatus, type, progress)); - } - private string _Rev; - private ItemInfo _MyItem; - public ItemInfo MyItem - { - get { return _MyItem; } - set { _MyItem = value; } - } - private string _Watermark; - private string _WatermarkColor; - //C2018-009 print PROMS version - private string _PromsVersion = ""; - public string PromsVersion - { - get { return _PromsVersion; } - set { _PromsVersion = value; } - } - private string _PDFFile; - public string PDFFile - { - get { return _PDFFile; } - set { _PDFFile = value; } - } - private int _prtSectID = -1; - public int PrtSectID - { - get { return _prtSectID; } - set { _prtSectID = value; } - } - private bool _DebugOutput; - public bool DebugOutput - { - get { return _DebugOutput; } - set { _DebugOutput = value; } - } - private string _BackgroundFolder; - public string BackgroundFolder - { - get { return _BackgroundFolder; } - set { _BackgroundFolder = value; } - } - private bool _OpenPDF; + internal void OnStatusChanged(object sender, PromsPrintStatusArgs args) => StatusChanged?.Invoke(sender, args); + internal void OnStatusChanged(string myStatus, PromsPrinterStatusType type) => OnStatusChanged(this, new PromsPrintStatusArgs(myStatus, type)); + public void OnStatusChanged(string msg) => OnStatusChanged(this, new PromsPrintStatusArgs(msg, PromsPrinterStatusType.General)); + internal void OnStatusChanged(string myStatus, PromsPrinterStatusType type, int progress) => OnStatusChanged(this, new PromsPrintStatusArgs(myStatus, type, progress)); + private readonly string _Rev; - public bool OpenPDF - { - get { return _OpenPDF; } - set { _OpenPDF = value; } - } - private bool _OverWrite; + public ItemInfo MyItem { get; set; } + private readonly string _Watermark; + private readonly string _WatermarkColor; - public bool OverWrite - { - get { return _OverWrite; } - set { _OverWrite = value; } - } - private ChangeBarDefinition _MyChangeBarDefinition; - public ChangeBarDefinition MyChangeBarDefinition - { - get { return _MyChangeBarDefinition; } - set { _MyChangeBarDefinition = value; } - } - private bool _OriginalPageBreak; // use 16bit page breaks. - public bool OriginalPageBreak - { - get { return _OriginalPageBreak; } - set { _OriginalPageBreak = value; } - } - private bool _InsertBlankPages; - public bool InsertBlankPages - { - get { return _InsertBlankPages; } - set { _InsertBlankPages = value; } - } - private bool _BatchPrint = true; // flags that a batch-type print is occurring, i.e. AllProcedures or Automatic testing - public bool BatchPrint - { - get { return _BatchPrint; } - set { _BatchPrint = value; } - } - // B2020-159: When printing, if forced pagination errors occurred (see Pagination.cs), put up a dialog with - // the places they occurred. Do not do this is running baseline/automatic print testing. - private static List _ForcedPaginations = null; + public string PromsVersion { get; set; } = ""; + public string PDFFile { get; set; } + public int PrtSectID { get; set; } = -1; + public bool DebugOutput { get; set; } + public string BackgroundFolder { get; set; } + + public bool OpenPDF { get; set; } + + public bool OverWrite { get; set; } + public ChangeBarDefinition MyChangeBarDefinition { get; set; } + public bool OriginalPageBreak { get; set; } + public bool InsertBlankPages { get; set; } + public bool BatchPrint { get; set; } = true; + // B2020-159: When printing, if forced pagination errors occurred (see Pagination.cs), put up a dialog with + // the places they occurred. Do not do this is running baseline/automatic print testing. + private static List _ForcedPaginations = null; public static List ForcedPaginations { get { return PromsPrinter._ForcedPaginations; } @@ -266,7 +133,7 @@ namespace Volian.Print.Library { string pnProbl = null; foreach (string pstr in ForcedPaginations) - pnProbl = pnProbl + "\r\n" + pstr; + pnProbl = $"{pnProbl}\r\n{pstr}"; Clipboard.SetText(pnProbl); return FlexibleMessageBox.Show( "PROMS has identified location(s) in the PDF file that was created that may not have paginated correctly." @@ -286,17 +153,14 @@ namespace Volian.Print.Library get { return PromsPrinter._TransPageNumProblems; } set { PromsPrinter._TransPageNumProblems = value; } } - public static void ClearTransPageNumProblems() - { - _TransPageNumProblems = null; - } - public static DialogResult ReportTransPageNumProblems() + public static void ClearTransPageNumProblems() => _TransPageNumProblems = null; + public static DialogResult ReportTransPageNumProblems() { if (TransPageNumProblems != null && TransPageNumProblems.Count > 0) { string pnProbl = null; foreach (string pstr in TransPageNumProblems) - pnProbl = pnProbl + "\r\n" + pstr; + pnProbl = $"{pnProbl}\r\n{pstr}"; Clipboard.SetText(pnProbl); return FlexibleMessageBox.Show("The following list was placed on the Windows Clipboard." + "\r\nIt shows the page numbers of the locations that are referenced by transitions." @@ -308,42 +172,18 @@ namespace Volian.Print.Library } return DialogResult.No; } - private ReaderHelper _MyReaderHelper; - public ReaderHelper MyReaderHelper - { - get { return _MyReaderHelper; } - set { _MyReaderHelper = value; } - } - private string _BlankPageText; // C2019-004: Allow user to define duplex blank page text - public string BlankPageText - { - get { return _BlankPageText; } - set { _BlankPageText = value; } - } - // use DidAll & MergeNotIncuded to know that printing all (not single) was done. Used w/ merge code to know when to return, i.e. not include in merged pdf - private bool _DidAll; - public bool DidAll // value passed in from frmPdfStatusForm - { - get { return _DidAll; } - set { _DidAll = value; } - } - private bool _MergeNotIncluded; - public bool MergeNotIncluded - { - get { return _MergeNotIncluded; } - set { _MergeNotIncluded = value; } - } - private MergedPdf _MergedPdf; - public MergedPdf MergedPdf - { - get { return _MergedPdf; } - set { _MergedPdf = value; } - } - //B2025-048 Problem with Printing CAS Steps - // default to Normal - // will skip certain logic if CAS Only or CTS Only - public PromsPrinterPrintType PromsPrinterPrintType { get; set; } = PromsPrinterPrintType.Normal; + public ReaderHelper MyReaderHelper { get; set; } + public string BlankPageText { get; set; } + public bool DidAll // value passed in from frmPdfStatusForm + { get; set; } + public bool MergeNotIncluded { get; set; } + public MergedPdf MergedPdf { get; set; } + + //B2025-048 Problem with Printing CAS Steps + // default to Normal + // will skip certain logic if CAS Only or CTS Only + public PromsPrinterPrintType PromsPrinterPrintType { get; set; } = PromsPrinterPrintType.Normal; //B2025-054 Wrong Page Numbers in CAS Summary // when section title continued and CAS @@ -355,65 +195,53 @@ namespace Volian.Print.Library ChangeBarDefinition cbd, String pdfFile, bool insertBlankPages, bool batchPrint, string prefix, bool saveLinks, int removeTrailngHardReturnsAndManualPageBreaks, string blankPageText, bool didAll, MergedPdf mergedPdf, string watermarkColor, int PrtSectID = -1) { Prefix = prefix; // RHM20150506 Multiline ItemID TextBox - _MyItem = myItem; + MyItem = myItem; _Rev = rev; _Watermark = watermark; _WatermarkColor = watermarkColor; - _DebugOutput = debugOutput; - _BackgroundFolder = backgroundFolder; - _OpenPDF = openPDF; - _OverWrite = overWrite; - _MyChangeBarDefinition = cbd; - _PDFFile = pdfFile; - _OriginalPageBreak = origPgBrk; - _InsertBlankPages = insertBlankPages; - _BatchPrint = batchPrint; - _MyReaderHelper = new ReaderHelper(this); - _SaveLinks = saveLinks; + DebugOutput = debugOutput; + BackgroundFolder = backgroundFolder; + OpenPDF = openPDF; + OverWrite = overWrite; + MyChangeBarDefinition = cbd; + PDFFile = pdfFile; + OriginalPageBreak = origPgBrk; + InsertBlankPages = insertBlankPages; + BatchPrint = batchPrint; + MyReaderHelper = new ReaderHelper(this); + SaveLinks = saveLinks; // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. if (removeTrailngHardReturnsAndManualPageBreaks == 1 || removeTrailngHardReturnsAndManualPageBreaks == 3) RemoveTrailingHardReturnsAndSpaces = new List(); if (removeTrailngHardReturnsAndManualPageBreaks == 2 || removeTrailngHardReturnsAndManualPageBreaks == 3) RemoveManualPageBreaks = new List(); - _BlankPageText = blankPageText; - _DidAll = didAll; - _MergeNotIncluded = false; - _MergedPdf = mergedPdf; - _prtSectID = PrtSectID; - //_MyReaderHelper.LoadTree(myItem); + BlankPageText = blankPageText; + DidAll = didAll; + MergeNotIncluded = false; + MergedPdf = mergedPdf; + this.PrtSectID = PrtSectID; } - // Pass 1 PDF Name - private string _BeforePageNumberPdf = null; - public string BeforePageNumberPdf - { - get { return _BeforePageNumberPdf; } - set { _BeforePageNumberPdf = value; } - } - // Pass 2 PDF Name - private string _BeforePageNumber2Pdf = null; - public string BeforePageNumber2Pdf - { - get { return _BeforePageNumber2Pdf; } - set { _BeforePageNumber2Pdf = value; } - } - // B2019-152: MergedLandscapePages is a dictionary whose key is the pdf file name & values are all of the page numbers - // in that pdf that should have landscaped page numbers. These are added when the page is finished (onEndPage) - public static Dictionary> MergedLandscapePages = null; + + public string BeforePageNumberPdf { get; set; } = null; + public string BeforePageNumber2Pdf { get; set; } = null; + // B2019-152: MergedLandscapePages is a dictionary whose key is the pdf file name & values are all of the page numbers + // in that pdf that should have landscaped page numbers. These are added when the page is finished (onEndPage) + public static Dictionary> MergedLandscapePages = null; public string Print(string pdfFolder, bool makePlacekeeper, bool makeContinuousActionSummary, bool makeTimeCriticalActionSummary, int PrtSectID = -1) { - if (_MyItem is ProcedureInfo) + if (MyItem is ProcedureInfo) { - _prtSectID = PrtSectID; - ProcedureConfig pcfg = (ProcedureConfig)(_MyItem as ProcedureInfo).MyConfig; + this.PrtSectID = PrtSectID; + ProcedureConfig pcfg = (ProcedureConfig)(MyItem as ProcedureInfo).MyConfig; if (DidAll && pcfg.Print_NotInMergeAll) // will be merging a pdf, so don't print this procedure if user set that on procedure propertures { - _MergeNotIncluded = true; + MergeNotIncluded = true; return null; } // B2017-186 First do Procedures that don't have page number transitions - if (!(_MyItem.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier || - _MyItem.ActiveFormat.PlantFormat.FormatData.TransData.UseSpecificTransitionModifier)) + if (!(MyItem.ActiveFormat.PlantFormat.FormatData.TransData.UseTransitionModifier || + MyItem.ActiveFormat.PlantFormat.FormatData.TransData.UseSpecificTransitionModifier)) { // B2017-186 Do Facing Page SAMGs - if ((_MyItem as ProcedureInfo).ProcHasSupInfoData) + if ((MyItem as ProcedureInfo).ProcHasSupInfoData) { // Use two passes to print facing page supplemental information for SAMGs // First pass gets pagination for the step sections and stores the associated supplemental information ids in @@ -423,10 +251,10 @@ namespace Volian.Print.Library SectionInfo.ResetLookupStepSectPageBreaks(); // B2017-192: Reset lists for tracking page breaks SectionInfo.ResetLookupStepSectPageBreaksForSupInfo(); SupInfoPrintType = E_SupInfoPrintType.DoPageBreaks; - string retstr = Print(_MyItem as ProcedureInfo, pdfFolder, false, false, false); + string retstr = Print(MyItem as ProcedureInfo, pdfFolder, false, false, false); if (retstr == null) return null; SupInfoPrintType = E_SupInfoPrintType.Merge; - string tmps = Print(_MyItem as ProcedureInfo, pdfFolder, false, false, false); + string tmps = Print(MyItem as ProcedureInfo, pdfFolder, false, false, false); if (!BatchPrint && ForcedPaginations != null && ForcedPaginations.Count > 0) // B2020-159: Forced Pagination Reporting { ReportForcedPaginations(); @@ -436,7 +264,7 @@ namespace Volian.Print.Library } else // B2017-186 Neither Facing Pages or Page Number Transitions { - string tmpss = Print(_MyItem as ProcedureInfo, pdfFolder, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalActionSummary); + string tmpss = Print(MyItem as ProcedureInfo, pdfFolder, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalActionSummary); if (!BatchPrint && ForcedPaginations != null && ForcedPaginations.Count > 0) // B2020-159: Forced Pagination Reporting { ReportForcedPaginations(); @@ -453,7 +281,7 @@ namespace Volian.Print.Library // 2nd pass fills in the page numbers in transitions. DirectoryInfo di = new DirectoryInfo(pdfFolder + @"\PageNumberPass1"); if (!di.Exists) di.Create(); - if ((_MyItem as ProcedureInfo).ProcHasSupInfoData)// B2017-186 Adds Facing Page Code to Page Number Transition Code + if ((MyItem as ProcedureInfo).ProcHasSupInfoData)// B2017-186 Adds Facing Page Code to Page Number Transition Code { // Use two passes to print facing page supplemental information for SAMGs // First pass gets pagination for the step sections and stores the associated supplemental information ids in @@ -461,17 +289,17 @@ namespace Volian.Print.Library // Second pass prints the supplemental information pdfs using the list generated in the first pass to know where to do the // supplemental information page breaks & then merges in those pages when printing the step sections. SupInfoPrintType = E_SupInfoPrintType.DoPageBreaks; - retstr = Print(_MyItem as ProcedureInfo, pdfFolder, false, false, false); + retstr = Print(MyItem as ProcedureInfo, pdfFolder, false, false, false); if (retstr == null) return null; SupInfoPrintType = E_SupInfoPrintType.Merge; } - retstr = Print(_MyItem as ProcedureInfo, pdfFolder + @"\PageNumberPass1", false, false, false); + retstr = Print(MyItem as ProcedureInfo, pdfFolder + @"\PageNumberPass1", false, false, false); if (retstr == null) return null; BeforePageNumberPdf = retstr; BeforePageNumber2Pdf = null; // C2017-018 Initialize Pass 2 PDF Name - ProcedureInfo.RefreshPageNumTransitions(_MyItem as ProcedureInfo); - _MyReaderHelper = new ReaderHelper(this); - retstr = Print(_MyItem as ProcedureInfo, pdfFolder, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalActionSummary); + ProcedureInfo.RefreshPageNumTransitions(MyItem as ProcedureInfo); + MyReaderHelper = new ReaderHelper(this); + retstr = Print(MyItem as ProcedureInfo, pdfFolder, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalActionSummary); if (!BatchPrint && ForcedPaginations != null && ForcedPaginations.Count > 0) // B2020-159: Forced Pagination Reporting { ReportForcedPaginations(); @@ -497,10 +325,10 @@ namespace Volian.Print.Library _MyLog.ErrorFormat("{0} During Save {1}", ex.GetType().FullName, ex.Message); } ClearTransPageNumProblems(); - RefreshPageNumber(_MyItem); - ProcedureInfo.RefreshPageNumTransitions(_MyItem as ProcedureInfo); - _MyReaderHelper = new ReaderHelper(this); - retstr = Print(_MyItem as ProcedureInfo, pdfFolder, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalActionSummary); + RefreshPageNumber(MyItem); + ProcedureInfo.RefreshPageNumTransitions(MyItem as ProcedureInfo); + MyReaderHelper = new ReaderHelper(this); + retstr = Print(MyItem as ProcedureInfo, pdfFolder, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalActionSummary); } } return retstr; @@ -524,15 +352,13 @@ namespace Volian.Print.Library } internal string BuildMSWordPDF(SectionInfo section) { - DateTime tStart = DateTime.Now; string MSWordFile = null; if (section.MyContent.ContentEntryCount == 1) { MSWordToPDF.DocReplace = DocReplace; MSWordFile = MSWordToPDF.GetDocPdf(section, PrintOverride.TextColor); MSWordToPDF.DocReplace = null; - //GC.Collect(); // memory garbage collection - OnStatusChanged("MSWord converted to PDF " + MSWordFile, PromsPrinterStatusType.MSWordToPDF); + OnStatusChanged($"MSWord converted to PDF {MSWordFile}", PromsPrinterStatusType.MSWordToPDF); } return MSWordFile; } @@ -622,12 +448,11 @@ namespace Volian.Print.Library { SectionInfo currentSection = _MyHelper.MySection; SectionInfo nextSection = GetNextSection(currentSection); // _MyHelper.MySection.NextItem as SectionInfo; - //SectionConfig sc = (nextSection ?? currentSection).MyConfig as SectionConfig; - // If we are changing to a different section, then get the config from the nextSection - // else we are still printing in the same section so get the config from the current section - SectionConfig sc = ((!sectionChange || nextSection == null) ? currentSection.MyConfig : nextSection.MyConfig) as SectionConfig; - bool wordMargins = (sc != null && sc.Section_WordMargin == "Y"); - if (wordMargins) + //SectionConfig sc = (nextSection ?? currentSection).MyConfig as SectionConfig; + // If we are changing to a different section, then get the config from the nextSection + // else we are still printing in the same section so get the config from the current section + bool wordMargins = (((!sectionChange || nextSection == null) ? currentSection.MyConfig : nextSection.MyConfig) is SectionConfig sc && sc.Section_WordMargin == "Y"); + if (wordMargins) { if (nextSection != null && (sectionChange) && !nextSection.IsStepSection) //change to a word section { @@ -695,13 +520,9 @@ namespace Volian.Print.Library if (parent == null) return null; return parent.NextItem.GetSectionInfo(); } - private SectionInfo _PreviousWordSection = null; - public SectionInfo PreviousWordSection - { - get { return _PreviousWordSection; } - set { _PreviousWordSection = value; } - } - private SectionInfo _LastWordSection = null; + + public SectionInfo PreviousWordSection { get; set; } = null; + private SectionInfo _LastWordSection = null; public SectionInfo LastWordSection { get { return _LastWordSection; } @@ -712,6 +533,7 @@ namespace Volian.Print.Library } } private int _PageCountOfWordSection = 0; + //For Debugging: //private void ShowNeedForPageSize() //{ // if(PreviousWordSection != null && PreviousWordSection != LastWordSection) @@ -759,16 +581,15 @@ namespace Volian.Print.Library // If enabled, CreateLayers will need to be skipped. //writer.PDFXConformance = PdfWriter.PDFA1B; } - catch (Exception ex) + catch (Exception) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Could not create"); sb.AppendLine(); - sb.AppendLine(outputFileName + "."); + sb.AppendLine($"{outputFileName}."); sb.AppendLine(); sb.AppendLine("If it is open, close and retry."); MessageBox.Show(sb.ToString(), "Error on CreatePdf", MessageBoxButtons.OK, MessageBoxIcon.Warning); - //MessageBox.Show("Could not create " + outputFileName + ". If it is open, close and retry.", "Error on CreatePdf"); return MyContentByte = null; } document.Open(); @@ -788,36 +609,20 @@ namespace Volian.Print.Library return MyContentByte; } - catch (Exception ex) + catch (Exception) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Error occured when creating Print PDF"); sb.AppendLine(); - sb.AppendLine(outputFileName + "."); + sb.AppendLine($"{outputFileName}."); sb.AppendLine(); sb.AppendLine("If it is open, close and retry."); MessageBox.Show(sb.ToString(), "Error Creating PDF", MessageBoxButtons.OK, MessageBoxIcon.Warning); - //MessageBox.Show("Could not create " + outputFileName + ". If it is open, close and retry.", "Error on CreatePdf"); return MyContentByte = null; } } - //private string CreateFileName(string procNumber, string sectNumber, string sectTitle) - //{ - // return FixFileName(procNumber + "_" + ((sectNumber ?? "") != "" ? sectNumber : sectTitle)); - //} - //private string CreateFileName(string procNumber) - //{ - // return FixFileName(procNumber); - //} - //private string FixFileName(string name) - //{ - // return Regex.Replace(name, "[ .,/]", "_") + ".pdf"; - //} - int _StepPageNumber = 0; private VlnSvgPageHelper _MyHelper = null; - //private static PdfReader _MyFoldoutReader = null; - //private static SectionInfo _MyFoldoutSection = null; private static List _MyFoldoutReader = null; public static List MyFoldoutReader { @@ -827,7 +632,7 @@ namespace Volian.Print.Library private static List _MyFoldoutSection = null; private string Print(ProcedureInfo myProcedure, string pdfFolder, bool makePlacekeeper, bool makeContinuousActionSummary, bool makeTimeCriticalAction) { - if (_ForcedPaginations != null) _ForcedPaginations.Clear(); + _ForcedPaginations?.Clear(); int profileDepth = ProfileTimer.Push(">>>> PromsPrinter.Print"); if (_TransPageNumProblems == null) _TransPageNumProblems = new List(); @@ -840,7 +645,7 @@ namespace Volian.Print.Library if (myProcedure.Sections != null) { int cnt = 0; - foreach (SectionInfo mySection in myProcedure.Sections) + foreach (SectionInfo mySection in myProcedure.Sections.OfType()) { if (PrtSectID == -1 || (PrtSectID > -1 && mySection.ItemID == PrtSectID)) { @@ -862,8 +667,8 @@ namespace Volian.Print.Library } } } - OnStatusChanged("Print " + myProcedure.DisplayNumber, PromsPrinterStatusType.Start); - string outputFileName = pdfFolder + "\\" + Prefix + PDFFile; // RHM20150506 Multiline ItemID TextBox + OnStatusChanged($"Print {myProcedure.DisplayNumber}", PromsPrinterStatusType.Start); + string outputFileName = $"{pdfFolder}\\{Prefix}{PDFFile}"; // RHM20150506 Multiline ItemID TextBox string retval = PrintProcedureOrFoldout(myProcedure, null, outputFileName, makePlacekeeper, makeContinuousActionSummary, makeTimeCriticalAction); ProfileTimer.Pop(profileDepth); @@ -893,20 +698,11 @@ namespace Volian.Print.Library } return -1; } - private bool _AllowAllWatermarks = false; - public bool AllowAllWatermarks - { - get { return _AllowAllWatermarks; } - set { _AllowAllWatermarks = value; } - } - private string _WatermarkOverrideColor = "BLUE"; // C2021-019: Override watermark color - public string WatermarkOverrideColor - { - get { return _WatermarkOverrideColor; } - set { _WatermarkOverrideColor = value; } - } - //private PdfReader readerWord; - private string PrintProcedureOrFoldout(ProcedureInfo myProcedure, SectionInfo myFoldoutSection, string outputFileName, bool makePlacekeeper, bool makeContinuousActionSummary, bool makeTimeCriticalActionSummary) + + public bool AllowAllWatermarks { get; set; } = false; + public string WatermarkOverrideColor { get; set; } = "BLUE"; + //private PdfReader readerWord; + private string PrintProcedureOrFoldout(ProcedureInfo myProcedure, SectionInfo myFoldoutSection, string outputFileName, bool makePlacekeeper, bool makeContinuousActionSummary, bool makeTimeCriticalActionSummary) { int profileDepth = ProfileTimer.Push(">>>> PrintProcedureOrFoldout"); Rtf2Pdf.TextAtCounter = 0; @@ -929,9 +725,8 @@ namespace Volian.Print.Library if (myProcedure.Sections != null && !myProcedure.Sections[0].IsStepSection && !doingFoldout) // B2019-166 also don't do this if doing a foldout else it will use the margins set in word { SectionInfo si = myProcedure.Sections[0] as SectionInfo; - SectionConfig sc = si.MyConfig as SectionConfig; - bool wordMargins = (sc != null && sc.Section_WordMargin == "Y"); - if (wordMargins) + bool wordMargins = (si.MyConfig is SectionConfig sc && sc.Section_WordMargin == "Y"); + if (wordMargins) { string pdfFile = BuildMSWordPDF(si); try @@ -975,15 +770,14 @@ namespace Volian.Print.Library string LastFmtName = null; int lastDocStyle = -1; bool firstStepSec = true; - // C2021-019: Override the watermark color, stored in the PSI - color list set as combobox in PSI with list of colors - ProcedureConfig pc = myProcedure.MyConfig as ProcedureConfig; - WatermarkOverrideColor = _WatermarkColor; - if (pc != null) + // C2021-019: Override the watermark color, stored in the PSI - color list set as combobox in PSI with list of colors + WatermarkOverrideColor = _WatermarkColor; + if (myProcedure.MyConfig is ProcedureConfig pc) { string clr = pc.GetValue("PSI", "WATERMARKOVERRIDECLR"); if (clr != null && clr != "") WatermarkOverrideColor = clr.ToUpper().Contains("DEFAULT") ? "BLUE" : clr; } - foreach (SectionInfo mySection in myProcedure.Sections) + foreach (SectionInfo mySection in myProcedure.Sections.OfType()) { if(PrtSectID == -1 || (PrtSectID > -1 && mySection.ItemID == PrtSectID) ) { @@ -1020,11 +814,11 @@ namespace Volian.Print.Library _MyHelper.CreatingSupInfoPage = false; _MyHelper.MyPdfContentByte = cb; - if (!mySection.IsStepSection) _MyHelper.PageBookmarks.Add((ItemInfo)mySection, ((mySection.DisplayNumber ?? "") == "" ? "" : mySection.DisplayNumber + " - ") + mySection.DisplayText, null); + if (!mySection.IsStepSection) _MyHelper.PageBookmarks.Add((ItemInfo)mySection, $"{((mySection.DisplayNumber ?? "") == "" ? "" : $"{mySection.DisplayNumber} - ")}{mySection.DisplayText}", null); if (DebugOutput) { // 16-bit background - string procedureFileName = BackgroundFolder + "\\" + PDFFile.Trim();//CreateFileName(myProcedure.DisplayNumber); + string procedureFileName = $"{BackgroundFolder}\\{PDFFile.Trim()}";//CreateFileName(myProcedure.DisplayNumber); FileInfo VEPromsFile = new FileInfo(procedureFileName); if (VEPromsFile.Exists && !doingFoldout) { @@ -1059,7 +853,7 @@ namespace Volian.Print.Library // C2019-039 Remove automatic zoom on Overlay PDFs //_MyHelper.DoZoomOMatic = DebugOutput; _MyHelper.OriginalPageBreak = OriginalPageBreak; - _MyHelper.PROMSVersion = _PromsVersion; //C2018-009 print PROMS version + _MyHelper.PROMSVersion = PromsVersion; //C2018-009 print PROMS version _MyHelper.WatermarkColor = WatermarkOverrideColor; // C2021-019: save the override for the watermark color OnStatusChanged("After Set PageEvent", PromsPrinterStatusType.SetPageEvent); } @@ -1076,7 +870,7 @@ namespace Volian.Print.Library lastDocStyle = (int)mySection.MyDocStyle.Index; LastFmtName = mySection.ActiveFormat.Name; } - if (!mySection.IsStepSection) _MyHelper.PageBookmarks.Add((ItemInfo)mySection, ((mySection.DisplayNumber ?? "") == "" ? "" : mySection.DisplayNumber + " - ") + mySection.DisplayText, null); + if (!mySection.IsStepSection) _MyHelper.PageBookmarks.Add((ItemInfo)mySection, $"{((mySection.DisplayNumber ?? "") == "" ? "" : $"{mySection.DisplayNumber} - ")}{mySection.DisplayText}", null); _MyHelper.MySection = mySection; //OnStatusChanged("After Set Svg", PromsPrinterStatusType.SetSVG); } @@ -1089,28 +883,27 @@ namespace Volian.Print.Library SectionConfig sc = mySection.MyConfig as SectionConfig; if (sc.Section_PhoneList != null && sc.Section_PhoneList == "Y") { - DocVersionConfig dvc = mySection.MyDocVersion.MyConfig as DocVersionConfig; - if (dvc != null) - { - string phlist = dvc.Print_PhoneList; - if (phlist != null && phlist != "") - { - // count lines: - int cl = 0; - int indx = phlist.IndexOf("\n"); - while (indx > 0) - { - cl++; - if (indx + 1 > phlist.Length) - indx = -1; - else - indx = phlist.IndexOf("\n", indx + 1); - } - if (cl == 0) cl = 1; // phone list is a single line without an ending newline - _MyHelper.PhoneListHeight = cl * vlnPrintObject.SixLinesPerInch; - } - } - } + if (mySection.MyDocVersion.MyConfig is DocVersionConfig dvc) + { + string phlist = dvc.Print_PhoneList; + if (phlist != null && phlist != "") + { + // count lines: + int cl = 0; + int indx = phlist.IndexOf("\n"); + while (indx > 0) + { + cl++; + if (indx + 1 > phlist.Length) + indx = -1; + else + indx = phlist.IndexOf("\n", indx + 1); + } + if (cl == 0) cl = 1; // phone list is a single line without an ending newline + _MyHelper.PhoneListHeight = cl * vlnPrintObject.SixLinesPerInch; + } + } + } } _MyHelper.FinalMessageSectionID = finalMessageSectionID; // set VlnSvgPageHelper with the finalMessageSectionID @@ -1121,12 +914,6 @@ namespace Volian.Print.Library InsertBlankPage(cb); } GenerateTOC(mySection, myProcedure, cb, _TextLayer); - // B2020-102: extra page printing after auto TOC for summer. Retested for Farley and was successful also - // F2018-033: Farley Auto TOC. If doing foldouts or supinfo facing pages, add a blank page after also: - //if (myProcedure.ProcHasSupInfoData && InsertBlankPages) // Bug Fix: B2016-181 - add blank page if page count is even - //{ - // InsertBlankPage(cb); - //} } else { @@ -1189,7 +976,7 @@ namespace Volian.Print.Library _MyHelper.MyPdfContentByte.PdfWriter.CurrentPageNumber, "No PROMS Output"); } } - OnStatusChanged(myProcedure.DisplayNumber + " PDF Creation Completed", PromsPrinterStatusType.Progress, progress); + OnStatusChanged($"{myProcedure.DisplayNumber} PDF Creation Completed", PromsPrinterStatusType.Progress, progress); if (DebugPagination.IsOpen) DebugPagination.TotalPages += cb.PdfWriter.CurrentPageNumber; CloseDocument(outputFileName); if (_MyHelper != null && makePlacekeeper) @@ -1233,7 +1020,7 @@ namespace Volian.Print.Library { _MyHelper.OnBlankPage = true; string baselinemsg = "==Insert Blank Page=="; - if (_BlankPageText != null && _BlankPageText != "") // C2019-004: Allow user to define duplex blank page text + if (BlankPageText != null && BlankPageText != "") // C2019-004: Allow user to define duplex blank page text { if (_MyHelper.IsLandscape) // rotate the blank page message on landscaped pages { @@ -1244,11 +1031,11 @@ namespace Volian.Print.Library string bsfontfamily = MyItem.ActiveFormat.PlantFormat.FormatData.StepDataList[0].Font.Family; int bsfontsize = 26; iTextSharp.text.Font font = FontFactory.GetFont(bsfontfamily, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, bsfontsize, iTextSharp.text.Font.NORMAL, new iTextSharp.text.Color(PrintOverride.TextColor)); - PrintTextMessage(cb, _BlankPageText, _TextLayer, font); + PrintTextMessage(cb, BlankPageText, _TextLayer, font); if (_MyHelper.IsLandscape) cb.RestoreState(); // B2019-019: Add the blank page message to the baseline output file. - baselinemsg = string.Format("==Insert Blank Page With Message \"{0}\"==", _BlankPageText); + baselinemsg = string.Format("==Insert Blank Page With Message \"{0}\"==", BlankPageText); } else cb.PdfDocument.Add(new iTextSharp.text.Table(1)); @@ -1263,30 +1050,12 @@ namespace Volian.Print.Library document.AddCreator(string.Format("{0} {1}", Application.ProductName, Application.ProductVersion)); document.AddAuthor(Volian.Base.Library.VlnSettings.UserID); } - private Placekeeper _MyPlacekeeper = null; - public Placekeeper MyPlacekeeper - { - get { return _MyPlacekeeper; } - set { _MyPlacekeeper = value; } - } + public Placekeeper MyPlacekeeper { get; set; } = null; - private ContinuousActionSummary _MyContActSummary = null; + public ContinuousActionSummary MyContActSummary { get; set; } = null; - public ContinuousActionSummary MyContActSummary - { - get { return _MyContActSummary; } - set { _MyContActSummary = value; } - } - - //F2022-024 Time Critical Action Summary - private ContinuousActionSummary _MyTimeCriticalActSummary = null; - - public ContinuousActionSummary MyTimeCriticalActSummary - { - get { return _MyTimeCriticalActSummary; } - set { _MyTimeCriticalActSummary = value; } - } + public ContinuousActionSummary MyTimeCriticalActSummary { get; set; } = null; public void CreateWordDocPdf(PdfContentByte cb, SectionInfo mySection) { @@ -1340,18 +1109,17 @@ namespace Volian.Print.Library } else { - // see if this section will be added to the table of content. This is for sections that - // precede tha actual Automated TOC section. - SectionConfig sc = mySection.MyConfig as SectionConfig; - if (sc != null && sc.Section_TOC == "Y") - { - string tockey = "TOC" + mySection.ItemID.ToString(); - if (!_MyHelper.MyTOCPageNums.ContainsKey(tockey)) - // increment the CurrentTOCPageNumber by 1 since we haven't hit an - // endpage yet, and that's what increments it to the current page number. - _MyHelper.MyTOCPageNums.Add(tockey, _MyHelper.CurrentTOCPageNumber + 1); - } - } + // see if this section will be added to the table of content. This is for sections that + // precede tha actual Automated TOC section. + if (mySection.MyConfig is SectionConfig sc && sc.Section_TOC == "Y") + { + string tockey = $"TOC{mySection.ItemID}"; + if (!_MyHelper.MyTOCPageNums.ContainsKey(tockey)) + // increment the CurrentTOCPageNumber by 1 since we haven't hit an + // endpage yet, and that's what increments it to the current page number. + _MyHelper.MyTOCPageNums.Add(tockey, _MyHelper.CurrentTOCPageNumber + 1); + } + } float origYoff = (float)mySection.MyDocStyle.Layout.TopMargin; bool resetSvgForCont = true; for (int ii = 0; ii < sectPageCount; ii++) @@ -1432,8 +1200,6 @@ namespace Volian.Print.Library Chunk chk = new Chunk(mySection.DisplayNumber, font); chk.SetLocalDestination(string.Format("ItemID={0}", mySection.ItemID)); //Console.WriteLine("++++ ItemID={0}", mySection.ItemID); - //float x1 = cb.PdfDocument.PageSize.Width / 2; - //float y1 = cb.PdfDocument.PageSize.Height ; // 1.8f; float height = 12 * 1.5F; // B2019-102 Locate the chunk below the bottom of the page ct.SetSimpleColumn(0, -height, chk.GetWidthPoint() * 1.01F, -2 * height); @@ -1468,7 +1234,7 @@ namespace Volian.Print.Library if ((float)mySection.MyDocStyle.End.Flag < 0) // Adjust this many lines down the page. { adjMsgY = (float)(-(float)mySection.MyDocStyle.End.Flag * vlnPrintObject.SixLinesPerInch); - if (ylocation - adjMsgY > mySection.MyDocStyle.Layout.FooterLength) ylocation = ylocation - adjMsgY; + if (ylocation - adjMsgY > mySection.MyDocStyle.Layout.FooterLength) ylocation -= adjMsgY; } bool landscape = (mySection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_WordContentLandscaped) == E_DocStructStyle.DSS_WordContentLandscaped; if (landscape) @@ -1526,7 +1292,7 @@ namespace Volian.Print.Library OnStatusChanged("After NewPage", PromsPrinterStatusType.NewPage); } } - catch (Exception ex) + catch (Exception) { NewPage(); // can we put out 'error on page'? _MyLog.InfoFormat("NewPage error on page {0}", cb.PdfWriter.CurrentPageNumber); @@ -1554,20 +1320,19 @@ namespace Volian.Print.Library else { // Create the list & add this to dictionary, pdf file with page list. - List children = new List(); - children.Add(_MyHelper.CurrentPageNumber); + List children = new List + { + _MyHelper.CurrentPageNumber + }; MergedLandscapePages.Add(tmp, children); } } private void GenerateTOC(SectionInfo tocSection, ProcedureInfo myProcedure, PdfContentByte cb, PdfLayer textLayer) { - iTextSharp.text.pdf.PdfWriter writer = cb.PdfWriter; float _PointsPerPage = PDFPageSize.PaperSizePoints(myProcedure.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize); // C2020-002 paper size is now set in the format files float yTopMargin = _PointsPerPage - (float)tocSection.MyDocStyle.Layout.TopMargin; - float yBottomMargin = Math.Max(0, yTopMargin - (float)tocSection.MyDocStyle.Layout.PageLength); // - 2 * vlnPrintObject.SixLinesPerInch); if (textLayer != null) cb.BeginLayer(textLayer); TableOfContentsData tOfC = tocSection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData; - //ItemInfo procItem = ItemInfo.Get(myProcedure.ItemID); ItemInfo procItem = myProcedure; lastyLocation = 0; AddSectionToTOC(tocSection, procItem, tOfC, cb, yTopMargin, 0, false); // add all of the marked sections and sub-sections to the table of contents @@ -1577,11 +1342,8 @@ namespace Volian.Print.Library _NoBreakYOffset = 0; } float lastyLocation = 0; - private string GetRtfToC(string txt, TableOfContentsData tOfCData) - { - return GetRtfToC(txt, tOfCData, null); - } - private string GetRtfToC(string txt, TableOfContentsData tOfCData, VE_Font overrideFont) + private string GetRtfToC(string txt, TableOfContentsData tOfCData) => GetRtfToC(txt, tOfCData, null); + private string GetRtfToC(string txt, TableOfContentsData tOfCData, VE_Font overrideFont) { StringBuilder _RtfSB = new StringBuilder(); VEPROMS.CSLA.Library.DisplayText toctxt = new VEPROMS.CSLA.Library.DisplayText(txt, tOfCData.Font, false); @@ -1620,11 +1382,10 @@ namespace Volian.Print.Library { int sectCnt = 0; // keep count of which section/sub-section we are processing bool doSubY = false; - int level = 0; - // C2018-004 create meta file for baseline compares - Volian.Base.Library.BaselineMetaFile.WriteLine("TOC Ystart {0} LeftMar {1} ScNmPos {2} ScTtlPos {3} ScPgPos {4}", yPageStart, leftMargin, secNumPos, secTitlePos, secPagePos); + // C2018-004 create meta file for baseline compares + Volian.Base.Library.BaselineMetaFile.WriteLine("TOC Ystart {0} LeftMar {1} ScNmPos {2} ScTtlPos {3} ScPgPos {4}", yPageStart, leftMargin, secNumPos, secTitlePos, secPagePos); bool inGroup = false; - foreach (SectionInfo mySection in ii.Sections) + foreach (SectionInfo mySection in ii.Sections.OfType()) { if (PrtSectID == -1 || (PrtSectID > -1 && mySection.ItemID == PrtSectID)) { @@ -1633,10 +1394,10 @@ namespace Volian.Print.Library if ((mySection.MyDocStyle != null && mySection.MyDocStyle.IncludeInTOC && (sc == null || sc.Section_TOC != "Y")) || ((mySection.MyDocStyle == null || !mySection.MyDocStyle.IncludeInTOC) && (sc != null && sc.Section_TOC == "Y"))) { - // for indenting of subsections, count up tree. Only start indenting - // at third level, i.e. not indent on 1.0 and 1.1, but indent on 1.1.1: - level = 0; - ItemInfo iilvl = mySection as ItemInfo; + // for indenting of subsections, count up tree. Only start indenting + // at third level, i.e. not indent on 1.0 and 1.1, but indent on 1.1.1: + int level = 0; + ItemInfo iilvl = mySection as ItemInfo; while (!iilvl.IsProcedure) { level++; @@ -1715,7 +1476,6 @@ namespace Volian.Print.Library // Do the title first since it may wrap to 2nd line and this is an issue for // doing a pagebreak, i.e. may cause a page break when the number on a single line // would not. - //if (tocSection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData if (level == 0 && tocSection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData.TofCUnderlineFirstLevelTitle) { VE_Font ovrFont = new VE_Font(tOfC.Font.Family, (int)tOfC.Font.Size, (E_Style)tOfC.Font.Style | E_Style.Underline, (float)tOfC.Font.CPI); @@ -1747,7 +1507,6 @@ namespace Volian.Print.Library _MyHelper.ResetSvg(); // needed to reset so that PSNotFirst pagelist justify flag gets used for BGE yLocation = lastyLocation = 0; } - //if (yLocation > 0) yLocation += vlnPrintObject.SixLinesPerInch;// commented out for B2016-200 // for two blank line between last TOC title and the new grouping title float rtnval = Rtf2Pdf.TextAt(cb, myparagraphGrpTitle, leftMargin + secNumPos, yPageStart - yLocation, w, height, "", yBottomMargin); // print the Group Title yLocation += vlnPrintObject.SixLinesPerInch; // for two blank line between last TOC title and the new grouping title - added for B2016-200 if (lnsp > -1) yLocation += (lnaftergroup * vlnPrintObject.SixLinesPerInch); // new line @@ -1768,8 +1527,6 @@ namespace Volian.Print.Library // is put out. retval = Rtf2Pdf.TextAt(cb, myparagraphSecNum, leftMargin + secNumPos + indentOffset, yPageStart - yLocation, numwidth * 1.3F, height, "", yBottomMargin); - //float lSpace = (float)(tOfC.TofCLineSpacing ?? 1) * vlnPrintObject.SixLinesPerInch; - // adjust ylocation for pagenumber - the ylocation will get reset if the // section title split on 2 lines and the page number needs to be on the 2nd line. // Only do this if the title is not empty (the code was meant for if title spans more than a line) @@ -1821,7 +1578,7 @@ namespace Volian.Print.Library spacchrwid += chkt.GetWidthPoint(); while (numSpace > 6) { - spaceStr = spaceStr + tOfC.TofCSpaceChar; + spaceStr += tOfC.TofCSpaceChar; numSpace -= spacchrwid; } @@ -1846,13 +1603,9 @@ namespace Volian.Print.Library } //If the format wants single spacing within subsections (2nd level and lower), then need to figure out // spacing (vcb1 table of contents) - //bool dosuby = (((tocSection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData.TofCLineSpacingSub ?? 1) > 0) - // && (mySection.MyParent.IsSection && ((mySection.Sections != null && mySection.Sections.Count > 0) || (level > 0 && mySection.NextItem != null)))) - // || didGrp; doSubY = (((tocSection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData.TofCLineSpacingSub ?? 1) > 0) && (mySection.MyParent.IsSection && (/* mySection.Sections == null && */ sectCnt < ii.Sections.Count))) // B2016-205 || didGrp; - //float spc = (float)(tOfC.TofCLineSpacing ?? 1); if (doSubY) { float spcs = (float)(tOfC.TofCLineSpacingSub ?? 1); @@ -1881,7 +1634,7 @@ namespace Volian.Print.Library // table of contents for this section, format flag & section has steps: if (mySection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData.TofCAllowHLS && mySection.IsStepSection && mySection.Steps != null && mySection.Steps.Count > 0) - yLocation = AddHLSToTOC(tocSection, mySection, tOfC, cb, yPageStart, yLocation, doSubY, level + 1, adjSecTitlePos); + yLocation = AddHLSToTOC(tocSection, mySection, tOfC, cb, yPageStart, yLocation, level + 1, adjSecTitlePos); } float savYLoc = yLocation; yLocation = AddSectionToTOC(tocSection, mySection, tOfC, cb, yPageStart, yLocation, doSubY); @@ -1900,7 +1653,7 @@ namespace Volian.Print.Library return yLocation; } // C2021-015: Barakah High Level Steps in Table of Contents - private float AddHLSToTOC(SectionInfo tocSection, ItemInfo ii, TableOfContentsData tOfC, PdfContentByte cb, float yPageStart, float yLocation, bool didSubSecLineSpacing, int level, float parTitleXOff) + private float AddHLSToTOC(SectionInfo tocSection, ItemInfo ii, TableOfContentsData tOfC, PdfContentByte cb, float yPageStart, float yLocation, int level, float parTitleXOff) { // if section is not in TOC, don't add the HLSs SectionConfig sc = ii.ActiveSection.MyConfig as SectionConfig; @@ -1932,122 +1685,121 @@ namespace Volian.Print.Library float numwidth = 0; foreach (ItemInfo hls in ii.Steps) // Ouput each HLS that has config flag to include it. { - StepConfig stc = hls.MyConfig as StepConfig; - if (stc != null && stc.Step_IncludeInTOC) - { - float yBottomMargin = yPageStart - (float)tocSection.MyDocStyle.Layout.PageLength + (2 * vlnPrintObject.SixLinesPerInch); + if (hls.MyConfig is StepConfig stc && stc.Step_IncludeInTOC) + { + float yBottomMargin = yPageStart - (float)tocSection.MyDocStyle.Layout.PageLength + (2 * vlnPrintObject.SixLinesPerInch); - // need to do the step number, title & page number. Page number has to be put on at end after number of page is known, so use a Template. - string tmptxt = hls.MyTab.CleanText; - if (tmptxt == null || tmptxt == "") tmptxt = " "; // if no number set to blanks. Without this, low level printing gets confused - string rtfText = GetRtfToC(tmptxt, tOfC); - Paragraph myparagraphStepNum = vlnPrintObject.RtfToParagraph(rtfText); - float width = 0; - foreach (Chunk chkt in myparagraphStepNum.Chunks) - width += chkt.GetWidthPoint(); - if (numwidth == 0) numwidth = width; // keep same xoffset for step text unless overwriting by number (see below) - Rtf2Pdf.Offset = new PointF(0, 2.5F); + // need to do the step number, title & page number. Page number has to be put on at end after number of page is known, so use a Template. + string tmptxt = hls.MyTab.CleanText; + if (tmptxt == null || tmptxt == "") tmptxt = " "; // if no number set to blanks. Without this, low level printing gets confused + string rtfText = GetRtfToC(tmptxt, tOfC); + Paragraph myparagraphStepNum = vlnPrintObject.RtfToParagraph(rtfText); + float width = 0; + foreach (Chunk chkt in myparagraphStepNum.Chunks) + width += chkt.GetWidthPoint(); + if (numwidth == 0) numwidth = width; // keep same xoffset for step text unless overwriting by number (see below) + Rtf2Pdf.Offset = new PointF(0, 2.5F); - // if the starting column of text would be in 'middle of' the number, just put it - // a few spaces after the number. The '182' below represents 2 chars. - float adjStepTitlePos = indentOffset + numwidth + 6; - if (width + indentOffset > adjStepTitlePos) - { - adjStepTitlePos = numwidth + 12 + indentOffset; - numwidth = width; - } + // if the starting column of text would be in 'middle of' the number, just put it + // a few spaces after the number. The '182' below represents 2 chars. + float adjStepTitlePos = indentOffset + numwidth + 6; + if (width + indentOffset > adjStepTitlePos) + { + adjStepTitlePos = numwidth + 12 + indentOffset; + numwidth = width; + } - string tocStepTitle = hls.FormattedDisplayText; - tocStepTitle = ConvertSpecialChars(tocStepTitle, ii.ActiveFormat.PlantFormat.FormatData); // B2019-172 process symbol characters - rtfText = GetRtfToC(tocStepTitle, tOfC); - Paragraph myparagraphStepTitle = vlnPrintObject.RtfToParagraph(rtfText); - width = stepPagePos - adjStepTitlePos - ((tOfC.TofCPageNumAlign.ToUpper() == "RIGHT") ? 18 : 6);// B2021-109 proper adjustment of section title width - copied from leader dots lenth calcuation below - float savTitleWid = width; - // Print the step text - float retval = Rtf2Pdf.TextAt(cb, myparagraphStepTitle, leftMargin + ((tOfC.TofCSecNumPos == tOfC.TofCSecTitlePos && tmptxt.Equals(" ")) ? stepNumPos : adjStepTitlePos), yPageStart - yLocation, width, height, "", yBottomMargin); - if (retval == 0) // couldn't fit, flags need for a page break. - { - NewPage(); - _MyHelper.ResetSvg(); // needed to reset so that PSNotFirst pagelist justify flag gets used for BGE - yLocation = lastyLocation = 0; - retval = Rtf2Pdf.TextAt(cb, myparagraphStepTitle, leftMargin + adjStepTitlePos, yPageStart - yLocation, width, height, "", yBottomMargin); - } - float ttlRetval = retval; - float savTitleFillWidth = Rtf2Pdf.FillWidth; + string tocStepTitle = hls.FormattedDisplayText; + tocStepTitle = ConvertSpecialChars(tocStepTitle, ii.ActiveFormat.PlantFormat.FormatData); // B2019-172 process symbol characters + rtfText = GetRtfToC(tocStepTitle, tOfC); + Paragraph myparagraphStepTitle = vlnPrintObject.RtfToParagraph(rtfText); + width = stepPagePos - adjStepTitlePos - ((tOfC.TofCPageNumAlign.ToUpper() == "RIGHT") ? 18 : 6);// B2021-109 proper adjustment of section title width - copied from leader dots lenth calcuation below + float savTitleWid = width; + // Print the step text + float retval = Rtf2Pdf.TextAt(cb, myparagraphStepTitle, leftMargin + ((tOfC.TofCSecNumPos == tOfC.TofCSecTitlePos && tmptxt.Equals(" ")) ? stepNumPos : adjStepTitlePos), yPageStart - yLocation, width, height, "", yBottomMargin); + if (retval == 0) // couldn't fit, flags need for a page break. + { + NewPage(); + _MyHelper.ResetSvg(); // needed to reset so that PSNotFirst pagelist justify flag gets used for BGE + yLocation = lastyLocation = 0; + retval = Rtf2Pdf.TextAt(cb, myparagraphStepTitle, leftMargin + adjStepTitlePos, yPageStart - yLocation, width, height, "", yBottomMargin); + } + float ttlRetval = retval; + float savTitleFillWidth = Rtf2Pdf.FillWidth; - // Now do the step number. Retval is the ylocation on page after the text is put out - retval = Rtf2Pdf.TextAt(cb, myparagraphStepNum, leftMargin + indentOffset, yPageStart - yLocation, numwidth * 1.3F, height, "", yBottomMargin); - if (retval != ttlRetval) yLocation += (retval - ttlRetval); + // Now do the step number. Retval is the ylocation on page after the text is put out + retval = Rtf2Pdf.TextAt(cb, myparagraphStepNum, leftMargin + indentOffset, yPageStart - yLocation, numwidth * 1.3F, height, "", yBottomMargin); + if (retval != ttlRetval) yLocation += (retval - ttlRetval); - // retval = the minimum (further down the page) between step number & text - accounts for multi line step - retval = Math.Min(retval, ttlRetval); - lastyLocation = retval; + // retval = the minimum (further down the page) between step number & text - accounts for multi line step + retval = Math.Min(retval, ttlRetval); + lastyLocation = retval; - // add a template for the page number: - // if the space character is not null & is not a space, the we've got to put out - // these between the section title & the page number - if (tOfC.TofCSpaceChar != null && tOfC.TofCSpaceChar != "" && tOfC.TofCSpaceChar != " ") - { - width = 0; - foreach (Chunk chkt in myparagraphStepTitle.Chunks) - width += chkt.GetWidthPoint(); + // add a template for the page number: + // if the space character is not null & is not a space, the we've got to put out + // these between the section title & the page number + if (tOfC.TofCSpaceChar != null && tOfC.TofCSpaceChar != "" && tOfC.TofCSpaceChar != " ") + { + width = 0; + foreach (Chunk chkt in myparagraphStepTitle.Chunks) + width += chkt.GetWidthPoint(); - // get height - if two lines high, need width of 2nd line for adding - // space characters - float heightTtl = vlnPrintObject.GetHeight(cb, myparagraphStepTitle, string.Empty, savTitleWid, false); - string spaceStr = ""; - float startSpace = 0; - // the '6's in the next few code lines & in the 'while' loop below allows the placement of the dots (or other space character) - // to be not too close to section title & page number. - if (heightTtl > vlnPrintObject.SixLinesPerInch) - { - // this title is 2 or more lines, find start of leader dots by determining length of text - // on 2nd line (the savTitleFillWidth is the widest line of the split title) - float secondLineWidth = width - savTitleFillWidth; - startSpace = leftMargin + adjStepTitlePos + secondLineWidth + 6; - } - else - startSpace = leftMargin + adjStepTitlePos + width + 6; - // If the page number is Right justified, need less space characters ('.') so that page number - // doesn't have the last space character overwriting the 1st digit: - int endJust = (tOfC.TofCPageNumAlign.ToUpper() == "RIGHT") ? 18 : 6; + // get height - if two lines high, need width of 2nd line for adding + // space characters + float heightTtl = vlnPrintObject.GetHeight(cb, myparagraphStepTitle, string.Empty, savTitleWid, false); + string spaceStr = ""; + float startSpace = 0; + // the '6's in the next few code lines & in the 'while' loop below allows the placement of the dots (or other space character) + // to be not too close to section title & page number. + if (heightTtl > vlnPrintObject.SixLinesPerInch) + { + // this title is 2 or more lines, find start of leader dots by determining length of text + // on 2nd line (the savTitleFillWidth is the widest line of the split title) + float secondLineWidth = width - savTitleFillWidth; + startSpace = leftMargin + adjStepTitlePos + secondLineWidth + 6; + } + else + startSpace = leftMargin + adjStepTitlePos + width + 6; + // If the page number is Right justified, need less space characters ('.') so that page number + // doesn't have the last space character overwriting the 1st digit: + int endJust = (tOfC.TofCPageNumAlign.ToUpper() == "RIGHT") ? 18 : 6; - float endSpace = leftMargin + stepPagePos - endJust; - float numSpace = endSpace - startSpace; - rtfText = GetRtfToC(tOfC.TofCSpaceChar, tOfC); - Paragraph tmpmyparagraph = vlnPrintObject.RtfToParagraph(rtfText); - float spacchrwid = 0; - foreach (Chunk chkt in tmpmyparagraph.Chunks) - spacchrwid += chkt.GetWidthPoint(); - while (numSpace > 6) - { - spaceStr = spaceStr + tOfC.TofCSpaceChar; - numSpace -= spacchrwid; - } + float endSpace = leftMargin + stepPagePos - endJust; + float numSpace = endSpace - startSpace; + rtfText = GetRtfToC(tOfC.TofCSpaceChar, tOfC); + Paragraph tmpmyparagraph = vlnPrintObject.RtfToParagraph(rtfText); + float spacchrwid = 0; + foreach (Chunk chkt in tmpmyparagraph.Chunks) + spacchrwid += chkt.GetWidthPoint(); + while (numSpace > 6) + { + spaceStr += tOfC.TofCSpaceChar; + numSpace -= spacchrwid; + } - rtfText = GetRtfToC(spaceStr, tOfC); // out the leader dots - Paragraph myparagraphs = vlnPrintObject.RtfToParagraph(rtfText); - retval = Rtf2Pdf.TextAt(cb, myparagraphs, startSpace, yPageStart - yLocation, endSpace - startSpace, height, "", yBottomMargin); - } - // if in the pre-table of content list, just put the page number out as text. - // otherwise, add a template _MyHelper.MyTOCPageCounts - string key = "TOC" + hls.ItemID.ToString(); - if (ii.IsAutoTOCSection || _MyHelper.MyTOCPageNums.ContainsKey(key)) - { - string pnum = _MyHelper.MyTOCPageNums.ContainsKey(key) ? _MyHelper.MyTOCPageNums[key].ToString() : (_MyHelper.CurrentTOCPageNumber + 1).ToString(); - rtfText = GetRtfToC(pnum, tOfC); - Paragraph myparagraphp = vlnPrintObject.RtfToParagraph(rtfText); - width = pnum.Length * 6; - retval = Rtf2Pdf.TextAt(cb, myparagraphp, leftMargin + stepPagePos, yPageStart - yLocation, width, height, "", yBottomMargin); - } - else - AddTemplateTOCPageCounts(tOfC, yLocation, yPageStartAdj, leftMargin, stepPagePos, height, key); + rtfText = GetRtfToC(spaceStr, tOfC); // out the leader dots + Paragraph myparagraphs = vlnPrintObject.RtfToParagraph(rtfText); + retval = Rtf2Pdf.TextAt(cb, myparagraphs, startSpace, yPageStart - yLocation, endSpace - startSpace, height, "", yBottomMargin); + } + // if in the pre-table of content list, just put the page number out as text. + // otherwise, add a template _MyHelper.MyTOCPageCounts + string key = $"TOC{hls.ItemID}"; + if (ii.IsAutoTOCSection || _MyHelper.MyTOCPageNums.ContainsKey(key)) + { + string pnum = _MyHelper.MyTOCPageNums.ContainsKey(key) ? _MyHelper.MyTOCPageNums[key].ToString() : (_MyHelper.CurrentTOCPageNumber + 1).ToString(); + rtfText = GetRtfToC(pnum, tOfC); + Paragraph myparagraphp = vlnPrintObject.RtfToParagraph(rtfText); + width = pnum.Length * 6; + retval = Rtf2Pdf.TextAt(cb, myparagraphp, leftMargin + stepPagePos, yPageStart - yLocation, width, height, "", yBottomMargin); + } + else + AddTemplateTOCPageCounts(tOfC, yLocation, yPageStartAdj, leftMargin, stepPagePos, height, key); - float spc = (float)(tOfC.TofCLineSpacing ?? 1); - yLocation += (spc * vlnPrintObject.SixLinesPerInch); - } + float spc = (float)(tOfC.TofCLineSpacing ?? 1); + yLocation += (spc * vlnPrintObject.SixLinesPerInch); + } - } + } return yLocation; } //B2019-172 This will add the RTF font commands around the symbol characters @@ -2080,165 +1832,11 @@ namespace Volian.Print.Library PdfTemplate tmp = _MyHelper.MyTOCPageCounts.AddToTemplateList(key, _MyHelper.MyPdfWriter, "{TOCPAGE}", tOfC.Font.WindowsFont, (tOfC.TofCPageNumAlign.ToUpper() == "RIGHT") ? Element.ALIGN_RIGHT : Element.ALIGN_LEFT, PrintOverride.TextColor); _MyHelper.MyPdfContentByte.AddTemplate(tmp, leftMargin + secPagePos, (yPageStartAdj - yLocation) - height / 2); } - - //private string GetRtfPlacekeeper(string txt, PlacekeeperData pkCData) - //{ - // StringBuilder _RtfSB = new StringBuilder(); - // Volian.Controls.Library.DisplayText pktxt = new Volian.Controls.Library.DisplayText(txt, pkCData.Font, false); - // System.Drawing.Font myFont = pktxt.TextFont.WindowsFont; - // _RtfSB.Append(vlnPrintObject.AddFontTable(myFont)); - // _RtfSB.Append(pktxt.StartText); - // _RtfSB.Append("}"); - // return _RtfSB.ToString(); - //} - //private float AddSectionToPK(SectionInfo pkSection, ItemInfo ii, PlacekeeperData pkData, PdfContentByte cb, float yPageStart, float yLocation) - //{ - // SectionConfig pkSC = pkSection.MyConfig as SectionConfig; - // if (pkSC.Section_Placekeeper != "Y") return yLocation; // automatic generation of Placekeeper turned off - // float xAdjNumber = -6 + 1.2F; - // float xAdjTitle = .8F + 1.2F; - // float xAdjTitleIndent = -6 + 2.4F; - // float yadj = 0.5F; // tweak to get 16 & 32 bit output to match. - - // float yPageStartAdj = yPageStart - yadj; - // float leftMargin = (float)pkSection.MyDocStyle.Layout.LeftMargin; - // //float secNumPos = (float)tOfC.TofCSecNumPos + xAdjNumber; - // //float secTitlePos = (float)tOfC.TofCSecTitlePos + xAdjTitle; - // //float secPagePos = (float)tOfC.TofCPageNumPos + xAdjNumber; - // //float height = tOfC.Font.WindowsFont.Size * 1.5F; - // if (ii.Sections != null) - // { - // foreach (SectionInfo mySection in ii.Sections) - // { - // SectionConfig sc = mySection.MyConfig as SectionConfig; - // if (mySection.ItemID != pkSection.ItemID && sc != null && sc.Section_Placekeeper == "Y") - // { - // // Look at each step in the section and build a Placekeeper for those steps that are marked - - // // need to do the section number, section title & page number. Page number - // // has to be put on at end after number of page is known, so use a Template. - // //string tmptxt = mySection.MyContent.Number == null || mySection.MyContent.Number == "" ? " " : mySection.MyContent.Number; - // //string rtfText = GetRtfPlacekeeper(tmptxt, pkData);//GetRtfToC(tmptxt, tOfC); - // //Paragraph myparagraphn = vlnPrintObject.RtfToParagraph(rtfText); - // float width = 0; - // //foreach (Chunk chkt in myparagraphn.Chunks) - // // width += chkt.GetWidthPoint(); - // float numwidth = width; - // float yBottomMargin = yPageStart - (float)pkSection.MyDocStyle.Layout.PageLength + (2 * vlnPrintObject.SixLinesPerInch); - // Rtf2Pdf.Offset = new PointF(0, 2.5F); - - // //// for indenting of subsections, count up tree. Only start indenting - // //// at third level, i.e. not indent on 1.0 and 1.1, but indent on 1.1.1: - // //int level = 0; - // //ItemInfo iilvl = mySection as ItemInfo; - // //while (!iilvl.IsProcedure) - // //{ - // // level++; - // // iilvl = iilvl.MyParent; - // //} - // //// check what level the plant wants the auto ToC indented: - // //int tofCNumLevels = pkSection.ActiveFormat.PlantFormat.FormatData.SectData.AccSectionData.TableOfContentsData.TofCNumLevels ?? 0; - // //if (tofCNumLevels > 0 && level > tofCNumLevels) return yLocation; - - // //level = level <= 2 ? 0 : level - 2; // no indenting until third level - // //float indentOffset = (level * (secTitlePos - secNumPos)); - - // // if the starting column of text would be in 'middle of' the number, just put it - // // a few spaces after the number. The '18' below represents 3 chars. - // //float adjSecTitlePos = secTitlePos + indentOffset + (level * 6); - // //if (secNumPos + numwidth + indentOffset > secTitlePos + indentOffset) - // // adjSecTitlePos = secNumPos + numwidth + 18 - xAdjTitleIndent + indentOffset; - // //rtfText = GetRtfToC(mySection.MyContent.Text, tOfC); - // //Paragraph myparagrapht = vlnPrintObject.RtfToParagraph(rtfText); - // //width = secPagePos - adjSecTitlePos - 6; - // //float retval = Rtf2Pdf.TextAt(cb, myparagrapht, leftMargin + adjSecTitlePos, yPageStart - yLocation, width, height, "", yBottomMargin); - // //float ttlRetval = retval; - // //if (retval == 0) - // //{ - // // cb.PdfDocument.NewPage(); - // // //_MyLog.InfoFormat("NewPage 5 {0}", cb.PdfWriter.CurrentPageNumber); - // // yLocation = lastyLocation = 0; - // // retval = Rtf2Pdf.TextAt(cb, myparagrapht, leftMargin + adjSecTitlePos, yPageStart - yLocation, width, height, "", yBottomMargin); - // // ttlRetval = retval; - // //} - // //retval = Rtf2Pdf.TextAt(cb, myparagraphn, leftMargin + secNumPos + indentOffset, yPageStart - yLocation, width * 1.3F, height, "", yBottomMargin); - // //if (retval == 0) // do a newpage, it couldn't fit on current page. - // //{ - // // cb.PdfDocument.NewPage(); - // // //_MyLog.InfoFormat("NewPage 5 {0}", cb.PdfWriter.CurrentPageNumber); - // // yLocation = lastyLocation = 0; - // // retval = Rtf2Pdf.TextAt(cb, myparagraphn, leftMargin + secNumPos + indentOffset, yPageStart - yLocation, width * 1.3F, height, "", yBottomMargin); - // //} - // //retval = Math.Min(retval, ttlRetval); - // //float lSpace = (tOfC.TofCLineSpacing == 2) ? 2 * vlnPrintObject.SixLinesPerInch : vlnPrintObject.SixLinesPerInch; - // //if (lastyLocation != 0 && ((lastyLocation - retval) > lSpace)) - // // yLocation += (lastyLocation - retval - lSpace); - // //lastyLocation = retval; - - // //// check that the page number should be in the TOC (some BGE sections do not have the page number) - // //if (!((mySection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DontNumberInTOC) == E_DocStructStyle.DontNumberInTOC)) - // //{ - // // // add a template for the page number: - // // // if the space character is not null & is not a space, the we've got to put out - // // // these between the section title & the page number - // // if (tOfC.TofCSpaceChar != null && tOfC.TofCSpaceChar != "" && tOfC.TofCSpaceChar != " ") - // // { - // // width = 0; - // // foreach (Chunk chkt in myparagrapht.Chunks) - // // width += chkt.GetWidthPoint(); - // // float startSpace = leftMargin + adjSecTitlePos + width; - // // float endSpace = leftMargin + secPagePos; - // // float numSpace = endSpace - startSpace; - // // string spaceStr = ""; - // // rtfText = GetRtfToC(tOfC.TofCSpaceChar, tOfC); - // // Paragraph tmpmyparagraph = vlnPrintObject.RtfToParagraph(rtfText); - // // float spacchrwid = 0; - // // foreach (Chunk chkt in tmpmyparagraph.Chunks) - // // spacchrwid += chkt.GetWidthPoint(); - // // while (numSpace > 0) - // // { - // // spaceStr = spaceStr + tOfC.TofCSpaceChar; - // // numSpace -= spacchrwid; - // // } - // // rtfText = GetRtfToC(spaceStr, tOfC); - // // Paragraph myparagraphs = vlnPrintObject.RtfToParagraph(rtfText); - // // retval = Rtf2Pdf.TextAt(cb, myparagraphs, startSpace, yPageStart - yLocation, endSpace - startSpace, height, "", yBottomMargin); - // // } - // // // if in the pre-table of content list, just put the page number out as text. - // // // otherwise, add a template _MyHelper.MyTOCPageCounts - // // string key = "TOC" + mySection.ItemID.ToString(); - // // if (mySection.IsAutoTOCSection || _MyHelper.MyTOCPageNums.ContainsKey(key)) - // // { - // // string pnum = _MyHelper.MyTOCPageNums.ContainsKey(key) ? _MyHelper.MyTOCPageNums[key].ToString() : (_MyHelper.CurrentTOCPageNumber + 1).ToString(); - // // rtfText = GetRtfToC(pnum, tOfC); - // // Paragraph myparagraphp = vlnPrintObject.RtfToParagraph(rtfText); - // // width = pnum.Length * 6; - // // retval = Rtf2Pdf.TextAt(cb, myparagraphp, leftMargin + secPagePos, yPageStart - yLocation, width, height, "", yBottomMargin); - // // } - // // else - // // AddTemplateTOCPageCounts(tOfC, yLocation, yPageStartAdj, leftMargin, secPagePos, height, mySection); - // //} - - // yLocation += vlnPrintObject.SixLinesPerInch; - // } - // //yLocation = AddSectionToTOC(tocSection, mySection, tOfC, cb, yPageStart, yLocation); - // } - // } - // return yLocation; - //} - - //private void AddTemplatePKPageCounts(TableOfContentsData tOfC, float yLocation, float yPageStartAdj, float leftMargin, float secPagePos, float height, SectionInfo mySection) - //{ - // string key = "PK" + mySection.ItemID.ToString(); - // PdfTemplate tmp = _MyHelper.MyTOCPageCounts.AddToTemplateList(key, _MyHelper.MyPdfWriter, "{TOCPAGE}", tOfC.Font.WindowsFont, Element.ALIGN_LEFT, PrintOverride.TextColor); - // _MyHelper.MyPdfContentByte.AddTemplate(tmp, leftMargin + secPagePos, (yPageStartAdj - yLocation) - height / 2); - //} private static void PrintTextMessage(PdfContentByte cb, string message, PdfLayer textLayer, iTextSharp.text.Font font) { if (textLayer != null) cb.BeginLayer(textLayer); float fontSize = font.Size; ColumnText ct = new ColumnText(cb); - //iTextSharp.text.Font font = FontFactory.GetFont("Arial", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, fontSize,iTextSharp.text.Font.NORMAL, new iTextSharp.text.Color(PrintOverride.TextColor)); Chunk chk = new Chunk(message, font); float xCenter = cb.PdfDocument.PageSize.Width / 2; float yCenter = cb.PdfDocument.PageSize.Height / 2; // 1.8f; @@ -2252,12 +1850,10 @@ namespace Volian.Print.Library if (textLayer != null) cb.EndLayer(); } private float _NoBreakYOffset = 0; - private float _NoBreakYPageStart = 0; private void CreateStepPdf(SectionInfo section, PdfContentByte cb) { int profileDepth = ProfileTimer.Push(">>>> CreateStepPdf"); //PrintTimer pt = new PrintTimer(); - iTextSharp.text.pdf.PdfWriter writer = cb.PdfWriter; ItemInfo myItemInfo = section as ItemInfo; if (SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) { @@ -2293,6 +1889,7 @@ namespace Volian.Print.Library _MyHelper.ChangeBarDefinition = MyChangeBarDefinition; //pt.Description = "vlnParagrph"; vlnParagraph myParagraph = new vlnParagraph(null, cb, myItemInfo, (float)myItemInfo.MyDocStyle.Layout.LeftMargin, _NoBreakYOffset, 0, myItemInfo.ColumnMode, myItemInfo.ActiveFormat, null, null, 0, true, this); + //For Testing: //pt.Description = "After vlnParagrph"; //if (myParagraph.MyItemInfo.InList(15906)) //{ @@ -2337,16 +1934,15 @@ namespace Volian.Print.Library // i.e. no page break between them. if (section.IsStepSection && nxtItem.IsStepSection) { - SectionInfo si = nxtItem as SectionInfo; - // B2017-201 if si is null we need to get it via the ItemID - if (si == null) - si = SectionInfo.Get(nxtItem.ItemID); //ActiveSection as SectionInfo; - SectionConfig sc = si.SectionConfig; + // B2017-201 if si is null we need to get it via the ItemID + if (!(nxtItem is SectionInfo si)) + si = SectionInfo.Get(nxtItem.ItemID); //ActiveSection as SectionInfo; + SectionConfig sc = si.SectionConfig; try { if (sc != null) sp = sc.Section_Pagination; } - catch (Exception ex) + catch (Exception) { sp = SectionConfig.SectionPagination.Separate; } @@ -2361,9 +1957,8 @@ namespace Volian.Print.Library NewPage(true); // end of step section //_MyLog.InfoFormat("NewPage 6 {0}", cb.PdfWriter.CurrentPageNumber); _NoBreakYOffset = 0; - yPageStart = yTopMargin; - } - else + } + else { if (nxtItem != null && nxtItem.MyPrevious != null && nxtItem.ActiveFormat.PlantFormat.FormatData.SectData.SectionHeader.Level0Big) localYPageStart -= 12; @@ -2377,8 +1972,7 @@ namespace Volian.Print.Library _NoBreakYOffset = myParagraph.YBottomMost; float yOffset = localYPageStart - yTopMargin; _NoBreakYOffset -= yOffset; - yPageStart = localYPageStart; - Volian.Base.Library.DebugText.WriteLine("NOBREAK:{0},'{1}','{2}','{3}','{4}','{5}'", section.ItemID, tmplocal, yTopMargin, localYPageStart, _NoBreakYOffset, myParagraph.YBottomMost); + Volian.Base.Library.DebugText.WriteLine("NOBREAK:{0},'{1}','{2}','{3}','{4}','{5}'", section.ItemID, tmplocal, yTopMargin, localYPageStart, _NoBreakYOffset, myParagraph.YBottomMost); } OnStatusChanged("StepSection converted to PDF " + section.ShortPath, PromsPrinterStatusType.BuildStep); //pt.Description = "End"; @@ -2397,7 +1991,7 @@ namespace Volian.Print.Library iTextSharp.text.Rectangle pageSize = PDFPageSize.UsePaperSize(MyItem.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize); // C2020-002 paper size is now set in the format files PdfContentByte cb = OpenDoc(ref SupInfoPdfName, pageSize); if (cb == null) return; - VlnSvgPageHelper myPageHelper = new VlnSvgPageHelper(vlnParagraph.MyItemInfo as SectionInfo, this, null, 0, _prtSectID); + VlnSvgPageHelper myPageHelper = new VlnSvgPageHelper(vlnParagraph.MyItemInfo as SectionInfo, this, null, 0, PrtSectID); cb.PdfWriter.PageEvent = myPageHelper; myPageHelper.AllowAllWatermarks = AllowAllWatermarks; myPageHelper.MyPdfWriter = cb.PdfWriter; @@ -2461,7 +2055,7 @@ namespace Volian.Print.Library // Binary Search to find proper font size within .1 while (decrement > .1f) { - decrement = decrement / 2f; //Reduce the decrement by half + decrement /= 2f; //Reduce the decrement by half if (mpglen > pageLength) // If the measured length is too big newFontSize -= decrement;// Reduce the font size else @@ -2476,9 +2070,10 @@ namespace Volian.Print.Library newFontSize -= decrement;// Reduce the font size float scaler = newFontSize / fontSize;// Calculate the reduction ReduceSupInfoGroupFontSize(grp, scaler, cb);// apply the new font size - fontSize = newFontSize;// adjust the base font size - mpglen = MeasureSupInfoGroupLength(grp, cb, pageLength);// Measure the length of the group of supinfo paragraphs - } +#pragma warning disable IDE0059 // Unnecessary assignment of a value - set mpglen for Debugging + mpglen = MeasureSupInfoGroupLength(grp, cb, pageLength);// Measure the length of the group of supinfo paragraphs +#pragma warning restore IDE0059 // Unnecessary assignment of a value + } } } } @@ -2581,7 +2176,7 @@ namespace Volian.Print.Library { float x = cell.MyTable.ColLeft[cell.c1]; float w = cell.MyTable.ColLeft[cell.c2 + 1] - x; - float hBefore = scaler * pg.GetParagraphHeight(cb, cell.MyPara, "", w); + //For Debugging: float hBefore = scaler * pg.GetParagraphHeight(cb, cell.MyPara, "", w); foreach (Chunk chk in cell.MyPara.Chunks) chk.Font.Size = scaler * chk.Font.Size; float hAfter = 1.075F * pg.GetParagraphHeight(cb, cell.MyPara, "", w);// 1.075 is a magic number that worked for Ginna. Otherwise decenders overlapped the bottom line of the cell. @@ -2637,19 +2232,23 @@ namespace Volian.Print.Library foreach (Chunk chk in vlnParagraph.IParagraph.Chunks) chk.Font.Size = scaler * chk.Font.Size; } - /// - /// Measure the Length of the Group - /// - /// Group of SupInfo Paragraphs - /// pdfContentByte - /// Page Length - /// Length - private float MeasureSupInfoGroupLength(List grp, PdfContentByte cb, float pagelength) + /// + /// Measure the Length of the Group + /// + /// Group of SupInfo Paragraphs + /// pdfContentByte + /// Page Length + /// Length + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "pagelength kept for Debugging")] + private float MeasureSupInfoGroupLength(List grp, PdfContentByte cb, float pagelength) { _LastBottom = 0; _LastOffset = 12;// 24; // account for the Sup Info header (two lines) - float fontSize = grp[0].IParagraph.Leading; // current font size - // For each SupInfo Paragraph calculate length + // current font size + // For each SupInfo Paragraph calculate length + //For Debugging: + //float fontSize = grp[0].IParagraph.Leading; + foreach (vlnParagraph pg in grp) { MeasureSupInfoGroupLength(pg, cb);// Measure a SupInfo Paragraph and children @@ -2702,7 +2301,7 @@ namespace Volian.Print.Library #endregion //ShrinkSupInfoGroupAtATime - public void DoSupInfoPage(PdfContentByte cb, string str, PdfLayer textLayer, VlnSvgPageHelper myPageHelper, int itemid, bool insertBlankPages) + public void DoSupInfoPage(PdfContentByte cb, PdfLayer textLayer, VlnSvgPageHelper myPageHelper, int itemid) { // see if the ID is in the facing page pdf - if so, get the page: if (SupInfoPdfPage == null || SupInfoPdfPage.Count < 1) return; @@ -2713,16 +2312,16 @@ namespace Volian.Print.Library InsertBlankPage(cb); return; } - PdfImportedPage sipage = null; - try - { + + try + { string SupInfoPdfName = Volian.Base.Library.VlnSettings.TemporaryFolder + @"\SupInfo" + myPageHelper.MySection.ItemID.ToString() + @".pdf"; PdfReader pdfreader = new PdfReader(SupInfoPdfName); - sipage = cb.PdfWriter.GetImportedPage(pdfreader, getpage + 1); - // F2023-035: WCN - allow for change in left margin for supplemental information pages by - // setting a value in the DocStyle for the adjustment. When importing the vlnParagraph page - // use this adjustment (note that page list items are done in VlnSvgPageHelper) - float lmargadj = myPageHelper.MySection.MyDocStyle.SupInfoMargAdj == null ? 0 : (float)myPageHelper.MySection.MyDocStyle.SupInfoMargAdj; + PdfImportedPage sipage = cb.PdfWriter.GetImportedPage(pdfreader, getpage + 1); + // F2023-035: WCN - allow for change in left margin for supplemental information pages by + // setting a value in the DocStyle for the adjustment. When importing the vlnParagraph page + // use this adjustment (note that page list items are done in VlnSvgPageHelper) + float lmargadj = myPageHelper.MySection.MyDocStyle.SupInfoMargAdj == null ? 0 : (float)myPageHelper.MySection.MyDocStyle.SupInfoMargAdj; AddImportedPageToLayer(cb.PdfWriter.DirectContent, textLayer, sipage, lmargadj, 0); DoingFacingPage = true; myPageHelper.ResetSvg(); @@ -2736,7 +2335,8 @@ namespace Volian.Print.Library Console.WriteLine(ex); } } - public void DoFoldoutPage(PdfContentByte cb, string str, PdfLayer textLayer, VlnSvgPageHelper myPageHelper, int foldoutindx, bool insertBlankPages) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "str Kept For Debugging")] + public void DoFoldoutPage(PdfContentByte cb, string str, PdfLayer textLayer, VlnSvgPageHelper myPageHelper, int foldoutindx, bool insertBlankPages) { if (_MyFoldoutSection == null || _MyFoldoutSection.Count == 0) return; @@ -2806,25 +2406,11 @@ namespace Volian.Print.Library cb.SaveState(); cb.BeginLayer(layer); SvgWatermark wm = new SvgWatermark(cb, watermark, System.Drawing.Color.Blue, .15F); - //wm.SetSquareDotPattern(.7F); - //wm.SetTextPattern(8, 3); - //wm.SetTextPattern2(8); - //wm.SetHashPattern(1, 6); - //wm.SetDotPattern(5, 2); wm.Draw(); cb.EndLayer(); cb.RestoreState(); } stamper.Close(); - /* - cb.SaveState(); - if (_WatermarkLayer != null) cb.BeginLayer(_WatermarkLayer); - SvgWatermark myWatermark = new SvgWatermark(cb, Watermark, System.Drawing.Color.Blue, .15F); - myWatermark.SetSquareDotPattern(.7F); - myWatermark.Draw(); - if (_WatermarkLayer != null) cb.EndLayer(); - cb.RestoreState(); - */ return ms.ToArray(); } // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. @@ -2836,21 +2422,20 @@ namespace Volian.Print.Library foreach (int iid in RemoveManualPageBreaks) { ItemInfo ii = ItemInfo.Get(iid); - StepConfig sc = ii.MyConfig as StepConfig; - if (sc != null) - { - using (Item itm = Item.Get(iid)) - { - if (!HasManPagAnnot(ii, "Removed Manual Page Break")) VEPROMS.CSLA.Library.Annotation.MakeAnnotation(itm, AnnotationType.GetByNameOrCreate("Manual Pagination Issues"), null, "Removed Manual Page Break", null); - sc.Step_NewManualPagebreak = false; // reset the flag that was set in the config - if (sc.Step_SubStepPagebreak) sc.Step_SubStepPagebreak = false; // C2023-018: remove substep page break flags - itm.MyContent.Config = sc.ToString(); - itm.MyContent.DTS = DateTime.Now; - itm.MyContent.UserID = Volian.Base.Library.VlnSettings.UserID; - itm.MyContent.Save(); - } - } - } + if (ii.MyConfig is StepConfig sc) + { + using (Item itm = Item.Get(iid)) + { + if (!HasManPagAnnot(ii, "Removed Manual Page Break")) VEPROMS.CSLA.Library.Annotation.MakeAnnotation(itm, AnnotationType.GetByNameOrCreate("Manual Pagination Issues"), null, "Removed Manual Page Break", null); + sc.Step_NewManualPagebreak = false; // reset the flag that was set in the config + if (sc.Step_SubStepPagebreak) sc.Step_SubStepPagebreak = false; // C2023-018: remove substep page break flags + itm.MyContent.Config = sc.ToString(); + itm.MyContent.DTS = DateTime.Now; + itm.MyContent.UserID = Volian.Base.Library.VlnSettings.UserID; + itm.MyContent.Save(); + } + } + } } // If trailing newlines and/or spages were removed, save those if (RemoveTrailingHardReturnsAndSpaces != null && RemoveTrailingHardReturnsAndSpaces.Count > 0) @@ -2905,13 +2490,9 @@ namespace Volian.Print.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private Dictionary dicPage = new Dictionary(); private Dictionary dicSize = new Dictionary(); - private PromsPrinter _MyPromsPrinter; - public PromsPrinter MyPromsPrinter - { - get { return _MyPromsPrinter; } - set { _MyPromsPrinter = value; } - } - private SectionInfo _MySectionInfo; + + public PromsPrinter MyPromsPrinter { get; set; } + private SectionInfo _MySectionInfo; public SectionInfo MySectionInfo { get { return _MySectionInfo; } @@ -2920,54 +2501,19 @@ namespace Volian.Print.Library if (_MySectionInfo == null || value.ItemID != _MySectionInfo.ItemID) { _MySectionInfo = value; - //MyPdfFile = _MyPromsPrinter.BuildMSWordPDF(MySectionInfo); - //try - //{ - // MyReader = MyPdfFile != null ? new PdfReader(MyPdfFile) : null; - // string key = string.Empty; - // for (int i = 1; i <= MyReader.NumberOfPages; i++) - // { - // key = string.Format("{0}.{1}", MySectionInfo.ItemID, i); - // dicPage.Add(key, MyPromsPrinter.MyContentByte.PdfWriter.GetImportedPage(MyReader, i)); - // dicSize.Add(key, MyReader.GetPageSizeWithRotation(i)); - // } - //} - //catch (Exception ex) - //{ - // MyReader = null; - //} } } } - private string _MyPdfFile; - public string MyPdfFile - { - get { return _MyPdfFile; } - set { _MyPdfFile = value; } - } - private int _DocID; - public int DocID - { - get { return _DocID; } - set { _DocID = value; } - } - private PdfReader _MyReader; - public PdfReader MyReader - { - get { return _MyReader; } - set { _MyReader = value; } - } - public ReaderHelper(PromsPrinter pp) + + public string MyPdfFile { get; set; } + public int DocID { get; set; } + public PdfReader MyReader { get; set; } + public ReaderHelper(PromsPrinter pp) { MyPromsPrinter = pp; - //this.LoadTree(pp.MyItem); } - public PdfImportedPage GetPage(SectionInfo sectInfo, int pageNumber) - { - string key = string.Format("{0}.{1}", sectInfo.ItemID, pageNumber); - return dicPage[key]; - } - public iTextSharp.text.Rectangle GetSize(SectionInfo sectInfo, int pageNumber) + public PdfImportedPage GetPage(SectionInfo sectInfo, int pageNumber) => dicPage[string.Format("{0}.{1}", sectInfo.ItemID, pageNumber)]; + public iTextSharp.text.Rectangle GetSize(SectionInfo sectInfo, int pageNumber) { string key = string.Format("{0}.{1}", sectInfo.ItemID, pageNumber); if (dicSize.ContainsKey(key)) @@ -2983,7 +2529,7 @@ namespace Volian.Print.Library private void LoadSectionTree(ItemInfo ii) { if (ii.Sections == null) return; // B2021-067 crash on null reference - foreach (SectionInfo si in ii.Sections) + foreach (SectionInfo si in ii.Sections.OfType()) { if (MyPromsPrinter.PrtSectID == -1 || (MyPromsPrinter.PrtSectID > -1 && (ii.ItemID == MyPromsPrinter.PrtSectID || si.ItemID == MyPromsPrinter.PrtSectID))) { @@ -2993,7 +2539,7 @@ namespace Volian.Print.Library } else { - MyPdfFile = _MyPromsPrinter.BuildMSWordPDF(si); + MyPdfFile = MyPromsPrinter.BuildMSWordPDF(si); if (MyPdfFile != null) { try @@ -3002,7 +2548,7 @@ namespace Volian.Print.Library if (fi.Length == 0) // B2017-218 Handle invalid word sections { if (!PromsPrinter.BaselineTesting) //B2018-071 Output a message box unless baseline testing is being performed. - MessageBox.Show(si.DisplayNumber + " " + si.DisplayText + " is not valid", "Invalid Word Section", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + MessageBox.Show($"{si.DisplayNumber} {si.DisplayText} is not valid", "Invalid Word Section", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } MyReader = MyPdfFile != null ? new PdfReader(MyPdfFile) : null; @@ -3016,12 +2562,11 @@ namespace Volian.Print.Library if (!((si.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_WordContentLandscaped) == E_DocStructStyle.DSS_WordContentLandscaped) && rectgl.Height < rectgl.Width) rectgl = new iTextSharp.text.Rectangle(rectgl.Height, rectgl.Width); dicSize.Add(key, rectgl); - //dicSize.Add(key, MyReader.GetPageSizeWithRotation(i)); } } catch (Exception ex) { - if (_MyPromsPrinter.DocReplace == null) + if (MyPromsPrinter.DocReplace == null) MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error); _MyLog.Warn(string.Format("Error in LoadSectionTree [{0}],{1}.{2}", si.ItemID, si.DisplayNumber, si.DisplayText), ex); } @@ -3031,33 +2576,5 @@ namespace Volian.Print.Library } } } - //public class PrintTimer - //{ - // private DateTime _StartTime = DateTime.Now; - - // public DateTime StartTime - // { - // get { return _StartTime; } - // set { _StartTime = value; } - // } - // private string _Description = "Start"; - // public string Description - // { - // get { return _Description; } - // set - // { - // DateTime dtNext = DateTime.Now; - // //Console.WriteLine("{0},'{1}'", TimeSpan.FromTicks(dtNext.Ticks - LastTime.Ticks).TotalSeconds, Description); - // _Description = value; - // _LastTime = dtNext; - // } - // } - // private DateTime _LastTime = DateTime.Now; - // public DateTime LastTime - // { - // get { return _LastTime; } - // set { _LastTime = value; } - // } - //} } diff --git a/PROMS/Volian.Print.Library/Rtf2Pdf.cs b/PROMS/Volian.Print.Library/Rtf2Pdf.cs index 3f6985e5..8646727d 100644 --- a/PROMS/Volian.Print.Library/Rtf2Pdf.cs +++ b/PROMS/Volian.Print.Library/Rtf2Pdf.cs @@ -1,12 +1,7 @@ using System; -using System.Collections.Generic; -using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; -using iTextSharp.text.factories; using Itenso.Rtf; -using Itenso.Rtf.Parser; -using Itenso.Rtf.Interpreter; using Itenso.Rtf.Support; using System.IO; using VEPROMS.CSLA.Library; @@ -36,25 +31,15 @@ namespace Volian.Print.Library { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - private string _Rtf; + #endregion - public string Rtf - { - get { return _Rtf; } - set { _Rtf = value; } - } - private string _FileName; + public string Rtf { get; set; } - public string FileName + public string FileName { get; set; } + public Rtf2Pdf(string rtf, string fileName) { - get { return _FileName; } - set { _FileName = value; } - } - public Rtf2Pdf(string rtf, string fileName) - { - _Rtf = rtf; - _FileName = fileName; + Rtf = rtf; + FileName = fileName; } public void Process() { @@ -83,67 +68,31 @@ namespace Volian.Print.Library yTop = newYTop; } } - private static string _PaperSize = "LETTER"; // default paper size - public static string PaperSize // C2020-002 paper size is now set in the format files - { - get { return Rtf2Pdf._PaperSize; } - set { Rtf2Pdf._PaperSize = value; } - } - private Rectangle _PaperSizeRec = PageSize.LETTER; // default paper size - public Rectangle PaperSizeRec - { - get { return PDFPageSize.UsePaperSize(PaperSize); } - } - private static bool _PdfDebug = true; - public static bool PdfDebug - { - get { return Rtf2Pdf._PdfDebug; } - set { Rtf2Pdf._PdfDebug = value; } - } - private static System.Drawing.PointF _Offset = new System.Drawing.PointF(0, 0); + + public static string PaperSize // C2020-002 paper size is now set in the format files + { get; set; } = "LETTER"; + public Rectangle PaperSizeRec => PDFPageSize.UsePaperSize(PaperSize); // default paper size = PageSize.LETTER + + public static bool PdfDebug { get; set; } = true; + private static System.Drawing.PointF _Offset = new System.Drawing.PointF(0, 0); public static System.Drawing.PointF Offset { - get { return Rtf2Pdf._Offset; } - set { Rtf2Pdf._Offset = value; } + get { return _Offset; } + set { _Offset = value; } } - public static float FillWidth = 0; // max text width (used in autoToc code) - private static int _TextAtCounter = 0; - public static int TextAtCounter + public static float FillWidth = 0; // max text width (used in autoToc code) + + public static int TextAtCounter { get; set; } = 0; + private static int NextTextAtCounter => ++TextAtCounter; + public class VlnSplitCharacter : ISplitCharacter { - get { return Rtf2Pdf._TextAtCounter; } - set { Rtf2Pdf._TextAtCounter = value; } - } - private static int NextTextAtCounter - { - get - { - int retval = ++TextAtCounter; - //if (InList(retval, 17)) Console.WriteLine("TextAt {0}", retval); - return retval; - } - } - public class VlnSplitCharacter : ISplitCharacter - { - public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) - { - return (cc[current] == ' '); - } - public bool IsSplitCharacter(char c) - { - return (c == ' '); - } - } - private static TableScrunching _AllowTableScrunching = TableScrunching.AllPhases; // RHM20150507 Table Scrunch - public static TableScrunching AllowTableScrunching - { - get { return Rtf2Pdf._AllowTableScrunching; } - set { Rtf2Pdf._AllowTableScrunching = value; } - } - public static bool GetTableScrunchingStatus(TableScrunching val) - { - return (val & _AllowTableScrunching) == val; - } - public static VlnSplitCharacter mySplitter = new VlnSplitCharacter(); + public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) => (cc[current] == ' '); + public bool IsSplitCharacter(char c) => (c == ' '); + } + + public static TableScrunching AllowTableScrunching { get; set; } = TableScrunching.AllPhases; + public static bool GetTableScrunchingStatus(TableScrunching val) => (val & AllowTableScrunching) == val; + public static VlnSplitCharacter mySplitter = new VlnSplitCharacter(); public static string ChunkTextAttributesInfo(Chunk chk1) // C2018-004 create meta file for baseline compares { string rtnval = "Atrbs:"; @@ -180,11 +129,8 @@ namespace Volian.Print.Library return rtnval; } public static int _lastPageNum = 0; // C2018-004 create meta file for baseline compares - public static float TextAt(PdfContentByte cb, Paragraph iParagraph, float x, float y, float width, float height, string debugText, float yBottomMargin) - { - return TextAt(cb, iParagraph, x, y, width, height, debugText, yBottomMargin, null); - } - public static float TextAt(PdfContentByte cb, Paragraph iParagraph, float x, float y, float width, float height, string debugText, float yBottomMargin, int? itmID) + public static float TextAt(PdfContentByte cb, Paragraph iParagraph, float x, float y, float width, float height, string debugText, float yBottomMargin) => TextAt(cb, iParagraph, x, y, width, height, debugText, yBottomMargin, null); + public static float TextAt(PdfContentByte cb, Paragraph iParagraph, float x, float y, float width, float height, string debugText, float yBottomMargin, int? itmID) { if (cb.PdfDocument.PageNumber != _lastPageNum) // C2018-004 create meta file for baseline compares { @@ -192,7 +138,7 @@ namespace Volian.Print.Library _lastPageNum = cb.PdfDocument.PageNumber; } VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; + PdfLayer textLayer = _MyPageHelper?.TextLayer; float left = x + Offset.X; float top = y + Offset.Y; // B2020-059 - Barakah 1T4-OP-EOP-AC-0001 Instructions and Contingency Actions section step 6 last table in RNO is compressed - cause first bullet substep in AER to print on top HLS text @@ -224,8 +170,6 @@ namespace Volian.Print.Library chk.Attributes.Add("NoSplit", false); } } - float right = left + width; - float bottom = top - height; ColumnText myColumnText = new ColumnText(cb); myColumnText.SetSimpleColumn(left, top, left + width, yBottomMargin); myColumnText.AddElement(iParagraph); @@ -259,22 +203,22 @@ namespace Volian.Print.Library } return myColumnText.YLine; } + //For Debugging: private static bool InList(int value, params int [] examples) { foreach (int ex in examples) if (ex == value) return true; return false; } - public static float FigureAt(PdfContentByte cb, iTextSharp.text.Image image, float x, float y, float width, float height, string debugText, float yBottommargin, bool hasBorder, int itmID, float sixLinesPerInch) + public static float FigureAt(PdfContentByte cb, iTextSharp.text.Image image, float x, float y, float width, float height, string debugText, bool hasBorder, int itmID, float sixLinesPerInch) { if (cb.PdfDocument.PageNumber != _lastPageNum) // C2018-004 create meta file for baseline compares { Volian.Base.Library.BaselineMetaFile.WriteLine("Page Change from {0} to {1}", _lastPageNum, cb.PdfDocument.PageNumber); _lastPageNum = cb.PdfDocument.PageNumber; } - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; - float left = x + Offset.X; + PdfLayer textLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.TextLayer; + float left = x + Offset.X; float top = y + Offset.Y + sixLinesPerInch; float bottom = top - height; image.ScaleAbsoluteWidth(width); @@ -309,21 +253,16 @@ namespace Volian.Print.Library return bottom; } - private static float _GridTopAdjust = -10; - public static float GridTopAdjust - { - get { return _GridTopAdjust; } - set { _GridTopAdjust = value; } - } - public static float GridAt(PdfContentByte cb, vlnTable myGrid, float x, float y, float width, float height, string debugText, float yBottomMargin, bool hasBorder) + + public static float GridTopAdjust { get; set; } = -10; + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "debugText Kept For Debugging")] + public static float GridAt(PdfContentByte cb, vlnTable myGrid, float x, float y, float width, float height, string debugText, float yBottomMargin, bool hasBorder) { if (cb.PdfDocument.PageNumber != _lastPageNum) // C2018-004 create meta file for baseline compares { Volian.Base.Library.BaselineMetaFile.WriteLine("Page Change from {0} to {1}", _lastPageNum, cb.PdfDocument.PageNumber); _lastPageNum = cb.PdfDocument.PageNumber; } - //VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; // RHM20150507 Table Scrunch - //PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; // RHM20150507 Table Scrunch float left = x + Offset.X; float top = y + Offset.Y; float right = left + width; @@ -331,7 +270,6 @@ namespace Volian.Print.Library int paperSizePoints = PDFPageSize.PaperSizePoints(myGrid.MyFlexGrid.MyDVI.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize); // C2020-002 paper size is now set in the format files ColumnText myColumnText = new ColumnText(cb); myColumnText.SetSimpleColumn(left, top, left + width, yBottomMargin); - //if (textLayer != null) cb.BeginLayer(textLayer); // RHM20150507 Table Scrunch // C2018-004 create meta file for baseline compares if (top + GridTopAdjust > paperSizePoints) // B2019-110 Table continued on the next page - off the top of page { @@ -340,14 +278,12 @@ namespace Volian.Print.Library } Volian.Base.Library.BaselineMetaFile.WriteLine("GD left={0} top={1} right={2} bottom={3} Mygrid.ItmID={4}", left, top + GridTopAdjust, right, bottom, myGrid.ItemID); myGrid.ToPdf(myColumnText, left, top + GridTopAdjust); - //if (textLayer != null) cb.EndLayer(); // RHM20150507 Table Scrunch return bottom; } internal static void DrawPdfDebug(PdfContentByte cb, float left, float top, float right, float bottom, string debugText, float yDescent) { - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer debugLayer = _MyPageHelper == null ? null : _MyPageHelper.DebugLayer; - if (debugLayer == null) return; + PdfLayer debugLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.DebugLayer; + if (debugLayer == null) return; System.Drawing.Color sysColor = PrintOverride.OverrideDebugColor(System.Drawing.Color.Gray); cb.SaveState(); cb.BeginLayer(debugLayer); @@ -374,19 +310,17 @@ namespace Volian.Print.Library cb.RestoreState(); } - internal static float RtfRawAt(PdfContentByte cb, System.Drawing.Image image, float XOffset, float yLocation, float Width, float Height, string debug, float yBottomMargin, bool hasBorder) + internal static float RtfRawAt(PdfContentByte cb, System.Drawing.Image image, float XOffset, float yLocation, float Width, float Height, string debug, bool hasBorder) { - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; - float left = XOffset + Offset.X; + PdfLayer textLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.TextLayer; + float left = XOffset + Offset.X; float top = yLocation + Offset.Y; float bottom = top - Height; float scale = .6f; - iTextSharp.text.Image it_image=null; - try - { - it_image = iTextSharp.text.Image.GetInstance(image,iTextSharp.text.Color.WHITE); - float itxtWid = scale * Width * 300 / 72; + try + { + iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(image, iTextSharp.text.Color.WHITE); + float itxtWid = scale * Width * 300 / 72; float itxtHt = scale * Height * 300 / 72; it_image.ScaleAbsoluteWidth(scale * Width); it_image.ScaleAbsoluteHeight(scale * Height); diff --git a/PROMS/Volian.Print.Library/Rtf2iTextSharp.cs b/PROMS/Volian.Print.Library/Rtf2iTextSharp.cs index 3b46a8c3..f89db169 100644 --- a/PROMS/Volian.Print.Library/Rtf2iTextSharp.cs +++ b/PROMS/Volian.Print.Library/Rtf2iTextSharp.cs @@ -1,18 +1,13 @@ using System; -using System.Collections.Generic; using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; -using iTextSharp.text.factories; using Itenso.Rtf; -using Itenso.Rtf.Parser; -using Itenso.Rtf.Interpreter; -//using Itenso.Rtf.Model; using Itenso.Rtf.Support; -using Microsoft.Win32; using Volian.Base.Library; using System.Text.RegularExpressions; using VEPROMS.CSLA.Library; +using System.Linq; namespace Volian.Print.Library { @@ -21,17 +16,13 @@ namespace Volian.Print.Library public static bool CompressSub = false; public static bool CompressSuper = false; public static bool CompressPropSubSup = false; - private static System.Drawing.Color _TextColor = System.Drawing.Color.Empty; - public static System.Drawing.Color TextColor + + public static System.Drawing.Color TextColor { get; set; } = System.Drawing.Color.Empty; + public static System.Drawing.Color OverrideTextColor(System.Drawing.Color color) { - get { return _TextColor; } - set { _TextColor = value; } - } - public static System.Drawing.Color OverrideTextColor(System.Drawing.Color color) - { - if (_TextColor == System.Drawing.Color.Empty) + if (TextColor == System.Drawing.Color.Empty) return color; - return _TextColor; + return TextColor; } private static System.Drawing.Color _SvgColor = System.Drawing.Color.Empty; public static System.Drawing.Color SvgColor @@ -45,29 +36,21 @@ namespace Volian.Print.Library return color; return _SvgColor; } - private static System.Drawing.Color _BoxColor = System.Drawing.Color.Empty; - public static System.Drawing.Color BoxColor + + public static System.Drawing.Color BoxColor { get; set; } = System.Drawing.Color.Empty; + public static System.Drawing.Color OverrideBoxColor(System.Drawing.Color color) { - get { return _BoxColor; } - set { _BoxColor = value; } - } - public static System.Drawing.Color OverrideBoxColor(System.Drawing.Color color) - { - if (_BoxColor == System.Drawing.Color.Empty) + if (BoxColor == System.Drawing.Color.Empty) return color; - return _BoxColor; + return BoxColor; } - private static System.Drawing.Color _ChangeBarColor = System.Drawing.Color.Empty; - public static System.Drawing.Color ChangeBarColor + + public static System.Drawing.Color ChangeBarColor { get; set; } = System.Drawing.Color.Empty; + public static System.Drawing.Color OverrideChangeBarColor(System.Drawing.Color color) { - get { return _ChangeBarColor; } - set { _ChangeBarColor = value; } - } - public static System.Drawing.Color OverrideChangeBarColor(System.Drawing.Color color) - { - if (_ChangeBarColor == System.Drawing.Color.Empty) + if (ChangeBarColor == System.Drawing.Color.Empty) return color; - return _ChangeBarColor; + return ChangeBarColor; } private static System.Drawing.Color _DebugColor = System.Drawing.Color.Empty; public static System.Drawing.Color DebugColor @@ -93,43 +76,17 @@ namespace Volian.Print.Library public class Rtf2iTextSharp : RtfVisualVisitorBase { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private bool _HasIndent = false; - public bool HasIndent - { - get { return _HasIndent; } - set { _HasIndent = value; } - } - private IRtfDocument _RtfDoc; - private Paragraph _MyParagraph = new Paragraph(); + + public bool HasIndent { get; set; } = false; + private readonly IRtfDocument _RtfDoc; + private readonly Paragraph _MyParagraph = new Paragraph(); private iTextSharp.text.Font _MyFont; - // Allow for definition of a default font: if the font is not proportional, this gets set. - // It is needed to set the chunk's font if the first character of a cell is a hardspace (or various - // other special cases (see its use below). Without this, pdfs were using the Helvetica font, - // which is a default itextsharp font (this was causing a problem for HLP, their pdfs could not - // contain a Helvetica font when putting them in their production environment). - private iTextSharp.text.Font _DefaultFont; - public iTextSharp.text.Font DefaultFont - { - get { return _DefaultFont; } - set { _DefaultFont = value; } - } - private string _MyDebugID = null; - public string MyDebugID - { - get { return _MyDebugID; } - set { _MyDebugID = value; } - } - public bool DoPdfLinks = false; - // public Rtf2iTextSharp(IRtfDocument rtfDoc, Document doc, PdfWriter writer) - public Rtf2iTextSharp(IRtfDocument rtfDoc) - { - if (rtfDoc == null) - throw new ArgumentNullException("rtfDoc"); - - _RtfDoc = rtfDoc; - } - public Paragraph Convert() + public iTextSharp.text.Font DefaultFont { get; set; } + public string MyDebugID { get; set; } = null; + public bool DoPdfLinks = false; + public Rtf2iTextSharp(IRtfDocument rtfDoc) => _RtfDoc = rtfDoc ?? throw new ArgumentNullException("rtfDoc"); + public Paragraph Convert() { int profileDepth = ProfileTimer.Push(">>>> Rtf2ITextSharp.Convert"); _MyParagraph.Clear(); @@ -138,7 +95,6 @@ namespace Volian.Print.Library { visual.Visit(this); } - //_MyParagraph.SetLeading(0, 1); ProfileTimer.Pop(profileDepth); return _MyParagraph; } @@ -177,6 +133,7 @@ namespace Volian.Print.Library _lastWasLineBreak = 0; // B2017-191 reset hard return count break; } + //For Debugging: //_MyParagraph.Add(string.Format("<{0}>", visualBreak.BreakKind.ToString())); } private void AddChunk(string str, iTextSharp.text.Font font) @@ -188,8 +145,9 @@ namespace Volian.Print.Library } protected override void DoVisitSpecial(IRtfVisualSpecialChar visualSpecialChar) { - //_MyParagraph.Add(string.Format("", visualSpecialChar.CharKind.ToString())); - iTextSharp.text.Font activeFont = _MyFont ?? DefaultFont; + //For Debugging: + //_MyParagraph.Add(string.Format("", visualSpecialChar.CharKind.ToString())); + iTextSharp.text.Font activeFont = _MyFont ?? DefaultFont; switch (visualSpecialChar.CharKind) { case RtfVisualSpecialCharKind.Bullet: @@ -248,23 +206,15 @@ namespace Volian.Print.Library if (c <= '\x7F') return false; return true; } + + //For Debugging: private bool ContainsAnySymbols(string p) { foreach (char c in p) if (c > '\x7F' && c != '\xA0' && c != '\xB0') return true; return false; } -// The funcction below was used for the first few lines of DoVisitText which have been commented-out - //private object FixText(string str) - //{ - // StringBuilder sb = new StringBuilder(); - // foreach (char c in str) - // if (c < ' ' || c > '\xFF') - // sb.Append(string.Format("[{0}]", (int)c)); - // else - // sb.Append(c); - // return sb.ToString(); - //} + // ParseLink & GetDefaultItemInfo (which used to be in vlnParagraph) support coding that was added to DoVisitText for // doing pdflink for each transition/ro in a step, see bug B2019-052 private RoUsageInfo _Roui = null; @@ -278,8 +228,9 @@ namespace Volian.Print.Library if (_LinkInfoText.Contains(@"\v")) throw new Exception("LinkText.ParseLink found RTF token"); Match m = Regex.Match(_LinkInfoText, @"[#]Link:([A-Za-z]*):(.*)"); - string _MyValue = m.Groups[1].Value; - string _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[1].Value) { case "ReferencedObject": @@ -319,7 +270,7 @@ namespace Volian.Print.Library if (myItemInfo.IsProcedure && myItemInfo.Sections != null) { SectionInfo siProcedureSteps = null; - foreach (SectionInfo si in myItemInfo.Sections) + foreach (SectionInfo si in myItemInfo.Sections.OfType()) { if (si.IsDefaultSection) { @@ -347,7 +298,7 @@ namespace Volian.Print.Library private static int chkStart = -1; protected override void DoVisitText(IRtfVisualText visualText) { - //Code to find text (non-symbol) being output with a symbol font + //Debugging Code to find text (non-symbol) being output with a symbol font //if(visualText.Format.Font.Name=="VESymbFix" && visualText.Text.Length > 1) //{ // string s = visualText.Text; @@ -375,44 +326,43 @@ namespace Volian.Print.Library { try { - Chunk chk = _MyParagraph.Chunks[i] as Chunk; - if (chk != null) - { - if (_linkType == 2 && _Ti != null) // transition - { - ItemInfo tiDefault = GetDefaultItemInfo(_Ti.MyItemToID); - ItemInfo from = _Ti.MyContent.ContentItems[0]; - if (_Ti.MyItemToID.MyProcedure.ItemID == from.MyProcedure.ItemID && - !((from.ActiveSection.MyConfig as SectionConfig).Section_IsFoldout == "Y")) //C2019-042 Section_IsFoldout checks Section Number, Section Title, and use of check box - { // Local Go To - // B2020-028, 029 and 030: all were related to print of supplemental information when printing with - // pdf links. The pdf links in the temporary supinfo pdf caused a crash on save of file because they didn't exist. - if (_Ti.MyItemToID.MyContent.Type > 9999 && !from.IsInSupInfo) // internal to this file - { - chk.SetLocalGoto(string.Format("ItemID={0}", tiDefault.ItemID)); - chk.SetBackground(Color.CYAN); - chk.SetBackground(new Color(System.Drawing.Color.LightCyan)); - } - } - else if (_Ti != null && !from.IsInSupInfo) // Remote Go To. Added SupInfo check for B2020 bugs (see above) - { - // C2024-009 add PDF file prefix and suffix if available to the PDF file name in the transition reference. - DocVersionConfig dvc = _Ti.MyItemToID.MyProcedure.MyDocVersion.DocVersionConfig; - string remotePDFName = dvc.Print_PDFFilePrefix + _Ti.MyItemToID.MyProcedure.DisplayNumber.Replace("/", "_") + dvc.Print_PDFFileSuffix + ".pdf"; - chk.SetRemoteGoto(remotePDFName, string.Format("ItemID={0}", tiDefault.ItemID)); - chk.SetBackground(new Color(System.Drawing.Color.PeachPuff)); - } - } - else if (_linkType == 1 && _Roui != null && !_Roui.MyContent.ContentItems[0].IsInSupInfo) // referenced object. Added SupInfo check for B2020 bugs (see above) - { - if (_Roui.ROID.Substring(0, 4) != "FFFF") - { - chk.SetRemoteGoto("completeroreport.pdf", string.Format("ROID={0}", _Roui.ROID.Substring(0, 12).ToUpper())); - chk.SetBackground(new Color(System.Drawing.Color.LightGreen)); - } - } - } - } + if (_MyParagraph.Chunks[i] is Chunk chk) + { + if (_linkType == 2 && _Ti != null) // transition + { + ItemInfo tiDefault = GetDefaultItemInfo(_Ti.MyItemToID); + ItemInfo from = _Ti.MyContent.ContentItems[0]; + if (_Ti.MyItemToID.MyProcedure.ItemID == from.MyProcedure.ItemID && + !((from.ActiveSection.MyConfig as SectionConfig).Section_IsFoldout == "Y")) //C2019-042 Section_IsFoldout checks Section Number, Section Title, and use of check box + { // Local Go To + // B2020-028, 029 and 030: all were related to print of supplemental information when printing with + // pdf links. The pdf links in the temporary supinfo pdf caused a crash on save of file because they didn't exist. + if (_Ti.MyItemToID.MyContent.Type > 9999 && !from.IsInSupInfo) // internal to this file + { + chk.SetLocalGoto(string.Format("ItemID={0}", tiDefault.ItemID)); + chk.SetBackground(Color.CYAN); + chk.SetBackground(new Color(System.Drawing.Color.LightCyan)); + } + } + else if (_Ti != null && !from.IsInSupInfo) // Remote Go To. Added SupInfo check for B2020 bugs (see above) + { + // C2024-009 add PDF file prefix and suffix if available to the PDF file name in the transition reference. + DocVersionConfig dvc = _Ti.MyItemToID.MyProcedure.MyDocVersion.DocVersionConfig; + string remotePDFName = $"{dvc.Print_PDFFilePrefix}{_Ti.MyItemToID.MyProcedure.DisplayNumber.Replace("/", "_")}{dvc.Print_PDFFileSuffix}.pdf"; + chk.SetRemoteGoto(remotePDFName, string.Format("ItemID={0}", tiDefault.ItemID)); + chk.SetBackground(new Color(System.Drawing.Color.PeachPuff)); + } + } + else if (_linkType == 1 && _Roui != null && !_Roui.MyContent.ContentItems[0].IsInSupInfo) // referenced object. Added SupInfo check for B2020 bugs (see above) + { + if (_Roui.ROID.Substring(0, 4) != "FFFF") + { + chk.SetRemoteGoto("completeroreport.pdf", string.Format("ROID={0}", _Roui.ROID.Substring(0, 12).ToUpper())); + chk.SetBackground(new Color(System.Drawing.Color.LightGreen)); + } + } + } + } catch (Exception ex) { _MyLog.ErrorFormat("Error creating pdf links {0}", ex.Message); @@ -630,6 +580,7 @@ namespace Volian.Print.Library } } + //For Debugging: private string ShowSpecialCharacters(string p) { StringBuilder sb = new StringBuilder(); @@ -642,31 +593,23 @@ namespace Volian.Print.Library sb.Append(c); } return sb.ToString(); - }// DoVisitText + } // ---------------------------------------------------------------------- protected override void DoVisitImage(IRtfVisualImage visualImage) - { - //_MyParagraph.Add(new Chunk("")); - //DateTime dt1 = DateTime.Now; - //System.Drawing.Image img2 = visualImage.ImageForDrawing; - //Console.WriteLine("1 Time Span {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - dt1.Ticks).TotalMilliseconds); - //img2.Save(@"c:\datacvrt\x.png"); - System.IO.MemoryStream ms = new System.IO.MemoryStream(); + { - //Console.WriteLine("2 Time Span {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - dt1.Ticks).TotalMilliseconds); - //Console.WriteLine("Size {0}", visualImage.ImageForDrawing.Size); - visualImage.ImageForDrawing.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); - //Console.WriteLine("3 Time Span {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - dt1.Ticks).TotalMilliseconds); - ms.Seek(0, System.IO.SeekOrigin.Begin); - //Console.WriteLine("4 Time Span {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - dt1.Ticks).TotalMilliseconds); - iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms); - //Console.WriteLine("5 Time Span {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - dt1.Ticks).TotalMilliseconds); - _MyParagraph.Add(img); - //Console.WriteLine("6 Time Span {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - dt1.Ticks).TotalMilliseconds); - _lastWasLineBreak = 0; // B2017-191 reset hard return count - } // DoVisitImage + using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) + { + visualImage.ImageForDrawing.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); + ms.Seek(0, System.IO.SeekOrigin.Begin); + iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms); + _MyParagraph.Add(img); + } - } + _lastWasLineBreak = 0; // B2017-191 reset hard return count + } + + } } diff --git a/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs b/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs index a6cc1382..d10c9202 100644 --- a/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs +++ b/PROMS/Volian.Print.Library/VlnSvgPageHelper.cs @@ -1,55 +1,31 @@ using System; using System.Collections.Generic; -using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; -using iTextSharp.text.factories; using Volian.Svg.Library; using System.Text.RegularExpressions; using System.Xml; using VEPROMS.CSLA.Library; using Volian.Base.Library; +using System.Linq; namespace Volian.Print.Library { public partial class VlnSvgPageHelper:SvgPageHelper { - private float _TableAdjustment = 0;// RHM20150525 - Table Scrunch - public float TableAdjustment - { - get { return _TableAdjustment; } - set { _TableAdjustment = value; } - } - private vlnParagraph _AdjustedTable; // B2020-059 - save info of table that was compressed (set in vlnParagraph.cs DrawGrid() and used in RTF2PDF.cs TextAt()) - public vlnParagraph AdjustedTable - { - get { return _AdjustedTable; } - set { _AdjustedTable = value; } - } - private float _AdjustedTableYtop; - public float AdjustedTableYtop // B2020-059 - save the Ytop of the compressed table (set in vlnParagraph.cs DrawGrid() and used in RTF2PDF.cs TextAt()) - { - get { return _AdjustedTableYtop; } - set { _AdjustedTableYtop = value; } - } - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private pkParagraphs _MyPlacekeepers = new pkParagraphs(); - public pkParagraphs MyPlacekeepers - { - get { return _MyPlacekeepers; } - } - private pkParagraphs _MyContActSteps = new pkParagraphs(); - public pkParagraphs MyContActSteps - { - get { return _MyContActSteps; } - } - // F2022-024 Time Critical Action Step - private pkParagraphs _MyTimeCriticalActionSteps = new pkParagraphs(); - public pkParagraphs MyTimeCriticalActionSteps - { - get { return _MyTimeCriticalActionSteps; } - } - private float? _BottomContent = null;// RHM20150525 - Table Scrunch + public float TableAdjustment { get; set; } = 0; + public vlnParagraph AdjustedTable { get; set; } + public float AdjustedTableYtop // B2020-059 - save the Ytop of the compressed table (set in vlnParagraph.cs DrawGrid() and used in RTF2PDF.cs TextAt()) + { get; set; } + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private readonly pkParagraphs _MyPlacekeepers = new pkParagraphs(); + public pkParagraphs MyPlacekeepers => _MyPlacekeepers; + private readonly pkParagraphs _MyContActSteps = new pkParagraphs(); + public pkParagraphs MyContActSteps => _MyContActSteps; + // F2022-024 Time Critical Action Step + private readonly pkParagraphs _MyTimeCriticalActionSteps = new pkParagraphs(); + public pkParagraphs MyTimeCriticalActionSteps => _MyTimeCriticalActionSteps; + private float? _BottomContent = null;// RHM20150525 - Table Scrunch public float? BottomContent { get @@ -62,127 +38,31 @@ namespace Volian.Print.Library _BottomContent = value; } } - private PageBookmarks _PageBookmarks = new PageBookmarks(); - public PageBookmarks PageBookmarks - { - get { return _PageBookmarks; } - set { _PageBookmarks = value; } - } - private List _MyPdfOutlines = new List(); - public List MyPdfOutlines - { - get { return _MyPdfOutlines; } - } - private ChkListBoxesHelper _CheckListBoxes = null; - private ChkListBoxesHelper CheckListBoxes - { - get { return _CheckListBoxes; } - set { _CheckListBoxes = value; } - } - private vlnText _TopMessage; - public vlnText TopMessage - { - get { return _TopMessage; } - set { _TopMessage = value; } - } - private int _prtSectID = -1; - public int PrtSectID - { - get { return _prtSectID; } - set { _prtSectID = value; } - } - private List _TopMessageRs=new List(); // Added if there are 2 messages, in AER AND RNO (for BGE) - public List TopMessageRs - { - get { return _TopMessageRs; } - set { _TopMessageRs = value; } - } - private List _TopMessageSub1s=new List(); // BGE Alarms: in CONDITION/RESPONSE if break within substep - public List TopMessageSub1s - { - get { return _TopMessageSub1s; } - set { _TopMessageSub1s = value; } - } - private List _TopMessageSub2s=new List(); // BGE Alarms: in CONDITION/RESPONSE if break within substep - public List TopMessageSub2s - { - get { return _TopMessageSub2s; } - set { _TopMessageSub2s = value; } - } - private List _BottomMessage = new List(); // B2017-203) any continuous sections with end messages may have more than 1 message on a page - public List BottomMessage - { - get { return _BottomMessage; } - set { _BottomMessage = value; } - } - private vlnText _BottomMessageR; // Added if there are 2 messages, in AER AND RNO (for BGE) - public vlnText BottomMessageR - { - get { return _BottomMessageR; } - set { _BottomMessageR = value; } - } - private vlnText _BottomMessageA; // Added if there are 3 messages, at bottom AND in AER AND RNO (for BGEALARMS) - public vlnText BottomMessageA - { - get { return _BottomMessageA; } - set { _BottomMessageA = value; } - } - private Dictionary> _NotesToFootNotesHLS = new Dictionary>(); - public Dictionary> NotesToFootNotesHLS - { - get { return _NotesToFootNotesHLS; } - set { _NotesToFootNotesHLS = value; } - } - private List _NotesToFootNotes = new List(); - public List NotesToFootNotes - { - get { return _NotesToFootNotes; } - set { _NotesToFootNotes = value; } - } - private float _NotesToFootNotesYoffset = 0; - public float NotesToFootNotesYoffset - { - get { return _NotesToFootNotesYoffset; } - set { _NotesToFootNotesYoffset = value; } - } - Dictionary _MyParagraphs = new Dictionary(); - public Dictionary MyParagraphs - { - get { return _MyParagraphs; } - set { _MyParagraphs = value; } - } - float _YMultiplier = 1; - public float YMultiplier - { - get { return _YMultiplier; } - set { _YMultiplier = value; } - } - float _PhoneListHeight = 0; - public float PhoneListHeight - { - get { return _PhoneListHeight; } - set { _PhoneListHeight = value; } - } - private float _AlarmYoffStart = 0; - public float AlarmYoffStart - { - get { return _AlarmYoffStart; } - set { _AlarmYoffStart = value; } - } - private float _AlarmYoffEnd = 0; - public float AlarmYoffEnd - { - get { return _AlarmYoffEnd; } - set { _AlarmYoffEnd = value; } - } - private float _SectionSepLineYoffStart = 0; - public float SectionSepLineYoffStart - { - get { return _SectionSepLineYoffStart; } - set { _SectionSepLineYoffStart = value; } - } - private PdfWriter _MyPdfWriter; + public PageBookmarks PageBookmarks { get; set; } = new PageBookmarks(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List _MyPdfOutlines = new List(); + public List MyPdfOutlines => _MyPdfOutlines; + + public vlnText TopMessage { get; set; } + public int PrtSectID { get; set; } = -1; + public List TopMessageRs { get; set; } = new List(); + public List TopMessageSub1s { get; set; } = new List(); + public List TopMessageSub2s { get; set; } = new List(); + public List BottomMessage { get; set; } = new List(); + public vlnText BottomMessageR { get; set; } + public vlnText BottomMessageA { get; set; } + public Dictionary> NotesToFootNotesHLS { get; set; } = new Dictionary>(); + public List NotesToFootNotes { get; set; } = new List(); + + public float NotesToFootNotesYoffset { get; set; } = 0; + public Dictionary MyParagraphs { get; set; } = new Dictionary(); + public float YMultiplier { get; set; } = 1; + public float PhoneListHeight { get; set; } = 0; + public float AlarmYoffStart { get; set; } = 0; + public float AlarmYoffEnd { get; set; } = 0; + public float SectionSepLineYoffStart { get; set; } = 0; + private PdfWriter _MyPdfWriter; public PdfWriter MyPdfWriter { get { return _MyPdfWriter; } @@ -194,79 +74,34 @@ namespace Volian.Print.Library _MyPdfWriter = value; } } - private PdfContentByte _MyPdfContentByte; - public PdfContentByte MyPdfContentByte - { - get { return _MyPdfContentByte; } - set { _MyPdfContentByte = value; } - } - private int _FinalMessageSectionID; - public int FinalMessageSectionID - { - get { return _FinalMessageSectionID; } - set { _FinalMessageSectionID = value; } - } - private bool _DidFirstPageDocStyle = false; - public bool DidFirstPageDocStyle - { - get { return _DidFirstPageDocStyle; } - set { _DidFirstPageDocStyle = value; } - } - public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) + + public PdfContentByte MyPdfContentByte { get; set; } + public int FinalMessageSectionID { get; set; } + public bool DidFirstPageDocStyle { get; set; } = false; + public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document) { AddBookmarks(writer); MyPageCounts.DrawTemplates(); } - private bool _OnBlankPage = false; - public bool OnBlankPage // used while inserting a blank page when printing a procedure with duplex foldouts - { - get { return _OnBlankPage; } - set { _OnBlankPage = value; } - } - // when false, no page has been printed yet (for determining whether a blank page before print - // needs done if first section has foldouts) - private bool _PrintedAPage = false; - public bool PrintedAPage - { - get { return _PrintedAPage; } - set { _PrintedAPage = value; } - } - // the following two variables are used to handle the 'PSOnlyFirst' page list Justify flag. - // PSOnlyFirst signals that the pagelist token should only be processed for the first page of - // the section. It gets set when this token is processed, so that any remaining pages will - // not get the token. It's value is derived by taking the different the location of this token - // & the location of the previous token, so that this amount can be used to move the text up - // on the 'not first' pages of the section. It's used as an adjustment on the topmargin. - // This is used in FNP formats. - private int _sectLevelNumTtlDiff = 0; - private int _PrintedSectionPage = 0; - public int PrintedSectionPage - { - get { return _PrintedSectionPage; } - set { _PrintedSectionPage = value; } - } - private static int _CountInApplProcs; // B2021-127: BNPPalr - Auto set of serial # - public static int CountInApplProcs - { - get { return _CountInApplProcs; } - set { _CountInApplProcs = value; } - } - // C2025-033 Child (slave) being printed - private static int _PrintingChild = 0; - public static int PrintingChild - { - get { return _PrintingChild; } - set { _PrintingChild = value; } - } + public bool OnBlankPage // used while inserting a blank page when printing a procedure with duplex foldouts + { get; set; } = false; + public bool PrintedAPage { get; set; } = false; - //private bool _AddBlankPagesForDuplexPrinting = false; - //public bool AddBlankPagesForDuplexPrinting // Tells us if a the option to add a blank page is turn on (for procedures with duplex foldouts) - //{ - // get { return _AddBlankPagesForDuplexPrinting; } - // set { _AddBlankPagesForDuplexPrinting = value; } - //} - private int _prevSectId = 0; + // the following two variables are used to handle the 'PSOnlyFirst' page list Justify flag. + // PSOnlyFirst signals that the pagelist token should only be processed for the first page of + // the section. It gets set when this token is processed, so that any remaining pages will + // not get the token. It's value is derived by taking the different the location of this token + // & the location of the previous token, so that this amount can be used to move the text up + // on the 'not first' pages of the section. It's used as an adjustment on the topmargin. + // This is used in FNP formats. + private int _sectLevelNumTtlDiff = 0; + + public int PrintedSectionPage { get; set; } = 0; + public static int CountInApplProcs { get; set; } + public static int PrintingChild { get; set; } = 0; + + private int _prevSectId = 0; public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document) { TableAdjustment = 0;// RHM20150525 - Table Scrunch @@ -323,17 +158,15 @@ namespace Volian.Print.Library { // yoffset the footer length + the size of the phone list: float yoff = (float)MySection.MyDocStyle.Layout.FooterLength + PhoneListHeight + 12; // 12 is an extra line for the horizontal. - DocVersionConfig dvc = MySection.MyDocVersion.MyConfig as DocVersionConfig; - if (dvc != null) - DrawPhoneList(writer.DirectContent, (float)MySection.MyDocStyle.Layout.LeftMargin, (float)MySection.MyDocStyle.Layout.PageWidth, yoff, dvc.Print_PhoneList); - } + if (MySection.MyDocVersion.MyConfig is DocVersionConfig dvc) + DrawPhoneList(writer.DirectContent, (float)MySection.MyDocStyle.Layout.LeftMargin, (float)MySection.MyDocStyle.Layout.PageWidth, yoff, dvc.Print_PhoneList); + } } if (MySection.MyDocStyle.CenterLineX != null && !onBlankPage) { if ((MySection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) DrawHorizontal(writer.DirectContent, (float)MySection.MyDocStyle.Layout.LeftMargin, (float)MySection.MyDocStyle.Layout.PageWidth, (float)MySection.MyDocStyle.CenterLineYTop); - //if (MySection.ColumnMode > 0 && onBlankPage == false) if (MySection.ColumnMode > 0 || MySection.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining) { DrawCenterLine(writer.DirectContent, MySection.MyDocStyle.Layout.LeftMargin + MySection.MyDocStyle.CenterLineX ?? 0, MySection.MyDocStyle.CenterLineYTop ?? 0, MySection.MyDocStyle.CenterLineYBottom ?? 0); @@ -411,7 +244,7 @@ namespace Volian.Print.Library cb.LineTo(x, y); cb.Stroke(); } - for (float y = yBottom; y <= yTop; y += 10) + for (float y = yBottom; y <= yTop; y += 10) { float w = 10; if (i % 10 == 0) w = 30; @@ -422,8 +255,8 @@ namespace Volian.Print.Library cb.LineTo(x, y); cb.Stroke(); } -i = 0; - cb.Stroke(); + + cb.Stroke(); cb.RestoreState(); cb.EndLayer(); } @@ -434,7 +267,6 @@ i = 0; if (PageListLayer != null) cb.BeginLayer(PageListLayer); cb.SetColorStroke(new Color(PrintOverride.SvgColor)); cb.SetLineWidth(1.05f); // Tweak the line width to match vlnmacro - //cb.SetColorStroke(lineColor); cb.MoveTo(x, top); cb.LineTo(x, bottom); cb.Stroke(); @@ -445,7 +277,7 @@ i = 0; private void DrawPhoneList(PdfContentByte pdfContentByte, float leftMargin, float pageWidth, float yOff, string plist) { // draw the line above the phone list: - yOff = yOff + 4; // move up 1/2 line: + yOff += 4; // move up 1/2 line: DrawHorizontal(pdfContentByte, leftMargin, pageWidth, yOff); pdfContentByte.SaveState(); @@ -494,7 +326,7 @@ i = 0; else endOfLine = true; } - lyoff = lyoff - vlnPrintObject.SixLinesPerInch; + lyoff -= vlnPrintObject.SixLinesPerInch; } } } @@ -513,7 +345,6 @@ i = 0; if (PageListLayer != null) cb.BeginLayer(PageListLayer); cb.SetColorStroke(new Color(PrintOverride.SvgColor)); if (MySection.MyDocStyle.CLineWidth != null && MySection.MyDocStyle.CLineWidth != 0) cb.SetLineWidth((float)MySection.MyDocStyle.CLineWidth); - //cb.SetColorStroke(lineColor); // C2018-004 create meta file for baseline compares Volian.Base.Library.BaselineMetaFile.WriteLine("HorzLn X1={0} Y={1} X2={2}", left, yoff, right); cb.MoveTo(left, yoff); @@ -541,13 +372,11 @@ i = 0; } private void DrawCenterLine(PdfContentByte cb, float xLoc, float yTop, float yBottom) { - //iTextSharp.text.Color lineColor = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.DarkOrange)); cb.SaveState(); if (PageListLayer != null) cb.BeginLayer(PageListLayer); float lwidth = MySection.MyDocStyle.CLineWidth ?? .95f; cb.SetLineWidth(lwidth); cb.SetColorStroke(new Color(PrintOverride.SvgColor)); - //cb.SetColorStroke(lineColor); cb.MoveTo(xLoc, yTop); float ylast = yTop; if (_MyGaps != null) @@ -608,7 +437,7 @@ i = 0; private float? _YTopMargin = null; public float? YTopMargin { - get { return _YTopMargin - _AdjustTopMarginForMultiLinePageListItems; } + get { return _YTopMargin - AdjustTopMarginForMultiLinePageListItems; } set { _YTopMargin = value; } } private void DrawRuler(PdfContentByte cb) @@ -711,14 +540,6 @@ i = 0; cb.LineTo(x1, yRuler + 5); } } - //cb.MoveTo(122.4F, 0); //WCN2 HLS - //cb.LineTo(122.4F, cb.PdfWriter.PageSize.Height); - //cb.MoveTo(78, 0); // HLP HLS - //cb.LineTo(78, cb.PdfWriter.PageSize.Height); - //cb.MoveTo(441, 0); // HLP cover page date - //cb.LineTo(441, cb.PdfWriter.PageSize.Height); - //cb.MoveTo(71.4F, 0); // WCN Purpose page, Revision: {REV} - //cb.LineTo(71.4F, cb.PdfWriter.PageSize.Height); cb.Stroke(); cb.EndLayer(); cb.RestoreState(); @@ -739,9 +560,8 @@ i = 0; } else { - PdfDestination dest =pb.PdfDestination; - if(dest==null) dest = new PdfDestination(PdfDestination.FIT); - PdfOutline pdo = new PdfOutline(MyPdfOutlines[lev-1], dest,Regex.Replace(pb.Title, @"\\{Prerequisite Step: .*?\\}", string.Empty), false); + PdfDestination dest = pb.PdfDestination ?? new PdfDestination(PdfDestination.FIT); + PdfOutline pdo = new PdfOutline(MyPdfOutlines[lev-1], dest,Regex.Replace(pb.Title, @"\\{Prerequisite Step: .*?\\}", string.Empty), false); if (MyPdfOutlines.Count == lev) MyPdfOutlines.Add(pdo); else @@ -852,42 +672,27 @@ i = 0; // TODO: Pass in zeroes because topdf is inherited. vcb.ToPdf(cb, topMargin, ref tmp, ref tmp); } - _MyChangeBars = new List(); + MyChangeBars = new List(); } - #region SectionLevelData - private ChangeBarDefinition _ChangeBarDefinition; - public ChangeBarDefinition ChangeBarDefinition - { - get { return _ChangeBarDefinition; } - set { _ChangeBarDefinition = value; } - } - #endregion - private PdfLayer _TextLayer; - public PdfLayer TextLayer - { - get { return _TextLayer; } - set { _TextLayer = value; } - } - private PdfLayer _DebugLayer; - public PdfLayer DebugLayer - { - get { return _DebugLayer; } - set { _DebugLayer = value; } - } - private VEPROMS.CSLA.Library.SectionInfo _MySection; + #region SectionLevelData + public ChangeBarDefinition ChangeBarDefinition { get; set; } + #endregion + public PdfLayer TextLayer { get; set; } + public PdfLayer DebugLayer { get; set; } + private VEPROMS.CSLA.Library.SectionInfo _MySection; public VEPROMS.CSLA.Library.SectionInfo MySection { get { return _MySection; } set { _MySection = value; - MySectionTitle = ((_MySection.DisplayNumber ?? string.Empty) == string.Empty ? string.Empty : _MySection.DisplayNumber + " - ") + _MySection.DisplayText; + MySectionTitle = $"{((_MySection.DisplayNumber ?? string.Empty) == string.Empty ? string.Empty : $"{_MySection.DisplayNumber} - ")}{_MySection.DisplayText}"; bool forceLoadSvg = false; if (value.SectionConfig.Section_Pagination == SectionConfig.SectionPagination.Separate && value.MyDocStyle.ResetFirstPageOnSection) DidFirstPageDocStyle = false; if (DidFirstPageDocStyle) forceLoadSvg = SetDocStyleAndValues(); // this method also gets the SVG (the 'else' part of this) - if (_prtSectID > -1) { + if (PrtSectID > -1) { forceLoadSvg = true; } Volian.Svg.Library.Svg sectSvg = BuildSvg(_MySection, forceLoadSvg); @@ -895,52 +700,16 @@ i = 0; _YTopMargin = null; } } - private string _MySectionTitle; - public string MySectionTitle - { - get { return _MySectionTitle; } - set { _MySectionTitle = value; } - } - private int _MaxRNO; - public int MaxRNO - { - get - { - return _MySection.ColumnMode; - } - } - private int _CurrentPageOf = 0; - public int CurrentPageOf - { - get { return _CurrentPageOf; } - set { _CurrentPageOf = value; } - } - private string _Rev = string.Empty; - public string Rev - { - get { return _Rev; } - set { _Rev = value; } - } - private string _RevDate = string.Empty; - public string RevDate - { - get { return _RevDate; } - set { _RevDate = value; } - } - private bool _DoFloatingFoldout = true; - public bool DoFloatingFoldout - { - get { return _DoFloatingFoldout; } - set { _DoFloatingFoldout = value; } - } - private List _MyChangeBars = new List(); - public List MyChangeBars - { - get { return _MyChangeBars; } - set { _MyChangeBars = value; } - } - public void AddChangeBar(vlnChangeBar vcb, string cbmess) + public string MySectionTitle { get; set; } + public int MaxRNO => _MySection.ColumnMode; + + public int CurrentPageOf { get; set; } = 0; + public string Rev { get; set; } = string.Empty; + public string RevDate { get; set; } = string.Empty; + public bool DoFloatingFoldout { get; set; } = true; + public List MyChangeBars { get; set; } = new List(); + public void AddChangeBar(vlnChangeBar vcb, string cbmess) { if (vcb == null) return; vlnChangeBar prevCB = null; @@ -1041,17 +810,12 @@ i = 0; vcb.YChangeBarBottomExtend >= (cb.YChangeBarBottomExtend - tolerance)) return true; return false; } - private PromsPrinter _MyPromsPrinter; - public PromsPrinter MyPromsPrinter - { - get { return _MyPromsPrinter; } - set { _MyPromsPrinter = value; } - } - private int _MyRomanPage = 1; - public VlnSvgPageHelper(VEPROMS.CSLA.Library.SectionInfo mySection, PromsPrinter myPromsPrinter, string hlsText, int hlsItemId, int PrtSectID) + + public PromsPrinter MyPromsPrinter { get; set; } + public VlnSvgPageHelper(VEPROMS.CSLA.Library.SectionInfo mySection, PromsPrinter myPromsPrinter, string hlsText, int hlsItemId, int PrtSectID) : base() { - _prtSectID = PrtSectID; + this.PrtSectID = PrtSectID; HLSText = hlsText; HasHLSTextId = hlsItemId; MyPromsPrinter = myPromsPrinter; @@ -1060,20 +824,6 @@ i = 0; } private Volian.Svg.Library.Svg BuildSvg(VEPROMS.CSLA.Library.SectionInfo mySection, bool forceLoad) { - // if mysection uses continuous pagination, and the previous section uses the same format, - // and the docstyle is set to use on first page only, - // then set section to use the Use On Rest of Pages - //SectionConfig.SectionPagination sPag = SectionConfig.SectionPagination.Separate; - //if (mySection.IsStepSection && mySection.MyPrevious != null && mySection.MyPrevious.IsStepSection) - //{ - // SectionConfig sc = mySection.MyConfig as SectionConfig; - // sPag = sc.Section_Pagination; - // if (sPag == SectionConfig.SectionPagination.Continuous) - // { - // if (MySection.MyDocStyle.StructureStyle.Where == E_DocStyleUse.UseOnFirstPage) - // MySection.DidFirstPageDocStyle = true; - // } - //} VEPROMS.CSLA.Library.FormatInfo activeFormat = mySection.ActiveFormat; VEPROMS.CSLA.Library.DocStyle docStyle = mySection.MyDocStyle; Volian.Svg.Library.Svg mySvg = null; @@ -1101,7 +851,6 @@ i = 0; SectionConfig sc = mySection.MyConfig as SectionConfig; sPag = sc.Section_Pagination; } - //if (sPag == SectionConfig.SectionPagination.Continuous && !mySection.DidFirstPageDocStyle) return null; if (forceLoad) return mySvg; if (sPag == SectionConfig.SectionPagination.Continuous) return null; return mySvg; @@ -1109,8 +858,8 @@ i = 0; public PageCounts MyPageCounts = null; public PageCounts MyTOCPageCounts = null; public Dictionary MyTOCPageNums = null; - private static Regex regexFindToken = new Regex("{[^{}]*}"); - private static Regex regexFindSubToken = new Regex(@"\[[^{}]*\]"); + private static readonly Regex regexFindToken = new Regex("{[^{}]*}"); + private static readonly Regex regexFindSubToken = new Regex(@"\[[^{}]*\]"); private string mySvg_ProcessText(object sender, SvgProcessTextArgs args) { if (args.MyText == null) return string.Empty; // Needed for empty genmac text (was space in 16bit files) @@ -1126,26 +875,18 @@ i = 0; { top = top.MyParent; } - string key = "DocCurPage." + top.ItemID; + string key = $"DocCurPage.{top.ItemID}"; string txt = args.MyText.Replace("{METACURPAGE}", "{PAGE}").Replace("{METATOTPAGE}", "{OF}"); MyPdfContentByte.AddTemplate(MyPageCounts.AddToTemplateList(key, MyPdfWriter, txt, args.MySvgText.Font, args.MySvgText.Align, args.MySvgText.FillColor), args.MySvgScale.X(args.MySvgText.X), args.MySvgScale.Y(MyPdfContentByte, args.MySvgText.Y)); return string.Empty; } if (args.MyText.Contains("{DOCCURPAGE}") || args.MyText.Contains("{DOCTOTPAGE}")) { - string key = "DocCurPage." + MySection.ItemID; + string key = $"DocCurPage.{MySection.ItemID}"; string txt = args.MyText.Replace("{DOCCURPAGE}", "{PAGE}").Replace("{DOCTOTPAGE}", "{OF}"); MyPdfContentByte.AddTemplate(MyPageCounts.AddToTemplateList(key, MyPdfWriter, txt, args.MySvgText.Font, args.MySvgText.Align, args.MySvgText.FillColor), args.MySvgScale.X(args.MySvgText.X), args.MySvgScale.Y(MyPdfContentByte, args.MySvgText.Y)); return string.Empty; } - //if (args.MyText.Contains("{ROMANPAGE}")) - //{ - // //return args.MyText.Replace("{ROMANPAGE}", ItemInfo.RomanNumbering(_MyRomanPage++).ToLower()); - // string key = "RomanPage." + MySection.ItemID; - // string txt = args.MyText; - // MyPdfContentByte.AddTemplate(MyPageCounts.AddToTemplateList(key, MyPdfWriter, txt, args.MySvgText.Font, args.MySvgText.Align, args.MySvgText.FillColor), args.MySvgScale.X(args.MySvgText.X), args.MySvgScale.Y(MyPdfContentByte, args.MySvgText.Y)); - // return string.Empty; - //} if (args.MyText.Contains("{SECONDARYPAGE}") || args.MyText.Contains("{SECONDARYOF}")) { string key = "SecondaryPage." + MySection.DisplayNumber; @@ -1153,12 +894,12 @@ i = 0; MyPdfContentByte.AddTemplate(MyPageCounts.AddToTemplateList(key, MyPdfWriter, txt, args.MySvgText.Font, args.MySvgText.Align, args.MySvgText.FillColor), args.MySvgScale.X(args.MySvgText.X), args.MySvgScale.Y(MyPdfContentByte, args.MySvgText.Y)); return string.Empty; } - //string tocKey = "TOC" + MySection.ItemID.ToString(); if (args.MyText.Contains("{PAGE}") || args.MyText.Contains("{OF}")) { #region numberingseq /* + //For Reference: public enum E_NumberingSequence : uint { NoPageNum = 0, @@ -1189,7 +930,7 @@ i = 0; case E_NumberingSequence.WithSteps: // Number with 'originalstepsection' ProcedureInfo pc = MySection.MyProcedure; int sectid = 0; - foreach (SectionInfo si in pc.Sections) + foreach (SectionInfo si in pc.Sections.OfType()) { SectionConfig sc = si.MyConfig as SectionConfig; if (sc.Section_OriginalSteps == "Y") @@ -1198,33 +939,30 @@ i = 0; break; } } - if (sectid != 0) key = (int)E_NumberingSequence.WithinEachSection + "." + sectid; + if (sectid != 0) key = $"{(int)E_NumberingSequence.WithinEachSection}.{sectid}"; break; case E_NumberingSequence.WithinEachDocStyle: - key = key + "." + MySection.ActiveFormat.FormatID + "." + MySection.MyDocStyle.Index; + key = $"{key}.{MySection.ActiveFormat.FormatID}.{MySection.MyDocStyle.Index}"; break; - //case E_NumberingSequence.WithinEachDocStyle1: - // key = key + "." + MySection.DisplayNumber; - // break; case E_NumberingSequence.WithinEachSection: - key = key + "." + MySection.ItemID; + key = $"{key}.{MySection.ItemID}"; break; case E_NumberingSequence.WithinEachSectionNumber: - key = key + "." + ( MySection.DisplayNumber == string.Empty ? (MySection.ActiveParent as ItemInfo).DisplayNumber : MySection.DisplayNumber); + key = $"{key}.{( MySection.DisplayNumber == string.Empty ? (MySection.ActiveParent as ItemInfo).DisplayNumber : MySection.DisplayNumber)}"; break; case E_NumberingSequence.GroupedByLevel: case E_NumberingSequence.Like6_ButDoesntNeedSubsection: if (MySection.MyParent.IsSection) - key = key + "." + MySection.MyParent.ItemID; + key = $"{key}.{MySection.MyParent.ItemID}"; else - key = key + "." + MySection.ItemID; + key = $"{key}.{MySection.ItemID}"; break; case E_NumberingSequence.WithStepsAndSecondaryPageNumber: // For this one, we'll do two keys and templates. One will go with the main steps // section and one will be for this secondary section. ProcedureInfo pc1 = MySection.MyProcedure; int psectid = 0; - foreach (SectionInfo si in pc1.Sections) + foreach (SectionInfo si in pc1.Sections.OfType()) { SectionConfig sc = si.MyConfig as SectionConfig; if (sc.Section_OriginalSteps == "Y") @@ -1235,7 +973,7 @@ i = 0; } if (psectid != 0) { - key = (int)E_NumberingSequence.WithinEachSection + "." + psectid; + key = $"{(int)E_NumberingSequence.WithinEachSection}.{psectid}"; PdfTemplate tmp1 = MyPageCounts.AddToTemplateList(key, MyPdfWriter, args.MyText, args.MySvgText.Font, args.MySvgText.Align, args.MySvgText.FillColor); } break; @@ -1299,7 +1037,7 @@ i = 0; } if (sGenMacBase != null && sGenMacBase != string.Empty) { - sGenMac = sGenMac.Replace("", sGenMacBase + ""); + sGenMac = sGenMac.Replace("", $"{sGenMacBase}"); } if (!sGenMac.Contains("xmlns")) sGenMac = sGenMac.Replace(" token.Substring(1, 1) + token.Substring(token.Length - 2, 1); // The following variables are used to keep track of whether a check off header should be printed // if the {CHKOFFHEADING} pagelist item is found. PageListTopCheckOffHeader is the text that @@ -1356,12 +1090,6 @@ i = 0; } SvgGroup svgGroup = new SvgGroup(); - //int defPtPerRow = 72 / 6; - //int curLPI = 6; // default - //int prevLPI = 6; - //float PrevRow = 0; - //float rowAdj = 0; // = 18; - bool usePSIvalue = false; // C2021-065 used with ROLkUpMatch pagelist flag (Barakah Alarms) string otherChildUnit = string.Empty; // C2021-065 used when OTHER applicability information is used for the ROLookUp // F2023-035: WCN - allow for change in left margin for supplemental information pages by @@ -1388,18 +1116,6 @@ i = 0; VE_Font useFontForCheckOffHeader = null; if (forceLoad || (sPag == SectionConfig.SectionPagination.Separate || ((sPag == SectionConfig.SectionPagination.Continuous || sPag ==0 )&& (pageItem.Row < 0)))) { - //if (PrevRow > 0) - //{ - // //float pgRow = (float)(pageItem.Row + rowAdj); - // if (curLPI != prevLPI) - // { - // int prow = (int)(PrevRow / defPtPerRow); - // int nrows = ((int)(pageItem.Row / defPtPerRow)) - prow; - // rowAdj += (float)Math.Abs(((nrows * (72 / curLPI)) - ((nrows * defPtPerRow) + rowAdj))); - // //rowAdj += (float)(((pgRow - PrevRow) / (72 * prevLPI)) * (72 / curLPI)); - // prevLPI = curLPI; - // } - //} // C2019-006 - Moved and modified the RO_Lookup() logic here, before we process the tokens in the page list // this allows us to use RO_Lookup() in a "PS=" conditional token (is usually a PSI check box) // A while loop was also added to the we can have more than one call to RO_Lookup() on a pagelist line @@ -1502,7 +1218,6 @@ i = 0; foreach (Match match in matches) { string token = match.Value; - //token = Regex.Replace(token, @"[\xB3-\xDF]", " "); // handle any conditional PS tokens if (token.Contains(@"PS=")) @@ -1528,8 +1243,7 @@ i = 0; string relval = procConfig.GetValue("PSI", reltoken); if (relval == "Y") { - //svgGroup.Add(PageItemToSvgText(pageItem.Token, (float)pageItem.RelatedItem.Row, (float)pageItem.RelatedItem.Col, pageItem.RelatedItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft, pageItem.Font, val, MySection)); - svgGroup.Add(PageItemToSvgText(pltok, (float)pageItem.RelatedItem.Row, (float)pageItem.RelatedItem.Col, pageItem.RelatedItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft, pageItem.Font, val, MySection)); + svgGroup.Add(PageItemToSvgText(pltok, (float)pageItem.RelatedItem.Row, (float)pageItem.RelatedItem.Col, pageItem.RelatedItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft, pageItem.Font, val, MySection)); plstr = string.Empty; // Clear it so it isn't put out twice (used below) } } @@ -1540,8 +1254,6 @@ i = 0; val = token.Substring(bindx + 1, eindx - bindx - 1); } if (val != null && val != string.Empty && !PgLogicals.ContainsKey(pstok)) PgLogicals.Add(pstok, val != null); - //if (val == null || val == string.Empty) - //val = " "; if (val == null) val = string.Empty; plstr = plstr.Replace(token, val); @@ -1595,8 +1307,6 @@ i = 0; val = token.Substring(bindx + 1, eindx - bindx - 1); } if (val != null && val != string.Empty && !PgLogicals.ContainsKey(pstok)) PgLogicals.Add(pstok, val != null); - //if (val == null || val == string.Empty) - //val = " "; if (val == null) val = string.Empty; plstr = plstr.Replace(token, val); @@ -1650,23 +1360,18 @@ i = 0; Volian.Base.Library.BaselineMetaFile.WriteLine("No Pagelist Information"); } - private string ROLookup(string accpageid, string multiid, string deflt) - { - return ROLookup(accpageid, multiid, deflt, string.Empty); - } - // C2021-065 pass in a override for the child unit - in this case the token is being used (Barakah Alarms) private string ROLookup(string accpageid, string multiid, string deflt, string overrideChild) { ROFSTLookup myLookup = MySection.MyDocVersion.DocVersionAssociations[0].MyROFst.GetROFSTLookup(MySection.MyDocVersion, overrideChild); //C2026-047 first try the RO Lookup with the ascii dash character in the accpageid. If not found, try again with the unicode dash - ROFSTLookup.rochild roc = myLookup.GetROChildByAccPageID("<" + accpageid.Replace(@"\u8209?", "-") + "." + multiid + ">", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); + ROFSTLookup.rochild roc = myLookup.GetROChildByAccPageID($"<{accpageid.Replace(@"\u8209?", "-")}.{multiid}>", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); if (roc.value == null) { // try again but this time with the unicode dash - roc = myLookup.GetROChildByAccPageID("<" + accpageid + "." + multiid + ">", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); + roc = myLookup.GetROChildByAccPageID($"<{accpageid}.{multiid}>", MySection.MyDocVersion.DocVersionConfig.RODefaults_setpointprefix, MySection.MyDocVersion.DocVersionConfig.RODefaults_graphicsprefix); } if (!deflt.StartsWith("[") && !string.IsNullOrEmpty(roc.value) && roc.value.Trim().Length > 0) // don't return val if it's an empty or blank string - jsj 01-28-2019 @@ -1679,19 +1384,9 @@ i = 0; return deflt; } - private bool _DidHLSText = false; - public bool DidHLSText - { - get { return _DidHLSText; } - set { _DidHLSText = value; } - } - private int _HasHLSTextId = 0; - public int HasHLSTextId - { - get { return _HasHLSTextId; } - set { _HasHLSTextId = value; } - } - private string _HLSText = string.Empty; + public bool DidHLSText { get; set; } = false; + public int HasHLSTextId { get; set; } = 0; + private string _HLSText = string.Empty; public string HLSText { get { return _HLSText; } @@ -1701,43 +1396,24 @@ i = 0; _HLSText = value; } } - private string _HLSTAB = string.Empty; - public string HLSTAB - { - get { return _HLSTAB; } - set { _HLSTAB = value; } - } - private string _HLRNO = string.Empty; - public string HLRNO - { - get { return _HLRNO; } - set { _HLRNO = value; } - } - private bool _OldTemplateContMsg = false; - public bool OldTemplateContMsg - { - get { return _OldTemplateContMsg; } - set { _OldTemplateContMsg = value; } - } - private float _AdjustTopMarginForMultiLinePageListItems = 0; - public float AdjustTopMarginForMultiLinePageListItems - { - get { return _AdjustTopMarginForMultiLinePageListItems; } - set { _AdjustTopMarginForMultiLinePageListItems = value; } - } - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// true - if token is resolved - /// false - if entire text is processed - /// - private bool ProcessPaglistToken(VEPROMS.CSLA.Library.SectionInfo section, SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, ref VE_Font useFontForCheckOffHeader, ref string plstr, string token, float supInfoMargAdj) + + public string HLSTAB { get; set; } = string.Empty; + public string HLRNO { get; set; } = string.Empty; + public bool OldTemplateContMsg { get; set; } = false; + public float AdjustTopMarginForMultiLinePageListItems { get; set; } = 0; + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// true - if token is resolved + /// false - if entire text is processed + /// + private bool ProcessPaglistToken(VEPROMS.CSLA.Library.SectionInfo section, SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, ref VE_Font useFontForCheckOffHeader, ref string plstr, string token, float supInfoMargAdj) { bool retval = true; @@ -1755,12 +1431,6 @@ i = 0; plstr = plstr.Replace(token, string.Empty); AddImage(svgGroup, 10f, 10f, 78.7f, 29.8f, "cpllogo.bmp"); break; - //case "{!domlogo}": - // AddImage(svgGroup, 10f, 70f, 123f, 40.1f, "domlogo.bmp"); - // break; - //case "{!gpclogo}": - // AddImage(svgGroup, 10f, 150f, 35.2f, 35.8f, "gpclogo.bmp"); - // break; case "{HEADER1}": case "[HEADER1]": case "{HEADER2}": @@ -1811,29 +1481,22 @@ i = 0; box = "3"; else if (_MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.Two) box = "2"; - box = "{BOX" + box + "}"; + box = $"{{BOX{box}}}"; plstr = plstr.Replace(token, string.Empty); svgGroup.Add(PageItemToSvgUse(pageItem, FirstAndLast(box), supInfoMargAdj)); break; case "{DRAFTPAGE}": - //if (!AllowedWatermarks.Contains("Draft")) AllowedWatermarks.Add("Draft"); -- B2018-124 not needed anymore plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; case "{REFERENCEPAGE}": - //if (!AllowedWatermarks.Contains("Reference")) AllowedWatermarks.Add("Reference"); -- B2018-124 not needed anymore plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; case "{MASTERPAGE}": - //if (!AllowedWatermarks.Contains("Master")) AllowedWatermarks.Add("Master"); -- B2018-124 not needed anymore plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; case "{SAMPLEPAGE}": - //if (!AllowedWatermarks.Contains("Sample")) AllowedWatermarks.Add("Sample"); -- B2018-124 not needed anymore plstr = plstr.Replace(token, string.Empty);// Remove token since it is handled now break; - //case "{INFORMATIONPAGE}": - // if (!AllowedWatermarks.Contains("Information Only")) AllowedWatermarks.Add("Information Only"); -- B2018-124 not needed anymore - // break; case "{PROCTITLE}": case "[PROCTITLE]": case "{PROCTITLE1}": @@ -1845,7 +1508,6 @@ i = 0; case "{COVERPROCTITLE}": case "[COVERPROCTITLE]": int tlen = (token.Contains("COVERPROCTITLE"))?(int)section.ActiveFormat.PlantFormat.FormatData.ProcData.CoverTitleLength : (int)section.ActiveFormat.PlantFormat.FormatData.ProcData.TitleLength; - //float linelen = (int)section.ActiveFormat.PlantFormat.FormatData.ProcData.TitleLength * (float)pageItem.Font.CPI / 12; float linelen = tlen * (float)pageItem.Font.CPI / 12; string title = section.MyProcedure.MyContent.Text; if (title.Contains("") && !section.ActiveFormat.PlantFormat.FormatData.ProcData.PrintNoTitle) @@ -1924,7 +1586,7 @@ i = 0; // F2023-087: Added PDFDate at PDFTime - note that cannot have multiple tokens in a conditional because of reg expression // processing. case "[PDFDateAtTime]": - plstr = plstr.Replace("[PDFDateAtTime]", DateTime.Now.ToString("MM/dd/yyyy") + " at " + DateTime.Now.ToString("HH:mm:ss")); + plstr = plstr.Replace("[PDFDateAtTime]", $"{DateTime.Now:MM/dd/yyyy} at {DateTime.Now:HH:mm:ss}"); break; case "{EOPNUM}": case "[EOPNUM]": @@ -1984,8 +1646,6 @@ i = 0; eopnum = eopnum.TrimEnd(pageItem.TrimEnding.ToCharArray()); plstr = plstr.Replace(token, eopnum); - //svgGroup.Add(PageItemToSvgText(pageItem, pageItem.Token.Replace(token, eopnum))); - //svgGroup.Add(PageItemToSvgText(pageItem, pageItem.Token.Replace(token, section.MyProcedure.MyContent.Number))); break; case "{SECTIONLEVELTITLE}": case "[SECTIONLEVELTITLE]": @@ -2007,7 +1667,7 @@ i = 0; && token.Contains("ATTACHTITLECONT") && DidFirstPageDocStyle) { string myMsg = section.MyDocStyle.Continue.Top.Message; - if (myMsg != null && myMsg != string.Empty)stitle = stitle + myMsg; + if (myMsg != null && myMsg != string.Empty)stitle += myMsg; } // B2023-043: Beaver Valley AOP - allow attributes, such as superscript on section titles when printing if (section.ActiveFormat.PlantFormat.FormatData.PrintData.SectionTitleWithAttributes) @@ -2024,7 +1684,6 @@ i = 0; } else plstr = plstr.Replace(token, string.Empty); - //svgGroup.Add(PageItemToSvgText(pageItem, section.DisplayText)); break; case "{METASECTIONTITLE}": // This will print the top level section title (versus level above current) starting from a sub-section case "[METASECTIONTITLE]": @@ -2078,7 +1737,6 @@ i = 0; // text starts with a ' - ' - remove it. else if (plstr.StartsWith(" - ") && plstr.IndexOf("{SECTIONLEVELTITLE}") == 3) plstr = plstr.Substring(3); - //svgGroup.Add(PageItemToSvgText(pageItem, pageItem.Token.Replace(token, section.DisplayNumber))); break; case "{METASECTIONNUMBER}": // This will print the top level section number when starting from a sub-section case "[METASECTIONNUMBER]": @@ -2113,7 +1771,6 @@ i = 0; case "{UNITTEXT}": case "[UNITTEXT]": plstr = plstr.Replace(token, MySection.MyDocVersion.DocVersionConfig.Unit_Text); - //svgGroup.Add(PageItemToSvgText(pageItem, pageItem.Token.Replace(token, MySection.MyDocVersion.DocVersionConfig.Unit_Text))); break; case "{UNITNUMBER}": case "[UNITNUMBER]": @@ -2319,15 +1976,9 @@ i = 0; break; case "{INITIALS}": // For Calvert: if this section has checkoffs turned on, put out this pagelist item: - // Get SectionInfos to access specific section config items... - //SectionInfo si = SectionInfo.Get(MySection.ItemID); - //SectionInfo si = MySection.GetSectionInfo(); - //SectionConfig sectCfg = si.MyConfig as SectionConfig; - //int sc = sectCfg.Section_CheckoffListSelection; if (!MySection.HasInitials) { plstr = plstr.Replace(token, string.Empty); - //PIInitials = pageItem; } else { @@ -2341,19 +1992,19 @@ i = 0; } break; case "{REVUNIT}": - // copied from 16bit's pagelist.cs for BGE: - string revUnit = null; - string unitNum = MySection.MyDocVersion.DocVersionConfig.Print_UnitNumberForPageList; - if (Rev != null && Rev != string.Empty) - { - revUnit = Rev; - int indxs = Rev.IndexOf(MySection.ActiveFormat.PlantFormat.FormatData.PrintData.RevDateWithForwardSlash ? '\\' : '/'); - if (indxs > 0) revUnit = Rev.Substring(0, indxs); - } - else - revUnit = " "; + string unitNum = MySection.MyDocVersion.DocVersionConfig.Print_UnitNumberForPageList; + // copied from 16bit's pagelist.cs for BGE: + string revUnit; + if (Rev != null && Rev != string.Empty) + { + revUnit = Rev; + int indxs = Rev.IndexOf(MySection.ActiveFormat.PlantFormat.FormatData.PrintData.RevDateWithForwardSlash ? '\\' : '/'); + if (indxs > 0) revUnit = Rev.Substring(0, indxs); + } + else + revUnit = " "; - if (unitNum == "2") + if (unitNum == "2") revUnit += "/Unit 2"; else if (unitNum == "1") revUnit += "/Unit 1"; @@ -2431,12 +2082,11 @@ i = 0; { int indx = token.IndexOf("-"); int qindx = token.IndexOf("?", indx); - string val = null; - if (qindx == -1) + if (qindx == -1) { - val = procConfig.GetValue("PSI", token.Substring(4, token.Length - 5)); - // F2021-034: Resolve applicability unit tokens (not just '') - if(val.ToUpper().Contains("") || val.ToUpper().Contains("') + if (val.ToUpper().Contains("") || val.ToUpper().Contains("", 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; } - // B2019-076: moved the following to DocVersionExt.cs to make it available to transitionext.cs code. - //private string GetInheritedSIValue(ProcedureInfo pi, string fieldName) - //{ - // string val = null; - // DocVersionConfig dvConfig = new DocVersionConfig(pi.MyDocVersion.Config); - // if (dvConfig != null) - // { - // val = dvConfig.GetValue("SI", fieldName); - // if (val != null && val != string.Empty) return val; // the value exists within the docversion level - // } - // FolderInfo fi = pi.MyDocVersion.MyFolder; - // while (fi != null) - // { - // FolderConfig folderConfig = new FolderConfig(fi.Config); - // if (folderConfig != null) - // { - // val = folderConfig.GetValue("SI", fieldName); - // if (val != null && val != string.Empty) return val; // the value exists within this folder - // } - // fi = fi.ActiveParent as FolderInfo; - // } - // return val; - //} private static ItemInfo ValveGetFirstStep(VEPROMS.CSLA.Library.SectionInfo section) { ItemInfo firstHigh = null; @@ -2596,7 +2198,7 @@ i = 0; private static void AddImage(SvgGroup svgGroup, float x, float y, float w, float h, string figure) { svgGroup.Add(new SvgImage(new System.Drawing.PointF(x, y), new System.Drawing.SizeF(w, h), - System.Windows.Forms.Application.StartupPath + @"\Resources\" + figure)); + $@"{System.Windows.Forms.Application.StartupPath}\Resources\{figure}")); } private float SplitTextMaxWidth(SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, string title, int? len, string match, ref string plstr) { @@ -2649,7 +2251,6 @@ i = 0; if (match == "{PROCTITLE}") title = title.Replace("\\line ", string.Empty); if (match == "{PROCTITLE2}" || match == "[PROCTITLE2]") return plstr.Replace(match, string.Empty); // this would have been done in proctitle1 plstr = plstr.Replace(match, title).Replace("@@",string.Empty); - //svgGroup.Add(PageItemToSvgText(pageItem, title)); return plstr; } @@ -2657,7 +2258,7 @@ i = 0; // the '@@' marked the starting location for the title. Process this differently than other split titles: if (plstr.Contains("@@")) { - DoSpecialSectNumTitle(svgGroup, pageItem, title, len, match, plstr); + DoSpecialSectNumTitle(svgGroup, pageItem, title, len, plstr); return string.Empty; // all resolved pagelist items were already added to svgGroup for printing. } // Otherwise determine how many line to split the text into @@ -2710,36 +2311,22 @@ i = 0; set { if (_PIInitials != null && value == null) - _LastPIInitials = _PIInitials; + LastPIInitials = _PIInitials; _PIInitials = value; } } - private PageItem _LastPIInitials = null; - public PageItem LastPIInitials - { - get { return _LastPIInitials; } - set { _LastPIInitials = value; } - } - private bool _HasInitials = false; - public bool HasInitials - { - get { return _HasInitials; } - set { _HasInitials = value; } - } - private bool _InitialsPrinted = false; - public bool InitialsPrinted - { - get { return _InitialsPrinted; } - set { _InitialsPrinted = value; } - } - public bool PrintInitials(PdfContentByte cb,float yLocation, float leftMargin) + + public PageItem LastPIInitials { get; set; } = null; + public bool HasInitials { get; set; } = false; + public bool InitialsPrinted { get; set; } = false; + public bool PrintInitials(PdfContentByte cb,float yLocation, float leftMargin) { if (InitialsPrinted) return false; InitialsPrinted = true; vlnParagraph.TextAt(cb,this, PIInitials ?? LastPIInitials, yLocation, leftMargin); return true; } - private void DoSpecialSectNumTitle(SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, string title, int? len, string match, string plstr) + private void DoSpecialSectNumTitle(SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, string title, int? len, string plstr) { // first add anything up to the "@@" to the svgGroup: string befAts = plstr.Substring(0, plstr.IndexOf("@@")); @@ -2783,28 +2370,6 @@ i = 0; } return plstr.Replace(token, string.Empty); } - //private string symblsStr = "\u25CF\u0394"; // string of possible symbol character in a tab - //// add symbol characters as needed - //// "\u25CF" - solid bullet - //// \x0394 - delta - //private float GetTextWidth(VE_Font vefont, string txt, string symblFontName) - //{ - // System.Drawing.Font font = new System.Drawing.Font(vefont.Family, (float)vefont.Size, GetSysFontStyle(vefont)); - // System.Drawing.Font symbFont = new System.Drawing.Font(symblFontName, (float)vefont.Size); - // iTextSharp.text.Font iFont = Volian.Svg.Library.VolianPdf.GetFont(font); - // iTextSharp.text.Font iSymblFont = Volian.Svg.Library.VolianPdf.GetFont(symbFont); - // float w = 0; - // foreach (char c in txt) - // { - // int idx = symblsStr.IndexOf(c); - // if (idx >= 0) // symbol character - use symbol font to find its width - // w += iSymblFont.BaseFont.GetWidthPointKerned(symblsStr[idx].ToString(), (float)vefont.Size); - // else - // w += iFont.BaseFont.GetWidthPointKerned(c.ToString(), (float)vefont.Size); - // } - // //float w = iFont.BaseFont.GetWidthPointKerned(Text.Replace("\u25CF","@"), (float)vefont.Size); - // return w; - //} private string SplitCoverTitle(SvgGroup svgGroup, VEPROMS.CSLA.Library.PageItem pageItem, string title, int? len, string match, string plstr) { @@ -2812,7 +2377,6 @@ i = 0; { if (match == "{COVERTITLE2}" || match == "[COVERTITLE2]") return plstr; // this would have been done in COVERTITLE1 plstr = plstr.Replace(match, title); - //svgGroup.Add(PageItemToSvgText(pageItem, title)); return plstr; } // Otherwise determine how many line to split the text into @@ -2820,12 +2384,10 @@ i = 0; if (match == "{COVERTITLE1}" || match == "[COVERTITLE1]") { plstr = plstr.Replace(match, titleLines[0]); - //svgGroup.Add(PageItemToSvgText(pageItem, titleLines[0])); return plstr; } // if the token was proctitle, dont' adjust. If the token was PROCTITLE1/2 then // move down 6. -// int adj = pageItem.Token.Contains("1") || pageItem.Token.Contains("2") ? 0 : -6; int adj = (titleLines.Count > 2) ? -6 : 0; float yOffset = adj * (titleLines.Count - 2); int lnCnt = 0; @@ -2840,27 +2402,15 @@ i = 0; } return plstr; } - private int FindWidth(string title, int start, int len) - { - for (int ii = start + len; ii > start; ii--) - { - if (title[ii] == ' ') - { - while (title[ii] == ' ') ii--; - if (ii > start) - return 2 + ii - start; - return len; - } - } - return len; - } private SvgPart PageItemToSvgUse(VEPROMS.CSLA.Library.PageItem pageItem, string templateName, float supmargadj) { - SvgUse svgUse = new SvgUse(); - svgUse.UseID = templateName; - svgUse.X = new SvgMeasurement((float)(pageItem.Col ?? 0) + supmargadj, E_MeasurementUnits.PT); // F2023-035: Add in supplemental info margin adjust - svgUse.Y = new SvgMeasurement((float)(pageItem.Row ?? 0), E_MeasurementUnits.PT); - return svgUse; + SvgUse svgUse = new SvgUse + { + UseID = templateName, + X = new SvgMeasurement((float)(pageItem.Col ?? 0) + supmargadj, E_MeasurementUnits.PT), // F2023-035: Add in supplemental info margin adjust + Y = new SvgMeasurement((float)(pageItem.Row ?? 0), E_MeasurementUnits.PT) + }; + return svgUse; } private static SvgText PageItemToSvgText(VEPROMS.CSLA.Library.PageItem pageItem, string text, VE_Font font, SectionInfo mySection, float supmargadj) { @@ -2924,7 +2474,7 @@ i = 0; // setting a value in the DocStyle for the adjustment. svgText.X = new SvgMeasurement((float)lcol - colAdj16bit + supmargadj, E_MeasurementUnits.PT); // F2023-035: Add in supplemental info margin adjust svgText.Y = new SvgMeasurement(row, E_MeasurementUnits.PT); - if (svgText.Font.Underline && svgText.Text.EndsWith(" ")) svgText.Text = svgText.Text.Substring(0, svgText.Text.Length - 1) + "\xA0";// replace last space with a hardspace + if (svgText.Font.Underline && svgText.Text.EndsWith(" ")) svgText.Text = $"{svgText.Text.Substring(0, svgText.Text.Length - 1)}\xA0";// replace last space with a hardspace // C2018-004 create meta file for baseline compares Volian.Base.Library.BaselineMetaFile.WriteLine(" PL x {0} y {1} {2} {3} {4} \"{5}\"", svgText.X, svgText.Y, svgText.FontFamily, svgText.FontSize, svgText.SVGFontStyle, TextForBaseline.FixText(svgText.Text)); return svgText; @@ -2948,8 +2498,8 @@ i = 0; System.Drawing.SizeF mySize = g.MeasureString(text, svgText.Font); while (mySize.Width > fontShrinkAftLen && tmpi > 8) { - tmpi = tmpi - 1; - svgText.FontSize = tmpi.ToString() + "PT"; + tmpi--; + svgText.FontSize = $"{tmpi}PT"; mySize = g.MeasureString(text, svgText.Font); } @@ -2976,9 +2526,11 @@ i = 0; } private SvgPart PageItemToSvgText(VEPROMS.CSLA.Library.PageItem pageItem, string text, float yOffset) { - SvgText svgText = new SvgText(); - svgText.Text = text; - VEPROMS.CSLA.Library.E_Justify justify = pageItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft; + SvgText svgText = new SvgText + { + Text = text + }; + VEPROMS.CSLA.Library.E_Justify justify = pageItem.Justify ?? VEPROMS.CSLA.Library.E_Justify.PSLeft; float colAdj16bit = 0; if ((justify & VEPROMS.CSLA.Library.E_Justify.PSLeft) == VEPROMS.CSLA.Library.E_Justify.PSLeft) svgText.Justify = SvgJustify.Left; @@ -3010,18 +2562,21 @@ i = 0; lcol = (lcol * 25) / dotsPerChar; } svgText.Font = pageItem.Font.WindowsFont; - svgText.X = new SvgMeasurement((float)lcol - colAdj16bit, E_MeasurementUnits.PT); // new SvgMeasurement((float)(pageItem.Col ?? 0), E_MeasurementUnits.PT); + svgText.X = new SvgMeasurement((float)lcol - colAdj16bit, E_MeasurementUnits.PT); svgText.Y = new SvgMeasurement((float)(yOffset + pageItem.Row ?? 0), E_MeasurementUnits.PT); - if (svgText.Font.Underline && svgText.Text.EndsWith(" ")) svgText.Text = svgText.Text.Substring(0, svgText.Text.Length - 1) + "\xA0";// replace last space with a hardspace + if (svgText.Font.Underline && svgText.Text.EndsWith(" ")) svgText.Text = $"{svgText.Text.Substring(0, svgText.Text.Length - 1)}\xA0";// replace last space with a hardspace // C2018-004 create meta file for baseline compares Volian.Base.Library.BaselineMetaFile.WriteLine(" PL x {0} y {1} {2} {3} {4} \"{5}\"", svgText.X, svgText.Y, svgText.FontFamily, svgText.FontSize, svgText.SVGFontStyle, TextForBaseline.FixText(svgText.Text)); return svgText; } - private SvgPart PageItemToSvgText(string token, float row, float col, E_Justify just, VE_Font font, string text, SectionInfo MySection) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping token for Debugging")] + private SvgPart PageItemToSvgText(string token, float row, float col, E_Justify just, VE_Font font, string text, SectionInfo MySection) { - SvgText svgText = new SvgText(); - svgText.Text = text; - VEPROMS.CSLA.Library.E_Justify justify = just; + SvgText svgText = new SvgText + { + Text = text + }; + VEPROMS.CSLA.Library.E_Justify justify = just; float colAdj16bit = 0; if ((justify & VEPROMS.CSLA.Library.E_Justify.PSLeft) == VEPROMS.CSLA.Library.E_Justify.PSLeft) svgText.Justify = SvgJustify.Left; @@ -3059,12 +2614,13 @@ i = 0; svgText.Font = font.WindowsFont; svgText.X = new SvgMeasurement((float)lcol - colAdj16bit, E_MeasurementUnits.PT); // new SvgMeasurement((float)(pageItem.Col ?? 0), E_MeasurementUnits.PT); svgText.Y = new SvgMeasurement(row, E_MeasurementUnits.PT); - if (svgText.Font.Underline && svgText.Text.EndsWith(" ")) svgText.Text = svgText.Text.Substring(0, svgText.Text.Length - 1) + "\xA0";// replace last space with a hardspace + if (svgText.Font.Underline && svgText.Text.EndsWith(" ")) svgText.Text = $"{svgText.Text.Substring(0, svgText.Text.Length - 1)}\xA0";// replace last space with a hardspace // C2018-004 create meta file for baseline compares Volian.Base.Library.BaselineMetaFile.WriteLine(" PL x {0} y {1} {2} {3} {4} \"{5}\"", svgText.X, svgText.Y, svgText.FontFamily, svgText.FontSize, svgText.SVGFontStyle, TextForBaseline.FixText(svgText.Text)); return svgText; } - private static List _MissingTokens = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _MissingTokens = new List(); protected override string ReplacePageListToken(Match match) { switch (match.Value) @@ -3110,26 +2666,6 @@ i = 0; return string.Empty; } } - public class ChkListBoxesHelper : List - { - private float _yOffsetStart; - private float _yOffsetEnd; - public ChkListBoxesHelper() - : base() - { - } - public void Add(ItemInfo myHls, float yoffStart, float yoffend) - { - Add(new ChkListBoxHelper()); - } - public void Draw() - { - foreach (ChkListBoxHelper cb in this) - { - - } - } - } public class ChkListBoxHelper { public ChkListBoxHelper() @@ -3151,40 +2687,17 @@ i = 0; } public class PageBookmark { - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo + public ItemInfo MyItemInfo { get; set; } + public string Title { get; set; } + public PdfDestination PdfDestination { get; set; } + public PageBookmark(ItemInfo itemInfo, string title, PdfDestination pdfDestination) { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } + MyItemInfo = itemInfo; + Title = title; + PdfDestination = pdfDestination; } - private string _Title; - public string Title - { - get { return _Title; } - set { _Title = value; } - } - private PdfDestination _PdfDestination; - public PdfDestination PdfDestination - { - get { return _PdfDestination; } - set { _PdfDestination = value; } - } - public PageBookmark(ItemInfo itemInfo, string title, PdfDestination pdfDestination) - { - _MyItemInfo = itemInfo; - _Title = title; - _PdfDestination = pdfDestination; - } - internal bool IsTopLevel - { - get - { - ItemInfo parent = MyItemInfo.ActiveParent as ItemInfo; - if (parent == null || parent.IsProcedure) return true; - return false; - } - } - internal int Level + internal bool IsTopLevel => !(MyItemInfo.ActiveParent is ItemInfo parent) || parent.IsProcedure; + internal int Level { get { @@ -3201,48 +2714,17 @@ i = 0; } public class ChangeBarDefinition // anything that is section level should go in here. { - private PrintChangeBar _MyChangeBarType; - public PrintChangeBar MyChangeBarType - { - get { return _MyChangeBarType; } - set { _MyChangeBarType = value; } - } - private PrintChangeBarLoc _MyChangeBarLoc; - public PrintChangeBarLoc MyChangeBarLoc - { - get { return _MyChangeBarLoc; } - set { _MyChangeBarLoc = value; } - } - private PrintChangeBarText _MyChangeBarText; - public PrintChangeBarText MyChangeBarText - { - get { return _MyChangeBarText; } - set { _MyChangeBarText = value; } - } - private string _MyChangeBarMessage; // user defined change bar message from docconfig - public string MyChangeBarMessage - { - get { return _MyChangeBarMessage; } - set { _MyChangeBarMessage = value; } - } - private int _MyChangeBarColumn; // two dimensional array, if both on same side, values are = - public int MyChangeBarColumn - { - get { return _MyChangeBarColumn; } - set { _MyChangeBarColumn = value; } - } - /* + public PrintChangeBar MyChangeBarType { get; set; } + public PrintChangeBarLoc MyChangeBarLoc { get; set; } + public PrintChangeBarText MyChangeBarText { get; set; } + public string MyChangeBarMessage { get; set; } + public int MyChangeBarColumn { get; set; } + /* * could have line thickness (set default from 16-bit), line color (set default as black), line style - */ - public ChangeBarDefinition() + */ + public ChangeBarDefinition() { } - public ChangeBarDefinition(PrintChangeBar myCBT, PrintChangeBarLoc myCBL, PrintChangeBarText myCBTxt, string myCBMsg) - { - _MyChangeBarType = myCBT; - _MyChangeBarLoc = myCBL; - _MyChangeBarText = myCBTxt; - } public ChangeBarDefinition(DocVersionConfig docverConfig, FormatInfo formatInfo) { // if there is not overridden data on the docversion, prompt user... @@ -3250,81 +2732,58 @@ i = 0; if (docverConfig == null || docverConfig.Print_ChangeBar == PrintChangeBar.SelectBeforePrinting) { // use these for now, i.e. this is what user would have selected from dialog. - _MyChangeBarType = PrintChangeBar.WithDefault; - _MyChangeBarLoc = PrintChangeBarLoc.OutsideBox; - _MyChangeBarText = PrintChangeBarText.None; + MyChangeBarType = PrintChangeBar.WithDefault; + MyChangeBarLoc = PrintChangeBarLoc.OutsideBox; + MyChangeBarText = PrintChangeBarText.None; } else { - _MyChangeBarType = docverConfig.Print_ChangeBar; - _MyChangeBarLoc = docverConfig.Print_ChangeBarLoc; - _MyChangeBarText = docverConfig.Print_ChangeBarText; + MyChangeBarType = docverConfig.Print_ChangeBar; + MyChangeBarLoc = docverConfig.Print_ChangeBarLoc; + MyChangeBarText = docverConfig.Print_ChangeBarText; } - if (_MyChangeBarType == PrintChangeBar.WithDefault) // get data from format + if (MyChangeBarType == PrintChangeBar.WithDefault) // get data from format { - _MyChangeBarText = changeBarData.ChangeBarMessage == "ChgID" ? PrintChangeBarText.ChgID : + MyChangeBarText = changeBarData.ChangeBarMessage == "ChgID" ? PrintChangeBarText.ChgID : changeBarData.ChangeBarMessage == "DateAndChgID" ? PrintChangeBarText.DateChgID : changeBarData.ChangeBarMessage == "None" ? PrintChangeBarText.None : changeBarData.ChangeBarMessage == "RevNum" ? PrintChangeBarText.RevNum : PrintChangeBarText.UserDef; } - if (_MyChangeBarType != PrintChangeBar.Without) + if (MyChangeBarType != PrintChangeBar.Without) { // if the format has the absolutefixedchangecolumn format flag, then always use the fixedchangecolumn from the // format, otherwise, use the default column based on the selected location, stored in the base format. - _MyChangeBarColumn = (changeBarData.AbsoluteFixedChangeColumn) ? + MyChangeBarColumn = (changeBarData.AbsoluteFixedChangeColumn) ? (int)changeBarData.FixedChangeColumn : - System.Convert.ToInt32(changeBarData.DefaultCBLoc.Split(",".ToCharArray())[(int)(_MyChangeBarLoc)]); - if (_MyChangeBarText == PrintChangeBarText.UserDef) - _MyChangeBarMessage = docverConfig.Print_UserCBMess1 + @"\n" + docverConfig.Print_UserCBMess2; + System.Convert.ToInt32(changeBarData.DefaultCBLoc.Split(",".ToCharArray())[(int)(MyChangeBarLoc)]); + if (MyChangeBarText == PrintChangeBarText.UserDef) + MyChangeBarMessage = docverConfig.Print_UserCBMess1 + @"\n" + docverConfig.Print_UserCBMess2; } } } public class CheckOffHeaderHelper { - private SvgText _SvgText; - public SvgText SvgText + public SvgText SvgText { get; set; } + public VEPROMS.CSLA.Library.VE_Font CheckOffHeaderFont { get; set; } + public CheckOffHeaderHelper(SvgText stext, VEPROMS.CSLA.Library.VE_Font vf) { - get { return _SvgText; } - set { _SvgText = value; } - } - private VEPROMS.CSLA.Library.VE_Font _CheckOffHeaderFont; - public VEPROMS.CSLA.Library.VE_Font CheckOffHeaderFont - { - get { return _CheckOffHeaderFont; } - set { _CheckOffHeaderFont = value; } - } - public CheckOffHeaderHelper(SvgText stext, VEPROMS.CSLA.Library.VE_Font vf) - { - _SvgText = stext; - _CheckOffHeaderFont = vf; + SvgText = stext; + CheckOffHeaderFont = vf; } } public class Gap { - private float _YTop; - public float YTop + public float YTop { get; set; } + public float YBottom { get; set; } + public Gap(float yTop, float yBottom) { - get { return _YTop; } - set { _YTop = value; } - } - private float _YBottom; - public float YBottom - { - get { return _YBottom; } - set { _YBottom = value; } - } - public Gap(float yTop, float yBottom) - { - _YTop = yTop; - _YBottom = yBottom; + YTop = yTop; + YBottom = yBottom; } } public class Gaps : List { - public void Add(float yTop, float yBotttom) - { - this.Add(new Gap(yTop, yBotttom)); - } - } + public void Add(float yTop, float yBotttom) => this.Add(new Gap(yTop, yBotttom)); + } } diff --git a/PROMS/Volian.Print.Library/Volian.Print.Library.csproj b/PROMS/Volian.Print.Library/Volian.Print.Library.csproj index d4694ccd..6c40776f 100644 --- a/PROMS/Volian.Print.Library/Volian.Print.Library.csproj +++ b/PROMS/Volian.Print.Library/Volian.Print.Library.csproj @@ -106,6 +106,7 @@ + diff --git a/PROMS/Volian.Print.Library/packages.config b/PROMS/Volian.Print.Library/packages.config index e28eb0be..449d67a4 100644 --- a/PROMS/Volian.Print.Library/packages.config +++ b/PROMS/Volian.Print.Library/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/PROMS/Volian.Print.Library/pdf.cs b/PROMS/Volian.Print.Library/pdf.cs index ccfbc88d..6ceb72de 100644 --- a/PROMS/Volian.Print.Library/pdf.cs +++ b/PROMS/Volian.Print.Library/pdf.cs @@ -1,46 +1,26 @@ using System; -using System.Collections.Generic; using System.Text; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; -using Microsoft.Win32; using Volian.Base.Library; namespace Volian.Print.Library { public class pdf { - private Document _MyDocument; - public Document MyDocument + public Document MyDocument { get; set; } + public PdfWriter MyWriter { get; set; } + public string MyFileName { get; set; } + public PdfContentByte ContentByte => MyWriter.DirectContent; + public pdf(string myFileName) { - get { return _MyDocument; } - set { _MyDocument = value; } - } - private PdfWriter _MyWriter; - public PdfWriter MyWriter - { - get { return _MyWriter; } - set { _MyWriter = value; } - } - private string _MyFileName; - public string MyFileName - { - get { return _MyFileName; } - set { _MyFileName = value; } - } - public PdfContentByte ContentByte - { - get { return _MyWriter.DirectContent; } - } - public pdf(string myFileName) - { - _MyFileName = myFileName; - _MyDocument = new Document(PageSize.LETTER); + MyFileName = myFileName; + MyDocument = new Document(PageSize.LETTER); try { - _MyWriter = PdfWriter.GetInstance(_MyDocument, new FileStream(myFileName, FileMode.Create)); - _MyWriter.SetAtLeastPdfVersion(PdfWriter.VERSION_1_7); + MyWriter = PdfWriter.GetInstance(MyDocument, new FileStream(myFileName, FileMode.Create)); + MyWriter.SetAtLeastPdfVersion(PdfWriter.VERSION_1_7); } catch (Exception ex) { @@ -49,24 +29,21 @@ namespace Volian.Print.Library } public pdf(string myFileName, Rectangle mySize) { - _MyFileName = myFileName; - _MyDocument = new Document(mySize); + MyFileName = myFileName; + MyDocument = new Document(mySize); try { - _MyWriter = PdfWriter.GetInstance(_MyDocument, new FileStream(myFileName, FileMode.Create)); - _MyWriter.SetAtLeastPdfVersion(PdfWriter.VERSION_1_7); + MyWriter = PdfWriter.GetInstance(MyDocument, new FileStream(myFileName, FileMode.Create)); + MyWriter.SetAtLeastPdfVersion(PdfWriter.VERSION_1_7); } catch (Exception ex) { Console.WriteLine("{0} - {1}\r\n{2}", ex.GetType().Name, ex.Message, ex.StackTrace); } } - public void Close() - { - MyDocument.Close(); - } - private Color _WatermarkColor = Color.BLUE; - private float _WatermarkOpacity = .10F; + public void Close() => MyDocument.Close(); + private readonly Color _WatermarkColor = Color.BLUE; + private readonly float _WatermarkOpacity = .10F; public void WatermarkPageNumber(int pageNumber) { Rectangle pageSize = ContentByte.PdfWriter.PageSize; // Get page size @@ -84,9 +61,11 @@ namespace Volian.Print.Library ContentByte.SetLineWidth(.5F); ContentByte.SetFontAndSize(myBasefont, myFontSize);// Set font and size ContentByte.SetColorStroke(_WatermarkColor); - PdfGState gs2 = new PdfGState(); - gs2.StrokeOpacity = _WatermarkOpacity; - ContentByte.SetGState(gs2); + PdfGState gs2 = new PdfGState + { + StrokeOpacity = _WatermarkOpacity + }; + ContentByte.SetGState(gs2); ContentByte.ShowTextAlignedKerned(PdfContentByte.ALIGN_CENTER, strPage, pageSize.Width / 2, 0, 0);// Draw the text ContentByte.EndText(); ContentByte.FillStroke(); // Controlled by TextRenderMode above @@ -108,9 +87,11 @@ namespace Volian.Print.Library { PdfPatternPainter myPatternPainter; myPatternPainter = ContentByte.CreatePattern(radius * 4, radius * 2, radius * 4, radius * 2); - PdfGState gState = new PdfGState(); - gState.FillOpacity = _WatermarkOpacity; - myPatternPainter.SetGState(gState); + PdfGState gState = new PdfGState + { + FillOpacity = _WatermarkOpacity + }; + myPatternPainter.SetGState(gState); myPatternPainter.SetColorFill(_WatermarkColor); myPatternPainter.Rectangle(0, 0, radius, radius); myPatternPainter.Rectangle(radius * 2, radius, radius, radius); diff --git a/PROMS/Volian.Print.Library/pkParagraph.cs b/PROMS/Volian.Print.Library/pkParagraph.cs index 0a57b8c3..4a6f8d53 100644 --- a/PROMS/Volian.Print.Library/pkParagraph.cs +++ b/PROMS/Volian.Print.Library/pkParagraph.cs @@ -1,27 +1,16 @@ -using System; using System.Collections.Generic; -using System.Text; namespace Volian.Print.Library { public class pkParagraph { - private vlnParagraph _MyParagraph; - public vlnParagraph MyParagraph - { - get { return _MyParagraph; } - } - private pkParagraphs _MyChildren; - public pkParagraphs MyChildren - { - get { return _MyChildren; } - } - private pkParagraphs _MyCautionsAndNotes; - public pkParagraphs MyCautionsAndNotes - { - get { return _MyCautionsAndNotes; } - } - public pkParagraph(vlnParagraph myParagraph) + private readonly vlnParagraph _MyParagraph; + public vlnParagraph MyParagraph => _MyParagraph; + private readonly pkParagraphs _MyChildren; + public pkParagraphs MyChildren => _MyChildren; + private readonly pkParagraphs _MyCautionsAndNotes; + public pkParagraphs MyCautionsAndNotes => _MyCautionsAndNotes; + public pkParagraph(vlnParagraph myParagraph) { _MyParagraph = myParagraph; _MyChildren = new pkParagraphs(); diff --git a/PROMS/Volian.Print.Library/vlnBox.cs b/PROMS/Volian.Print.Library/vlnBox.cs index 4ea37c80..9a7b514e 100644 --- a/PROMS/Volian.Print.Library/vlnBox.cs +++ b/PROMS/Volian.Print.Library/vlnBox.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Text; using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text; using VEPROMS.CSLA.Library; @@ -12,23 +11,11 @@ namespace Volian.Print.Library public partial class vlnBox : vlnPrintObject { private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private int _LineType; /* how to represent?? */ - private System.Drawing.Color _Color; - public System.Drawing.Color Color - { - get { return _Color; } - set { _Color = value; } - } - private Box _MyBox; - public Box MyBox - { - get { return _MyBox; } - set { _MyBox = value; } - } - // the following two fields are used if 'boxed' step, thus - // no 'Box' was defined in format file. - public override float Height + public Box MyBox { get; set; } + // the following two fields are used if 'boxed' step, thus + // no 'Box' was defined in format file. + public override float Height { get { @@ -41,26 +28,13 @@ namespace Volian.Print.Library public string DefBox = null; public float DefEnd = 0; - private bool _ContainsPageBreak = false; - public bool ContainsPageBreak - { - get { return _ContainsPageBreak; } - set { _ContainsPageBreak = value; } - } - private bool _DoubleBoxHls = false; // BGE double lined box around HLS - public bool DoubleBoxHls - { - get { return _DoubleBoxHls; } - set { _DoubleBoxHls = value; } - } - public const string DOUBLEboxHLS = "DoubleBox"; + public bool ContainsPageBreak { get; set; } = false; + public bool DoubleBoxHls { get; set; } = false; + public const string DOUBLEboxHLS = "DoubleBox"; //private bool _DoBottom = true; public vlnBox() { } - public vlnBox(vlnParagraph paragraph) - { - } public const string BoxThin = "\x2510.\x2500.\x250c.\x2502. . .\x2518.\x2514. .\x2500. . "; const string BoxThick = "\x2584.\x2584.\x2584.\x2588. . .\x2580.\x2580. .\x2580. . "; const string BoxDouble = "\x2557.\x2550.\x2554.\x2551. . .\x255D.\x255A. .\x2550. . "; @@ -95,10 +69,9 @@ namespace Volian.Print.Library if (MyBox == null) return yPageStart; cb.SaveState(); VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; + PdfLayer textLayer = _MyPageHelper?.TextLayer; if (textLayer != null) cb.BeginLayer(textLayer); MyContentByte = cb; - //Console.WriteLine("'{0}','{1}'", CharToAsc(MyBox.BoxStyle), MyParent.MyItemInfo.ShortPath); float top = CalculateYOffset(yPageStart, yTopMargin) - (7*MyPageHelper.YMultiplier); float bottom = top - (Height * MyPageHelper.YMultiplier); float left = (float)((MyBox.Start ?? 0) + MyParent.MyItemInfo.MyDocStyle.Layout.LeftMargin); @@ -157,7 +130,7 @@ namespace Volian.Print.Library else { const float llxOffset = 3; - float lineThickness = 0; + float lineThickness; switch (MyBox.BoxStyle) { case BoxThin: @@ -331,23 +304,23 @@ namespace Volian.Print.Library // create a new font without any styles such as underline. E_Style es = ((vef.Style & E_Style.Bold) == E_Style.Bold) ? E_Style.Bold : E_Style.None; - // if the box has a font, use it - otherwise use this item info's font - VE_Font vf = null; - bool UseBoxFont = false; - try + bool UseBoxFont = false; + try { UseBoxFont = MyParent.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox; } catch // done this way in case one of the format properties is null in the previous statement, UseBoxFont will be false. { } - if (UseBoxFont) - vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - else - vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + // if the box has a font, use it - otherwise use this item info's font + VE_Font vf; + if (UseBoxFont) + vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + else + vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - // To find the length of the line, account for the length of the upper right corner also (BXURC) - int urcLen = MyBox.BXHorz[MyBox.BXHorz.Length - 1] == ' ' && MyBox.BXURC[0] == ' ' ? 1 : MyBox.BXURC.Length; + // To find the length of the line, account for the length of the upper right corner also (BXURC) + int urcLen = MyBox.BXHorz[MyBox.BXHorz.Length - 1] == ' ' && MyBox.BXURC[0] == ' ' ? 1 : MyBox.BXURC.Length; float endHorz = (float)MyBox.End - (float)MyBox.Start - (float)(urcLen * (72 / vf.CPI)); float bxHorzTextWidth = GetTextWidth(vf, MyBox.BXHorz); // get the width of the BXHorz string @@ -355,21 +328,21 @@ namespace Volian.Print.Library StringBuilder sb = new StringBuilder(); sb.Append(MyBox.BXULC); float size = GetTextWidth(vf, MyBox.BXULC); //(float)(MyBox.BXULC.Length * (72 / vf.CPI)); - string bxstr = null; - if (!ContainsPageBreak) // Only do top line if there is no page break. + string bxstr; + if (!ContainsPageBreak) // Only do top line if there is no page break. { while (size < endHorz) { sb.Append(MyBox.BXHorz); - size = size + bxHorzTextWidth; //(float)(MyBox.BXHorz.Length * (72 / vf.CPI)); + size += bxHorzTextWidth; //(float)(MyBox.BXHorz.Length * (72 / vf.CPI)); } // Tack on the right upper corner. For some formats, the upper right corner in the // had the first character as a space, this would put two spaces in a row at the // end of the string, so remove the space before tacking on the upper right corner: bxstr = sb.ToString(); if (bxstr[bxstr.Length - 1] == ' ' && MyBox.BXURC[0] == ' ') bxstr = bxstr.TrimEnd(); - bxstr = bxstr + MyBox.BXURC; - size = size + GetTextWidth(vf, MyBox.BXURC);//(float)((MyBox.BXURC.Length) * (72 / vf.CPI)); + bxstr += MyBox.BXURC; + size += GetTextWidth(vf, MyBox.BXURC);//(float)((MyBox.BXURC.Length) * (72 / vf.CPI)); Rtf = GetRtf(bxstr, vf); IParagraph = null; // set to null so that next access of IParagraph sets the Rtf. Rtf2Pdf.TextAt(cb, IParagraph, left, top, size + 10, 100, "", yBottomMargin); @@ -384,15 +357,15 @@ namespace Volian.Print.Library while (size < endHorz) { sb.Append(MyBox.BXHorz); - size = size + bxHorzTextWidth;//(float)(MyBox.BXHorz.Length * (72 / vf.CPI)); + size += bxHorzTextWidth;//(float)(MyBox.BXHorz.Length * (72 / vf.CPI)); } bxstr = sb.ToString().TrimEnd() + MyBox.BXLRC; - size = size + GetTextWidth(vf, MyBox.BXLRC); //(float)((MyBox.BXLRC.Length) * (72 / vf.CPI)); + size += GetTextWidth(vf, MyBox.BXLRC); //(float)((MyBox.BXLRC.Length) * (72 / vf.CPI)); Rtf = GetRtf(bxstr, vf); IParagraph = null; // set to null so that next access of IParagraph sets the Rtf. Rtf2Pdf.TextAt(cb, IParagraph, left, bottom, size + 10, 100, "", yBottomMargin); } - private string symblsStr = "\u25CF\u0394"; // string of possible symbol character in a tab + private readonly string symblsStr = "\u25CF\u0394"; // string of possible symbol character in a tab // add symbol characters as needed // "\u25CF" - solid bullet // \x0394 - delta @@ -409,8 +382,6 @@ namespace Volian.Print.Library // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle - //System.Drawing.Font font = new System.Drawing.Font(vefont.Family, (float)vefont.Size, GetSysFontStyle(vefont)); - //System.Drawing.Font symbFont = new System.Drawing.Font(symblFontName, (float)vefont.Size); System.Drawing.Font font = VE_Font.GetWinSysFont(vefont.Family, (float)vefont.Size, GetSysFontStyle(vefont)); System.Drawing.Font symbFont = VE_Font.GetWinSysFont(symblFontName, (float)vefont.Size); iTextSharp.text.Font iFont = Volian.Svg.Library.VolianPdf.GetFont(font); @@ -424,10 +395,10 @@ namespace Volian.Print.Library else w += iFont.BaseFont.GetWidthPointKerned(c.ToString(), (float)vefont.Size); } - //float w = iFont.BaseFont.GetWidthPointKerned(Text.Replace("\u25CF","@"), (float)vefont.Size); return w; } - private void DrawAsteriskSide(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin, float top, float bottom, float left, float right, VE_Font vef) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "top and bottom kept for debugging")] + private void DrawAsteriskSide(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin, float top, float bottom, float left, float right, VE_Font vef) { // set the top & bottom of sides. If there is a page break in the middle of box, adjust these. // The vlnBox property, ContainsPageBreak, flags that a break occurred. @@ -453,23 +424,23 @@ namespace Volian.Print.Library // create a new font without any styles such as underline. E_Style es = ((vef.Style & E_Style.Bold) == E_Style.Bold) ? E_Style.Bold : E_Style.None; - // if the box has a font, use it - otherwise use this item info's font - VE_Font vf = null; - bool UseBoxFont = false; - try + bool UseBoxFont = false; + try { UseBoxFont = MyParent.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox; } catch // done this way in case one of the format properties is null in the previous statement, UseBoxFont will be false. { } - if (UseBoxFont) - vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - else - vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + // if the box has a font, use it - otherwise use this item info's font + VE_Font vf; + if (UseBoxFont) + vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + else + vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - // Left side first: - Rtf = GetRtf(MyBox.BXVert, vf); + // Left side first: + Rtf = GetRtf(MyBox.BXVert, vf); IParagraph = null; // set to null so that next access of IParagraph sets the Rtf. // start down one line because the top/bottom code draws the corner float vertDiff = top - (SixLinesPerInch * MyPageHelper.YMultiplier); @@ -503,17 +474,8 @@ namespace Volian.Print.Library } return sb.ToString(); } - private static List _UnimplementedBoxStyles = new List(); - private string CharToAsc(string p) - { - StringBuilder sb = new StringBuilder(); - foreach (char c in p) - { - if (c >= ' ' && c < 127) sb.Append(c); - else sb.Append(string.Format("\\x{0:x}", (int)c)); - } - return sb.ToString(); - } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List _UnimplementedBoxStyles = new List(); private void DrawAsteriskTopBottomHLS(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin, ref float top, ref float bottom, float left, VE_Font vef) { // this box is not drawn, it is a series of asterisks drawn above and below text. @@ -527,45 +489,45 @@ namespace Volian.Print.Library bottom = ytmpbottom1; // create a new font without any styles such as underline. E_Style es = ((vef.Style & E_Style.Bold) == E_Style.Bold) ? E_Style.Bold : E_Style.None; - // if the box has a font, use it - otherwise use this item info's font - VE_Font vf = null; - bool UseBoxFont = false; - try + bool UseBoxFont = false; + try { UseBoxFont = MyParent.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox; } catch // done this way in case one of the format properties is null in the previous statement, UseBoxFont will be false. { } - if (UseBoxFont) - vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - else - vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + // if the box has a font, use it - otherwise use this item info's font + VE_Font vf; + if (UseBoxFont) + vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + else + vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - // To find the length of the line, account for the length of the upper right corner also (BXURC) - int urcLen = MyBox.BXHorz[MyBox.BXHorz.Length - 1] == ' ' && MyBox.BXURC[0] == ' ' ? 1 : MyBox.BXURC.Length; + // To find the length of the line, account for the length of the upper right corner also (BXURC) + int urcLen = MyBox.BXHorz[MyBox.BXHorz.Length - 1] == ' ' && MyBox.BXURC[0] == ' ' ? 1 : MyBox.BXURC.Length; float endHorz = (float)MyBox.End - (float)MyBox.Start - (float)(urcLen * (72 / vf.CPI)); float bxHorzTextWidth = GetTextWidth(vf, MyBox.BXHorz); // get the width of the BXHorz string // Do the top line first: StringBuilder sb = new StringBuilder(); sb.Append(MyBox.BXULC); - float size = GetTextWidth(vf, MyBox.BXULC); //(float)(MyBox.BXULC.Length * (72 / vf.CPI)); - string bxstr = null; - if (!ContainsPageBreak) // Only do top line if there is no page break. + float size = GetTextWidth(vf, MyBox.BXULC); + string bxstr; + if (!ContainsPageBreak) // Only do top line if there is no page break. { while (size < endHorz) { sb.Append(MyBox.BXHorz); - size = size + bxHorzTextWidth; //(float)(MyBox.BXHorz.Length * (72 / vf.CPI)); + size += bxHorzTextWidth; } // Tack on the right upper corner. For some formats, the upper right corner in the // had the first character as a space, this would put two spaces in a row at the // end of the string, so remove the space before tacking on the upper right corner: bxstr = sb.ToString(); if (bxstr[bxstr.Length - 1] == ' ' && MyBox.BXURC[0] == ' ') bxstr = bxstr.TrimEnd(); - bxstr = bxstr + MyBox.BXURC; - size = size + GetTextWidth(vf, MyBox.BXURC);//(float)((MyBox.BXURC.Length) * (72 / vf.CPI)); + bxstr += MyBox.BXURC; + size += GetTextWidth(vf, MyBox.BXURC);//(float)((MyBox.BXURC.Length) * (72 / vf.CPI)); Rtf = GetRtf(bxstr, vf); IParagraph = null; // set to null so that next access of IParagraph sets the Rtf. Rtf2Pdf.TextAt(cb, IParagraph, left, top, size + 10, 100, "", yBottomMargin); @@ -576,24 +538,25 @@ namespace Volian.Print.Library sb.Remove(0, sb.Length); sb.Append(MyBox.BXLLC); - size = GetTextWidth(vf, MyBox.BXLLC); //(float)(MyBox.BXLLC.Length * (72 / vf.CPI)); + size = GetTextWidth(vf, MyBox.BXLLC); while (size < endHorz) { sb.Append(MyBox.BXHorz); - size = size + bxHorzTextWidth;//(float)(MyBox.BXHorz.Length * (72 / vf.CPI)); + size += bxHorzTextWidth; } bxstr = sb.ToString().TrimEnd() + MyBox.BXLRC; - size = size + GetTextWidth(vf, MyBox.BXLRC); //(float)((MyBox.BXLRC.Length) * (72 / vf.CPI)); + size += GetTextWidth(vf, MyBox.BXLRC); Rtf = GetRtf(bxstr, vf); IParagraph = null; // set to null so that next access of IParagraph sets the Rtf. Rtf2Pdf.TextAt(cb, IParagraph, left, bottom, size + 10, 100, "", yBottomMargin); } - private void DrawAsteriskSideHLS(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin, float top, float bottom, float left, float right, VE_Font vef) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "top and bottom kept for debugging")] + private void DrawAsteriskSideHLS(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin, float top, float bottom, float left, float right, VE_Font vef) { - // set the top & bottom of sides. If there is a page break in the middle of box, adjust these. - // The vlnBox property, ContainsPageBreak, flags that a break occurred. - float yOffBreak = 0; - if (!ContainsPageBreak) + // set the top & bottom of sides. If there is a page break in the middle of box, adjust these. + // The vlnBox property, ContainsPageBreak, flags that a break occurred. + float yOffBreak; + if (!ContainsPageBreak) { top = CalculateYOffset(yPageStart, yTopMargin); if (MyPageHelper.YMultiplier != 1) top += 2; @@ -613,8 +576,11 @@ namespace Volian.Print.Library } else { - top = CalculateYOffset(yPageStart, yTopMargin); - yOffBreak = MyPageHelper.ParaBreaks.Count > 0 ? MyPageHelper.ParaBreaks[0].YOffset : 0; + +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Keeping top for Debugging + top = CalculateYOffset(yPageStart, yTopMargin); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + yOffBreak = MyPageHelper.ParaBreaks.Count > 0 ? MyPageHelper.ParaBreaks[0].YOffset : 0; if (yOffBreak > 0) bottom = (yPageStart - yOffBreak) * MyPageHelper.YMultiplier; else @@ -636,23 +602,23 @@ namespace Volian.Print.Library // create a new font without any styles such as underline. E_Style es = ((vef.Style & E_Style.Bold) == E_Style.Bold) ? E_Style.Bold : E_Style.None; - // if the box has a font, use it - otherwise use this item info's font - VE_Font vf = null; - bool UseBoxFont = false; - try + bool UseBoxFont = false; + try { UseBoxFont = MyParent.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox; } catch // done this way in case one of the format properties is null in the previous statement, UseBoxFont will be false. { } - if (UseBoxFont) - vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - else - vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + // if the box has a font, use it - otherwise use this item info's font + VE_Font vf; + if (UseBoxFont) + vf = new VE_Font(vef.Family, (int)vef.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); + else + vf = new VE_Font(MyParent.MyItemInfo.FormatStepData.Font.Family, (int)MyParent.MyItemInfo.FormatStepData.Font.Size, es, (float)MyParent.MyItemInfo.FormatStepData.Font.CPI); - // Left side first: - Rtf = GetRtf(MyBox.BXVert, vf); + // Left side first: + Rtf = GetRtf(MyBox.BXVert, vf); IParagraph = null; // set to null so that next access of IParagraph sets the Rtf. // start down one line because the top/bottom code draws the corner float vertDiff = top - (SixLinesPerInch * MyPageHelper.YMultiplier); diff --git a/PROMS/Volian.Print.Library/vlnChangeBar.cs b/PROMS/Volian.Print.Library/vlnChangeBar.cs index 4c23968a..f1ae997a 100644 --- a/PROMS/Volian.Print.Library/vlnChangeBar.cs +++ b/PROMS/Volian.Print.Library/vlnChangeBar.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; -using System.Drawing; using iTextSharp.text.pdf; using iTextSharp.text; using VEPROMS.CSLA.Library; @@ -10,45 +8,26 @@ namespace Volian.Print.Library { public class vlnChangeBarMessage { - private float _ParentX; - public float ParentX - { - get { return _ParentX; } - set { _ParentX = value; } - } - private string _Message; - public string Message - { - get { return _Message; } - set { _Message = value; } - } - private static int _UniqueMessageId = 0; + public float ParentX { get; set; } + public string Message { get; set; } + private static int _UniqueMessageId = 0; public static int UniqueMessageId { - get { return vlnChangeBarMessage._UniqueMessageId++; } - set { vlnChangeBarMessage._UniqueMessageId = value; } + get { return _UniqueMessageId++; } + set { _UniqueMessageId = value; } } - private int _MessageId = UniqueMessageId; - public int MessageId + + public int MessageId { get; set; } = UniqueMessageId; + public vlnChangeBarMessage(float parentx, string msg) { - get { return _MessageId; } - set { _MessageId = value; } - } - public vlnChangeBarMessage(float parentx, string msg) - { - _ParentX = parentx; - _Message = msg; + ParentX = parentx; + Message = msg; } } public partial class vlnChangeBar : vlnPrintObject { - private bool _HasChangeBar; - public bool HasChangeBar - { - get { return _HasChangeBar; } - set { _HasChangeBar = value; } - } - protected float _YChangeBarBottom; + public bool HasChangeBar { get; set; } + protected float _YChangeBarBottom; public float YChangeBarBottom { get @@ -62,36 +41,15 @@ namespace Volian.Print.Library _Height = _YOffset - _YChangeBarBottom; } } - private SortedDictionary _Messages; - public SortedDictionary Messages - { - get { return _Messages; } - set { _Messages = value; } - } - private int _MessageAlignment; - public int MessageAlignment - { - get { return _MessageAlignment; } - set { _MessageAlignment = value; } - } - private float _YExtendLine = 4.75F; - public float YExtendLine - { - get { return _YExtendLine; } - set {_YExtendLine = value; } - } - public float YChangeBarBottomExtend - { - get {return YChangeBarBottom - YExtendLine; } - } - private bool _BottomIsTable = false; - public bool BottomIsTable - { - get { return _BottomIsTable; } - set { _BottomIsTable = value; } - } - private bool _IsRev; - private bool _MsgAtTop; // flags that message should be drawn at top of change bar + + public SortedDictionary Messages { get; set; } + public int MessageAlignment { get; set; } + public float YExtendLine { get; set; } = 4.75F; + public float YChangeBarBottomExtend => YChangeBarBottom - YExtendLine; + + public bool BottomIsTable { get; set; } = false; + private readonly bool _IsRev; + private readonly bool _MsgAtTop; // flags that message should be drawn at top of change bar public vlnChangeBar(PdfContentByte cb, vlnParagraph parent, float xoff, float yoff, int msgAlignment, bool isRev, bool msgAtTop) { // for grids, a y adjustment is made to match 16bit output, see the variable 'GridTopAdjust'. Take this @@ -113,7 +71,7 @@ namespace Volian.Print.Library { // see if any of children don't have changebar if ((vpo as vlnRNOSeparator).ExtendChangeBar) - _YExtendLine = (vpo.Height + vpo.YOffset - ((scale * parent.Height) + parent.YOffset)) * MyPageHelper.YMultiplier; + YExtendLine = (vpo.Height + vpo.YOffset - ((scale * parent.Height) + parent.YOffset)) * MyPageHelper.YMultiplier; } } foreach (vlnPrintObject vph in parent.PartsAbove) @@ -152,13 +110,10 @@ namespace Volian.Print.Library } } } - _MessageAlignment = msgAlignment; + MessageAlignment = msgAlignment; } - public override string ToString() - { - return string.Format("vlnChangeBar: X={0} Y={1} H={2} B={3} ID={4}", XOffset, YOffset, Height, YChangeBarBottom, MyParent.MyItemInfo.ItemID); - } - public override float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) + public override string ToString() => string.Format("vlnChangeBar: X={0} Y={1} H={2} B={3} ID={4}", XOffset, YOffset, Height, YChangeBarBottom, MyParent.MyItemInfo.ItemID); + public override float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) { float? topMost = null; cb.SaveState(); @@ -170,12 +125,10 @@ namespace Volian.Print.Library // calculate a new starting position for the change bar if (_MyParent is vlnParagraph) { - vlnParagraph pgh = _MyParent as vlnParagraph; topMost = cb.PdfWriter.PageSize.Height - yPageStart; } - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; - if (textLayer != null) cb.BeginLayer(textLayer); + PdfLayer textLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.TextLayer; + if (textLayer != null) cb.BeginLayer(textLayer); float yAdj = -3.75F; //0.5F; float xAdj = 3F; //cb.SetColorStroke(Color.GREEN); @@ -226,8 +179,6 @@ namespace Volian.Print.Library // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B21017-117 - //iTextSharp.text.Font iFont = _IsRev? Volian.Svg.Library.VolianPdf.GetFont(new System.Drawing.Font("Letter Gothic", 10F)): - // Volian.Svg.Library.VolianPdf.GetFont(new System.Drawing.Font("Letter Gothic", 5.5F)); iTextSharp.text.Font iFont = _IsRev? Volian.Svg.Library.VolianPdf.GetFont(VE_Font.GetWinSysFont("Letter Gothic", 10F)): Volian.Svg.Library.VolianPdf.GetFont(VE_Font.GetWinSysFont("Letter Gothic", 5.5F)); diff --git a/PROMS/Volian.Print.Library/vlnHeader.cs b/PROMS/Volian.Print.Library/vlnHeader.cs index a7234ee4..59653797 100644 --- a/PROMS/Volian.Print.Library/vlnHeader.cs +++ b/PROMS/Volian.Print.Library/vlnHeader.cs @@ -1,21 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text; using VEPROMS.CSLA.Library; namespace Volian.Print.Library { public partial class vlnHeader: vlnText { - private string _OrigStr; - public float HeaderWidth - { - get { return _WidthAdjust + (MyFont.CharsToTwips * Text.Length); } - } - public vlnHeader(vlnParagraph myParent, PdfContentByte cb, string origStr, string cleanStr, float xoffset, float yoffset, VE_Font vFont) + private readonly string _OrigStr; + public float HeaderWidth => _WidthAdjust + (MyFont.CharsToTwips * Text.Length); + public vlnHeader(vlnParagraph myParent, PdfContentByte cb, string origStr, string cleanStr, float xoffset, float yoffset, VE_Font vFont) { MyParent = myParent; MyContentByte = cb; diff --git a/PROMS/Volian.Print.Library/vlnMacro.cs b/PROMS/Volian.Print.Library/vlnMacro.cs index f701f3ca..5e62e3c5 100644 --- a/PROMS/Volian.Print.Library/vlnMacro.cs +++ b/PROMS/Volian.Print.Library/vlnMacro.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text; -using VEPROMS.CSLA.Library; namespace Volian.Print.Library { @@ -13,13 +7,8 @@ namespace Volian.Print.Library private bool _UseInternalY = false; // B2020-121: Account for Header on Caution or Note public bool UseInternalY { get => _UseInternalY; set => _UseInternalY = value; } - private string _MacroDef; - public string MacroDef - { - get { return _MacroDef; } - set { _MacroDef = value; } - } - public vlnMacro(float xoffset, float yoffset, string macroDef) + public string MacroDef { get; set; } + public vlnMacro(float xoffset, float yoffset, string macroDef) { YOffset = yoffset; XOffset = xoffset; @@ -33,9 +22,8 @@ namespace Volian.Print.Library if (UseInternalY) yLocation = YOffset; // B2020-121: Account for Header on Caution or Note // Adjust the starting point for the Macro if the LPI is 7 if (MyPageHelper.YMultiplier != 1) yLocation += SixLinesPerInch - _SevenLinesPerInch; - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; - if (textLayer != null) cb.BeginLayer(textLayer); + PdfLayer textLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.TextLayer; + if (textLayer != null) cb.BeginLayer(textLayer); MyContentByte = cb; System.Drawing.Color push = PrintOverride.SvgColor; PrintOverride.SvgColor = PrintOverride.TextColor == System.Drawing.Color.Empty ? System.Drawing.Color.Black : PrintOverride.TextColor; diff --git a/PROMS/Volian.Print.Library/vlnParagraph.cs b/PROMS/Volian.Print.Library/vlnParagraph.cs index 74bf0c8c..a8c939e0 100644 --- a/PROMS/Volian.Print.Library/vlnParagraph.cs +++ b/PROMS/Volian.Print.Library/vlnParagraph.cs @@ -1,99 +1,69 @@ +using iTextSharp.text; +using iTextSharp.text.pdf; using System; using System.Collections.Generic; +using System.IO; +using System.Linq; using System.Text; using System.Text.RegularExpressions; -using System.IO; -using iTextSharp.text.pdf; -using iTextSharp.text; -using Volian.Controls.Library; using VEPROMS.CSLA.Library; using Volian.Base.Library; +using Volian.Controls.Library; namespace Volian.Print.Library { - public partial class vlnParagraphs : List - { - private vlnParagraph _Parent; - public vlnParagraph Parent - { - get { return _Parent; } - set { _Parent = value; } - } - public vlnParagraphs(vlnParagraph parent) - { - _Parent = parent; - } - // Step Designators are used by Comanche Peak and stored in their CAUTION2 type - // We need to save this information and not process it like a normal Caution. - private string _StepDesignator; - public string StepDesignator - { - get { return _StepDesignator; } - set { _StepDesignator = value; } - } - private float? _StepDesignatorColumn; + public partial class vlnParagraphs : List + { + public vlnParagraph Parent { get; set; } + public vlnParagraphs(vlnParagraph parent) + { + Parent = parent; + } - public float? StepDesignatorColumn - { - get { return _StepDesignatorColumn; } - set { _StepDesignatorColumn = value; } - } - private VE_Font _StepDesignatorFont; + public string StepDesignator { get; set; } - public VE_Font StepDesignatorFont - { - get { return _StepDesignatorFont; } - set { _StepDesignatorFont = value; } - } + public float? StepDesignatorColumn { get; set; } - public bool IsEnhancedBackgroundFormat(ItemInfo itminfo) - { - return ((itminfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds); - } - public bool IsEnhancedDeviationFormat(ItemInfo itminfo) - { - return ((itminfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations); - } - public float Add(PdfContentByte cb, ItemInfoList itemInfoList, float xoff, float yoff, float yoffRight, int rnoLevel, int maxRNO, FormatInfo formatInfo) - { - return Add(cb, itemInfoList, xoff, yoff, yoffRight, rnoLevel, maxRNO, formatInfo, null); - } - public float Add(PdfContentByte cb, ItemInfoList itemInfoList, float xoff, float yoff, float yoffRight, int rnoLevel, int maxRNO, FormatInfo formatInfo, PromsPrinter pp) - { - int profileDepth = ProfileTimer.Push(">>>> vlnParagraphs.Add"); - bool bxHlsDraw = false; - int? bxIndex = null; - vlnBox box = null; - float yTop = yoff; - ItemInfo lastChild = null; - string lastHeader = null; - bool didComponentTableRow = false; - float tableBottomMost = 0; - float xoffBase = xoff; - int prevTplRow = 0; - int maxRnoSav = maxRNO; - foreach (ItemInfo iChildItemInfo in itemInfoList) - { - if (pp != null) pp.OnStatusChanged((iChildItemInfo.DisplayNumber ?? "") == "" ? iChildItemInfo.DisplayText : iChildItemInfo.DisplayNumber, PromsPrinterStatusType.LoadVlnParagraph); - if (iChildItemInfo.IsFootnote) - { - vlnParagraph para = new vlnParagraph(Parent, cb, iChildItemInfo, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRight, true, iChildItemInfo.IsSection ? pp : null); - continue; // don't add it, vlnParagraph adds this item to the footnote list in ToPdf. - } - maxRNO = maxRnoSav; - if (iChildItemInfo.IsHigh) bxIndex = null; - if (iChildItemInfo.IsSection && (iChildItemInfo as SectionInfo).ColumnMode != maxRNO) - maxRNO = (iChildItemInfo as SectionInfo).ColumnMode; - int maxRnoTemplate = iChildItemInfo.TemplateChildColumnMode; - if (maxRnoTemplate >= 0) maxRNO = maxRnoTemplate - 1; - ItemInfo childItemInfo = iChildItemInfo; - int? bxIndx = childItemInfo.FormatStepData == null ? -1 : childItemInfo.FormatStepData.StepLayoutData.STBoxindex; - // if the Caution or Note is not boxed, then use ColT to set the starting column of the Note or Caution - if (((bxIndx ?? -1) == -1) && (childItemInfo.IsCaution || childItemInfo.IsNote) && !childItemInfo.IsInRNO && - !childItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.Dev_Format && - !IsEnhancedBackgroundFormat(childItemInfo) && !IsEnhancedDeviationFormat(childItemInfo)) - //xoff += (float)childItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColT; - xoff = xoffBase + (float)childItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColT; + public VE_Font StepDesignatorFont { get; set; } + + public bool IsEnhancedBackgroundFormat(ItemInfo itminfo) => ((itminfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds); + public bool IsEnhancedDeviationFormat(ItemInfo itminfo) => ((itminfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations); + public float Add(PdfContentByte cb, ItemInfoList itemInfoList, float xoff, float yoff, float yoffRight, int rnoLevel, int maxRNO, FormatInfo formatInfo) => Add(cb, itemInfoList, xoff, yoff, yoffRight, rnoLevel, maxRNO, formatInfo, null); + public float Add(PdfContentByte cb, ItemInfoList itemInfoList, float xoff, float yoff, float yoffRight, int rnoLevel, int maxRNO, FormatInfo formatInfo, PromsPrinter pp) + { + int profileDepth = ProfileTimer.Push(">>>> vlnParagraphs.Add"); + bool bxHlsDraw = false; + int? bxIndex = null; + vlnBox box = null; + ItemInfo lastChild = null; + string lastHeader = null; + bool didComponentTableRow = false; + float tableBottomMost = 0; + float xoffBase = xoff; + int prevTplRow = 0; + int maxRnoSav = maxRNO; + foreach (ItemInfo iChildItemInfo in itemInfoList) + { + pp?.OnStatusChanged((iChildItemInfo.DisplayNumber ?? "") == "" ? iChildItemInfo.DisplayText : iChildItemInfo.DisplayNumber, PromsPrinterStatusType.LoadVlnParagraph); + if (iChildItemInfo.IsFootnote) + { + vlnParagraph para = new vlnParagraph(Parent, cb, iChildItemInfo, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRight, true, iChildItemInfo.IsSection ? pp : null); + continue; // don't add it, vlnParagraph adds this item to the footnote list in ToPdf. + } + maxRNO = maxRnoSav; + if (iChildItemInfo.IsHigh) bxIndex = null; + if (iChildItemInfo.IsSection && (iChildItemInfo as SectionInfo).ColumnMode != maxRNO) + maxRNO = (iChildItemInfo as SectionInfo).ColumnMode; + int maxRnoTemplate = iChildItemInfo.TemplateChildColumnMode; + if (maxRnoTemplate >= 0) maxRNO = maxRnoTemplate - 1; + ItemInfo childItemInfo = iChildItemInfo; + int? bxIndx = childItemInfo.FormatStepData == null ? -1 : childItemInfo.FormatStepData.StepLayoutData.STBoxindex; + // if the Caution or Note is not boxed, then use ColT to set the starting column of the Note or Caution + if (((bxIndx ?? -1) == -1) && (childItemInfo.IsCaution || childItemInfo.IsNote) && !childItemInfo.IsInRNO && + !childItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.Dev_Format && + !IsEnhancedBackgroundFormat(childItemInfo) && !IsEnhancedDeviationFormat(childItemInfo)) + //xoff += (float)childItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColT; + xoff = xoffBase + (float)childItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColT; // if in a ComponentTableFormat (FNP sub format 1, component list), column headers are defined // by the first level of children. The data for the column is the child of the column header. @@ -204,1401 +174,1342 @@ namespace Volian.Print.Library //int? bxIndx = childItemInfo.FormatStepData == null ? -1 : childItemInfo.FormatStepData.StepLayoutData.STBoxindex; bool boxHLS = false; - // If this step has a previous, and its header is different than the previous's header. Allow it to go - // into the box code. Without this check, none of the box code is run. This caused a problem - // for VCS where two different type notes where not getting separate boxes. - bool doSeparateBoxHdrChg = false; - if (childItemInfo.MyPrevious != null && ((childItemInfo.MyHeader != null && childItemInfo.MyPrevious.MyHeader != null - && childItemInfo.MyHeader.CleanText != childItemInfo.MyPrevious.MyHeader.CleanText) || - (childItemInfo.MyHeader == null && childItemInfo.MyPrevious.MyHeader != null || childItemInfo.MyHeader != null && childItemInfo.MyPrevious.MyHeader == null))) - doSeparateBoxHdrChg = childItemInfo.MyPrevious.MyContent.Type != childItemInfo.MyContent.Type;//true; + // If this step has a previous, and its header is different than the previous's header. Allow it to go + // into the box code. Without this check, none of the box code is run. This caused a problem + // for VCS where two different type notes where not getting separate boxes. + bool doSeparateBoxHdrChg = false; + if (childItemInfo.MyPrevious != null && ((childItemInfo.MyHeader != null && childItemInfo.MyPrevious.MyHeader != null + && childItemInfo.MyHeader.CleanText != childItemInfo.MyPrevious.MyHeader.CleanText) || + (childItemInfo.MyHeader == null && childItemInfo.MyPrevious.MyHeader != null || childItemInfo.MyHeader != null && childItemInfo.MyPrevious.MyHeader == null))) + doSeparateBoxHdrChg = childItemInfo.MyPrevious.MyContent.Type != childItemInfo.MyContent.Type;//true; - bool alwaysBox = (childItemInfo.IsHigh && childItemInfo.FormatStepData.BoxIt); - if ((alwaysBox || (bxIndx ?? -1) != -1) && (bxIndex != bxIndx || childItemInfo.FormatStepData.BoxIt || childItemInfo.MyHeader != null || doSeparateBoxHdrChg || childItemInfo.FormatStepData.SeparateBox)) - { - if (childItemInfo.FormatStepData.BoxIt) // this is a boxed HLS - { - box = new vlnBox(); - box.MyBox = new Box(); - box.DefBox = vlnBox.BoxThin; - StepSectionLayoutData ssld = formatInfo.MyStepSectionLayoutData; - float colR = float.Parse(formatInfo.MyStepSectionLayoutData.ColRTable.Split(",".ToCharArray())[childItemInfo.ColumnMode]); - int widS = vlnPrintObject.ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, maxRNO); - box.DefEnd = (float)(ssld.ColS + colR + widS + (60 / 4.8)); - box.YOffset = yoff - .75F * vlnPrintObject.SixLinesPerInch; - } - else if (bxIndex == null) // First boxed step - { - if (childItemInfo.IsHigh) boxHLS = true; - box = new vlnBox(); - box.MyBox = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; - if (box.MyBox != null) - { - // B2022-130: Barakah warning box prints on bottom of section title if warning is on first HLS - if (box.MyBox.ThickDouble && childItemInfo.MyParent != null && childItemInfo.MyParent.IsHigh && childItemInfo.MyParent.ItemID == childItemInfo.MyParent.FirstSibling.ItemID) - { - if (!childItemInfo.MyParent.MyParent.MyDocStyle.CancelSectTitle) - yoff += vlnPrintObject.SixLinesPerInch; - } - box.YOffset = yoff; - int ln = 1; // a format flag determines whether there is a space before the note/caution. - if (childItemInfo.FormatStepData.OneLineBeforeTab) ln++; - if (!boxHLS || (boxHLS && !childItemInfo.HasCautionOrNote)) - { - // note that in the following line of code, the Calvert Alarms' caution1 is their annunciator window - // so it needs the extra lines as defined by 'ln' or the text will be too close to the top of the box. - if (!formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || iChildItemInfo.IsCaution1) - yoff += ln * vlnPrintObject.SixLinesPerInch; - else - yoff += vlnPrintObject.SixLinesPerInch; - } - if (box.MyBox != null) - yoff += (float)(box.MyBox.AdjSpB4Tab ?? 0); // F2024-078 adjust space above the Note/Caution box tab - } - bxIndex = bxIndx; - } - else // Change Box Style - { - bool handleSeparateBox = true; - if (childItemInfo.IsCaution && !childItemInfo.FormatStepData.SeparateBox && !childItemInfo.FormatStepData.SeparateBoxCautions) handleSeparateBox = false; - if (childItemInfo.IsNote && !childItemInfo.FormatStepData.SeparateBox) handleSeparateBox = false; + bool alwaysBox = (childItemInfo.IsHigh && childItemInfo.FormatStepData.BoxIt); + if ((alwaysBox || (bxIndx ?? -1) != -1) && (bxIndex != bxIndx || childItemInfo.FormatStepData.BoxIt || childItemInfo.MyHeader != null || doSeparateBoxHdrChg || childItemInfo.FormatStepData.SeparateBox)) + { + if (childItemInfo.FormatStepData.BoxIt) // this is a boxed HLS + { + box = new vlnBox + { + MyBox = new Box(), + DefBox = vlnBox.BoxThin + }; + StepSectionLayoutData ssld = formatInfo.MyStepSectionLayoutData; + float colR = float.Parse(formatInfo.MyStepSectionLayoutData.ColRTable.Split(",".ToCharArray())[childItemInfo.ColumnMode]); + int widS = vlnPrintObject.ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, maxRNO); + box.DefEnd = (float)(ssld.ColS + colR + widS + (60 / 4.8)); + box.YOffset = yoff - .75F * vlnPrintObject.SixLinesPerInch; + } + else if (bxIndex == null) // First boxed step + { + if (childItemInfo.IsHigh) boxHLS = true; + box = new vlnBox + { + MyBox = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx] + }; + if (box.MyBox != null) + { + // B2022-130: Barakah warning box prints on bottom of section title if warning is on first HLS + if (box.MyBox.ThickDouble && childItemInfo.MyParent != null && childItemInfo.MyParent.IsHigh && childItemInfo.MyParent.ItemID == childItemInfo.MyParent.FirstSibling.ItemID) + { + if (!childItemInfo.MyParent.MyParent.MyDocStyle.CancelSectTitle) + yoff += vlnPrintObject.SixLinesPerInch; + } + box.YOffset = yoff; + int ln = 1; // a format flag determines whether there is a space before the note/caution. + if (childItemInfo.FormatStepData.OneLineBeforeTab) ln++; + if (!boxHLS || (boxHLS && !childItemInfo.HasCautionOrNote)) + { + // note that in the following line of code, the Calvert Alarms' caution1 is their annunciator window + // so it needs the extra lines as defined by 'ln' or the text will be too close to the top of the box. + if (!formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || iChildItemInfo.IsCaution1) + yoff += ln * vlnPrintObject.SixLinesPerInch; + else + yoff += vlnPrintObject.SixLinesPerInch; + } + if (box.MyBox != null) + yoff += (float)(box.MyBox.AdjSpB4Tab ?? 0); // F2024-078 adjust space above the Note/Caution box tab + } + bxIndex = bxIndx; + } + else // Change Box Style + { + bool handleSeparateBox = true; + if (childItemInfo.IsCaution && !childItemInfo.FormatStepData.SeparateBox && !childItemInfo.FormatStepData.SeparateBoxCautions) handleSeparateBox = false; + if (childItemInfo.IsNote && !childItemInfo.FormatStepData.SeparateBox) handleSeparateBox = false; - if (bxIndx != null && (handleSeparateBox || bxIndex != bxIndx || doSeparateBoxHdrChg)) - { - bool didSeparateBoxChgYAdjust = false; - if (box != null) - { - box.Height = yoff - box.YOffset; // new height, with children - if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || - formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - { - if (childItemInfo.MyHeader != null && childItemInfo.MyPrevious != null - && ((childItemInfo.MyPrevious.IsCautionOrNotePart && childItemInfo.IsCautionOrNotePart) - || childItemInfo.FormatStepData.SeparateBox)) - yoff += vlnPrintObject.SixLinesPerInch * 2; - } - else if (childItemInfo.MyHeader != null && childItemInfo.MyPrevious != null - && ((childItemInfo.MyPrevious.IsCaution && childItemInfo.IsCaution) || - (childItemInfo.MyPrevious.IsNote && childItemInfo.IsNote) || childItemInfo.FormatStepData.SeparateBox)) - yoff += vlnPrintObject.SixLinesPerInch * 2; - // B2020-026: Farley - Notes before Cautions/cautions and notes in same 'parts' list, so bxIndex what not null, need - // to add an extra line after note box. - else if (formatInfo.Name.ToUpper().StartsWith("FNP") && childItemInfo.MyPrevious != null && childItemInfo.MyPrevious.IsNote && childItemInfo.IsCaution) - yoff += vlnPrintObject.SixLinesPerInch * 2; - else if (doSeparateBoxHdrChg) // F2021-038: SHE/SHEA format - Less space after boxes (removes it below) - { - didSeparateBoxChgYAdjust = true; - yoff += vlnPrintObject.SixLinesPerInch * 2; - } - } - box = new vlnBox(); - box.MyBox = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; - // F2021-038: SHE/SHEA format - Less space after boxes - if (didSeparateBoxChgYAdjust && childItemInfo.IsStep && childItemInfo.FormatStepData.NoYBxAdjust) yoff -= vlnPrintObject.SixLinesPerInch; - int ln = 1; // a format flag determines whether there is a space before the note/caution. - //if (childItemInfo.FormatStepData.OneLineBeforeTab) ln++; - if (childItemInfo.MixCautionNotesDiffType()) ln += 2; - box.YOffset = yoff + ((ln - 1) * vlnPrintObject.SixLinesPerInch); - if (childItemInfo.FormatStepData.OneLineBeforeTab) ln++; - yoff += ln * vlnPrintObject.SixLinesPerInch; - if (box.MyBox != null) - yoff += (float)(box.MyBox.AdjSpB4Tab ?? 0); // F2024-078 adjust space above the Note/Caution box tab - } - } - bxIndex = bxIndx; - } - else if (((bxIndx ?? -1) == -1) && box != null) - { - // BGE STP has a null box for its 'Date Time Stamp', i.e. Note4, - // without this code if there is a previous sibling the 'Date Time Note' was - // included in its previous sibling's box: - // (STBoxindex="" is how Note4's box in BGE STP is defined - it is the only place - // in the format files that this is done) - box.Height = yoff - box.YOffset; // new height, with children - yoff += 2 * vlnPrintObject.SixLinesPerInch; - box = null; - } - // DoubleBoxHls is a format flag used by BGE to draw double lined boxes around their HLS - if (childItemInfo.IsHigh && ((childItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) - { - boxHLS = true; - box = new vlnBox(); - box.MyBox = new Box(); - box.DefBox = vlnBox.DOUBLEboxHLS; - bxHlsDraw = true; - } - vlnParagraph para = null; - // Comanche peak or WCN bck Step designator - if (childItemInfo.IsCaution2 && childItemInfo.SameRowAsParent || - childItemInfo.IsCaution1 && childItemInfo.SameRowAsParent) - { - // Save the Step Designator information - // SameRowAsParentMultiLine currently used in Comanche Peak EOP and Flex formats - handles a hard return in the caution type - _StepDesignator = ((childItemInfo.SameRowAsParentMultiLines) ? childItemInfo.MulitLineStepDesignatorDisplayText : childItemInfo.DisplayText); - int typ = ((int)childItemInfo.MyContent.Type) % 10000; - _StepDesignatorColumn = formatInfo.PlantFormat.FormatData.StepDataList[typ].ColOverride; - E_Style es = (E_Style)childItemInfo.FormatStepData.Font.Style; - _StepDesignatorFont = new VE_Font(childItemInfo.FormatStepData.Font.Family, (int)childItemInfo.FormatStepData.Font.Size, es, (float)childItemInfo.FormatStepData.Font.CPI); - } - else - { - if (childItemInfo is SectionInfo) formatInfo = (childItemInfo as SectionInfo).LocalFormat ?? formatInfo; - if (rnoLevel < maxRNO && childItemInfo.RNOs != null) yoff = Math.Max(yoff, yoffRight); - if (childItemInfo.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.ContActBoxOnSubSteps && - box != null && box.MyBox != null && bxIndx == null) // point beach boxed substeps - { - box.Height = yoff - box.YOffset - (1F * vlnPrintObject.SixLinesPerInch); - box = null; - yoff += 1 * vlnPrintObject.SixLinesPerInch; - } - para = new vlnParagraph(Parent, cb, childItemInfo, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRight, true, pp); + if (bxIndx != null && (handleSeparateBox || bxIndex != bxIndx || doSeparateBoxHdrChg)) + { + bool didSeparateBoxChgYAdjust = false; + if (box != null) + { + box.Height = yoff - box.YOffset; // new height, with children + if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || + formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + { + if (childItemInfo.MyHeader != null && childItemInfo.MyPrevious != null + && ((childItemInfo.MyPrevious.IsCautionOrNotePart && childItemInfo.IsCautionOrNotePart) + || childItemInfo.FormatStepData.SeparateBox)) + yoff += vlnPrintObject.SixLinesPerInch * 2; + } + else if (childItemInfo.MyHeader != null && childItemInfo.MyPrevious != null + && ((childItemInfo.MyPrevious.IsCaution && childItemInfo.IsCaution) || + (childItemInfo.MyPrevious.IsNote && childItemInfo.IsNote) || childItemInfo.FormatStepData.SeparateBox)) + yoff += vlnPrintObject.SixLinesPerInch * 2; + // B2020-026: Farley - Notes before Cautions/cautions and notes in same 'parts' list, so bxIndex what not null, need + // to add an extra line after note box. + else if (formatInfo.Name.ToUpper().StartsWith("FNP") && childItemInfo.MyPrevious != null && childItemInfo.MyPrevious.IsNote && childItemInfo.IsCaution) + yoff += vlnPrintObject.SixLinesPerInch * 2; + else if (doSeparateBoxHdrChg) // F2021-038: SHE/SHEA format - Less space after boxes (removes it below) + { + didSeparateBoxChgYAdjust = true; + yoff += vlnPrintObject.SixLinesPerInch * 2; + } + } + box = new vlnBox + { + MyBox = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx] + }; + // F2021-038: SHE/SHEA format - Less space after boxes + if (didSeparateBoxChgYAdjust && childItemInfo.IsStep && childItemInfo.FormatStepData.NoYBxAdjust) yoff -= vlnPrintObject.SixLinesPerInch; + int ln = 1; // a format flag determines whether there is a space before the note/caution. + //if (childItemInfo.FormatStepData.OneLineBeforeTab) ln++; + if (childItemInfo.MixCautionNotesDiffType()) ln += 2; + box.YOffset = yoff + ((ln - 1) * vlnPrintObject.SixLinesPerInch); + if (childItemInfo.FormatStepData.OneLineBeforeTab) ln++; + yoff += ln * vlnPrintObject.SixLinesPerInch; + if (box.MyBox != null) + yoff += (float)(box.MyBox.AdjSpB4Tab ?? 0); // F2024-078 adjust space above the Note/Caution box tab + } + } + bxIndex = bxIndx; + } + else if (((bxIndx ?? -1) == -1) && box != null) + { + // BGE STP has a null box for its 'Date Time Stamp', i.e. Note4, + // without this code if there is a previous sibling the 'Date Time Note' was + // included in its previous sibling's box: + // (STBoxindex="" is how Note4's box in BGE STP is defined - it is the only place + // in the format files that this is done) + box.Height = yoff - box.YOffset; // new height, with children + yoff += 2 * vlnPrintObject.SixLinesPerInch; + box = null; + } + // DoubleBoxHls is a format flag used by BGE to draw double lined boxes around their HLS + if (childItemInfo.IsHigh && ((childItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) + { + boxHLS = true; + box = new vlnBox + { + MyBox = new Box(), + DefBox = vlnBox.DOUBLEboxHLS + }; + bxHlsDraw = true; + } + vlnParagraph para = null; + // Comanche peak or WCN bck Step designator + if (childItemInfo.IsCaution2 && childItemInfo.SameRowAsParent || + childItemInfo.IsCaution1 && childItemInfo.SameRowAsParent) + { + // Save the Step Designator information + // SameRowAsParentMultiLine currently used in Comanche Peak EOP and Flex formats - handles a hard return in the caution type + StepDesignator = ((childItemInfo.SameRowAsParentMultiLines) ? childItemInfo.MulitLineStepDesignatorDisplayText : childItemInfo.DisplayText); + int typ = ((int)childItemInfo.MyContent.Type) % 10000; + StepDesignatorColumn = formatInfo.PlantFormat.FormatData.StepDataList[typ].ColOverride; + E_Style es = (E_Style)childItemInfo.FormatStepData.Font.Style; + StepDesignatorFont = new VE_Font(childItemInfo.FormatStepData.Font.Family, (int)childItemInfo.FormatStepData.Font.Size, es, (float)childItemInfo.FormatStepData.Font.CPI); + } + else + { + if (childItemInfo is SectionInfo) formatInfo = (childItemInfo as SectionInfo).LocalFormat ?? formatInfo; + if (rnoLevel < maxRNO && childItemInfo.RNOs != null) yoff = Math.Max(yoff, yoffRight); + if (childItemInfo.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.ContActBoxOnSubSteps && + box != null && box.MyBox != null && bxIndx == null) // point beach boxed substeps + { + box.Height = yoff - box.YOffset - (1F * vlnPrintObject.SixLinesPerInch); + box = null; + yoff += 1 * vlnPrintObject.SixLinesPerInch; + } + para = new vlnParagraph(Parent, cb, childItemInfo, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRight, true, pp); - // if doing the component list (FNP), keep track of the bottom most columns' data - // so this can be returned after the row is done. - tableBottomMost = Math.Max(tableBottomMost, para.YBottomMost); - if (box != null && box.MyParent == null) - { - box.MyParent = para; - para.PartsContainer.Add(box); - } - Add(para); - if (didComponentTableRow && iChildItemInfo.Steps != null && iChildItemInfo.Steps.Count > 1) - tableBottomMost = Math.Max(tableBottomMost, AddComponentTableSiblings(cb, iChildItemInfo.Steps[1], xoff, para.YBottomMost, rnoLevel, maxRNO, formatInfo, yoffRight, pp)); + // if doing the component list (FNP), keep track of the bottom most columns' data + // so this can be returned after the row is done. + tableBottomMost = Math.Max(tableBottomMost, para.YBottomMost); + if (box != null && box.MyParent == null) + { + box.MyParent = para; + para.PartsContainer.Add(box); + } + Add(para); + if (didComponentTableRow && iChildItemInfo.Steps != null && iChildItemInfo.Steps.Count > 1) + tableBottomMost = Math.Max(tableBottomMost, AddComponentTableSiblings(cb, iChildItemInfo.Steps[1], xoff, para.YBottomMost, rnoLevel, maxRNO, formatInfo, yoffRight, pp)); - // Calvert Alarm's caution1 is the Annunciator window, i.e. in top right of page. Adjust - // y offset for this caution that is printed BELOW the hls. - if (childItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && iChildItemInfo.IsCaution1) para.MyHighLevelParagraph.YBottomMost = para.YBottomMost; + // Calvert Alarm's caution1 is the Annunciator window, i.e. in top right of page. Adjust + // y offset for this caution that is printed BELOW the hls. + if (childItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && iChildItemInfo.IsCaution1) para.MyHighLevelParagraph.YBottomMost = para.YBottomMost; - // para.YBottomMost will have y for bottom of any substeps that are also enclosed in the box. - if (childItemInfo.IsStep && childItemInfo.MyHLS != null && childItemInfo.MyHLS.FormatStepData.UseSmartTemplate && para.ChildrenBelow.Count > 0 && para.ChildrenBelow[0].YBottomMost > para.YBottomMost) - yoff = para.ChildrenBelow[0].YBottomMost; - // if doing the component list (FNP), yoff for the HLS (if it's the component in the list, - // i.e. the leftmost item in the table), the yoff is either the HLS bottom, or the bottom most - // of all of the other columns' data. - else if (childItemInfo.IsHigh && childItemInfo.FormatStepData.UseOldTemplate && childItemInfo.MyDocStyle.ComponentList) - yoff = Math.Max(para.YBottom, para.YBottomMost) + vlnPrintObject.SixLinesPerInch; - // increment the y offset if not doing the ComponentTableFormat - else if (!para.UseTemplateKeepOnCurLine(childItemInfo)) - { - // B2019-028: These comments ARE NOT relevant and the code added, the if and the else/console.writeline - // are not correct (left in commented out so that change can be seen): - // Don't set to zero after a Word Section - // Otherwise the step section output will overlap previous step section output - // if in a sub section. - // To see the problem, create a section with three subsections. - // First section a multiple page step section - // Second section a word section - // Third section a step section - // skip the logic in the next three lines. (if to else) - //if (para.YBottomMost > 0) - yoff = para.YBottomMost; - //else - //Console.WriteLine("ERROR Would have changed yoff from {0} to zero",yoff); - } - // don't adjust YBottomost until after yoff is set for the RNO Separator - para.YBottomMost += para.YBottomMostAdjust; - if (box != null && childItemInfo.FormatStepData != null && childItemInfo.FormatStepData.BoxIt) - { - box.Height = yoff - box.YOffset - (1.1F * vlnPrintObject.SixLinesPerInch); - box = null; // if doing boxed steps, only do single sibling at a time. - } - if (bxHlsDraw) - { - box.YOffset = para.YTop; - box.Height = para.Height; - box = null; - } - else if (boxHLS) - { - // the following line controls whether there is 1 line or 2 lines between - // the box line & the starting/ending yoffset of the HLS. WEP2 had no extra line between - // box & top/bottom of step. The DiffContActBox was added for WEP2. - int boxLnAdjust = iChildItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox ? 1 : 2; - box.YOffset = para.YTop - (boxLnAdjust * vlnPrintObject.SixLinesPerInch); - boxLnAdjust = iChildItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox ? 1 : 0; + // para.YBottomMost will have y for bottom of any substeps that are also enclosed in the box. + if (childItemInfo.IsStep && childItemInfo.MyHLS != null && childItemInfo.MyHLS.FormatStepData.UseSmartTemplate && para.ChildrenBelow.Count > 0 && para.ChildrenBelow[0].YBottomMost > para.YBottomMost) + yoff = para.ChildrenBelow[0].YBottomMost; + // if doing the component list (FNP), yoff for the HLS (if it's the component in the list, + // i.e. the leftmost item in the table), the yoff is either the HLS bottom, or the bottom most + // of all of the other columns' data. + else if (childItemInfo.IsHigh && childItemInfo.FormatStepData.UseOldTemplate && childItemInfo.MyDocStyle.ComponentList) + yoff = Math.Max(para.YBottom, para.YBottomMost) + vlnPrintObject.SixLinesPerInch; + // increment the y offset if not doing the ComponentTableFormat + else if (!para.UseTemplateKeepOnCurLine(childItemInfo)) + { + yoff = para.YBottomMost; + } + // don't adjust YBottomost until after yoff is set for the RNO Separator + para.YBottomMost += para.YBottomMostAdjust; + if (box != null && childItemInfo.FormatStepData != null && childItemInfo.FormatStepData.BoxIt) + { + box.Height = yoff - box.YOffset - (1.1F * vlnPrintObject.SixLinesPerInch); + box = null; // if doing boxed steps, only do single sibling at a time. + } + if (bxHlsDraw) + { + box.YOffset = para.YTop; + box.Height = para.Height; + box = null; + } + else if (boxHLS) + { + // the following line controls whether there is 1 line or 2 lines between + // the box line & the starting/ending yoffset of the HLS. WEP2 had no extra line between + // box & top/bottom of step. The DiffContActBox was added for WEP2. + int boxLnAdjust = iChildItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox ? 1 : 2; + box.YOffset = para.YTop - (boxLnAdjust * vlnPrintObject.SixLinesPerInch); + boxLnAdjust = iChildItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox ? 1 : 0; - // if the YBottomForBox is set, use it to define height. Note that this property was - // introduced for IP3 continuous hls (surrounded by the asterisk box), no other format/step type uses it. - if (para.YBottomForBox > 0) - box.Height = para.YBottomForBox - box.YOffset - (boxLnAdjust * vlnPrintObject.SixLinesPerInch); // para.YTop - (1.1F * vlnPrintObject.SixLinesPerInch); - else - box.Height = para.YBottomMost - box.YOffset - (boxLnAdjust * vlnPrintObject.SixLinesPerInch); // para.YTop - (1.1F * vlnPrintObject.SixLinesPerInch); - box = null; - } - } - if (boxHLS) - { - // if the next HLS is boxed also, only need 1 line separating, otherwise - // need 2. - ItemInfo nxt = childItemInfo.GetNextItem(); - int nxtIsBoxed = 2; - if (nxt != null && - nxt.FormatStepData.StepLayoutData.STBoxindex != null && nxt.FormatStepData.StepLayoutData.STBoxindex >= 0) nxtIsBoxed--; - if (nxt != null && (nxt.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) nxtIsBoxed = 0; - yoff += (nxtIsBoxed * vlnPrintObject.SixLinesPerInch); - } - if (childItemInfo.IsSequential && childItemInfo.NextItem != null && childItemInfo.MyParent.IsHigh && ((childItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.XBlankW1stLevSub) == E_DocStructStyle.XBlankW1stLevSub)) - { - yoff += vlnPrintObject.SixLinesPerInch; - if (para != null) para.AdjustForXBlankW1stLevSub = vlnPrintObject.SixLinesPerInch; // B2020-112 - } - boxHLS = false; - lastChild = childItemInfo; - } - } - if (box != null && box.MyBox != null) - { - box.Height = yoff - box.YOffset; // new height, with children - // C2017-024 Wolf Creek wanted a hold point with out text and no extra blank lines in the caution/note box - // so if they put only a hard space in for the text, then we will print the note/caution box with only the tab text - // B2018-077 added check for parts under the note (ex. a table off of the note text) fix for Calvert OI-27B 6.11.B and 6.12.B - if (box.MyParent.MyItemInfo.MyContent.Text.StartsWith(@"\u160?") && box.MyParent.MyItemInfo.DisplayText.Length == 1 && box.MyParent.MyItemInfo.MyContent.ContentPartCount == 0) - { - box.Height -= 3 * vlnPrintObject.SixLinesPerInch; - yoff -= vlnPrintObject.SixLinesPerInch; - } - else - yoff += 2 * vlnPrintObject.SixLinesPerInch; - if (lastChild != null && lastChild.FormatStepData.AlwaysUseExtraLines && (lastChild.IsCaution || lastChild.IsNote)) - { - if (!lastChild.MyParent.IsHigh) - yoff += lastChild.ActiveFormat.PlantFormat.FormatData.StepDataList[2].StepLayoutData.STExtraSpace ?? 0; - } - } - // after the last child substep when doing a Component table row (FNP Component Lists), set the value - // of the yoff to be the bottom most line in the table. - if (didComponentTableRow) yoff = tableBottomMost; - ProfileTimer.Pop(profileDepth); - return yoff; - } - private float AddComponentTableSiblings(PdfContentByte cb, ItemInfo ii, float xoff, float yoff, int rnoLevel, int maxRNO, FormatInfo formatInfo, float yoffRight, PromsPrinter pp) - { - // Some of the data for the valve lists (BGE) and component lists (FARLEY) have - // sibling data within a column, rather than hard returns within the same paragraph. - float tableBottomMost = 0; - while (ii != null) - { - vlnParagraph para = new vlnParagraph(Parent, cb, ii, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRight, true, pp); - tableBottomMost = Math.Max(tableBottomMost, para.YBottomMost); - yoff = para.YBottomMost; - Add(para); - ii = ii.GetNextItem(); - } - return tableBottomMost; - } - public float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) - { - foreach (vlnParagraph child in this) - { - yPageStart = child.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - } - return yPageStart; - } - } - public partial class vlnParagraph : vlnPrintObject - { - // B2020-115 Create Static properties for vlnParagraph to limit the size of a figure and paginate large figures properly onto their own page. - public static float wMax = 0; - public static float hMax = 0; - private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - public override string ToString() - { - return string.Format("{0} - {1} - {2} - '{3}'", this.MyItemInfo.ItemID, this.YTop, this.YSize, this.MyItemInfo.ShortPath); - } - private bool _PageBreakOnStep = false; - public bool PageBreakOnStep - { - get { return _PageBreakOnStep; } - set { _PageBreakOnStep = value; } - } - private bool HasCalvertMacro = false; // this step has the Calvert (BGE) Alarm CONDITION/RESPONSE macro associated with it - private float WidthNoLimit = 0; - private vlnTable _MyGrid; - public vlnTable MyGrid - { - get { return _MyGrid; } - set { _MyGrid = value; } - } - public float SectYPageStart = 0; - private bool _IsWordDocPara = false; - public bool IsWordDocPara - { - get { return _IsWordDocPara; } - set { _IsWordDocPara = value; } - } - public static bool HasPrefPageBreak = false; // use to track page breaks for supp info - public bool PrefPageBreak = false; - private bool _ShowSectionTitles; - public bool ShowSectionTitles - { - get { return _ShowSectionTitles; } - set { _ShowSectionTitles = value; } - } + // if the YBottomForBox is set, use it to define height. Note that this property was + // introduced for IP3 continuous hls (surrounded by the asterisk box), no other format/step type uses it. + if (para.YBottomForBox > 0) + box.Height = para.YBottomForBox - box.YOffset - (boxLnAdjust * vlnPrintObject.SixLinesPerInch); // para.YTop - (1.1F * vlnPrintObject.SixLinesPerInch); + else + box.Height = para.YBottomMost - box.YOffset - (boxLnAdjust * vlnPrintObject.SixLinesPerInch); // para.YTop - (1.1F * vlnPrintObject.SixLinesPerInch); + box = null; + } + } + if (boxHLS) + { + // if the next HLS is boxed also, only need 1 line separating, otherwise + // need 2. + ItemInfo nxt = childItemInfo.GetNextItem(); + int nxtIsBoxed = 2; + if (nxt != null && + nxt.FormatStepData.StepLayoutData.STBoxindex != null && nxt.FormatStepData.StepLayoutData.STBoxindex >= 0) nxtIsBoxed--; + if (nxt != null && (nxt.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) nxtIsBoxed = 0; + yoff += (nxtIsBoxed * vlnPrintObject.SixLinesPerInch); + } + if (childItemInfo.IsSequential && childItemInfo.NextItem != null && childItemInfo.MyParent.IsHigh && ((childItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.XBlankW1stLevSub) == E_DocStructStyle.XBlankW1stLevSub)) + { + yoff += vlnPrintObject.SixLinesPerInch; + if (para != null) para.AdjustForXBlankW1stLevSub = vlnPrintObject.SixLinesPerInch; // B2020-112 + } + boxHLS = false; + lastChild = childItemInfo; + } + } + if (box != null && box.MyBox != null) + { + box.Height = yoff - box.YOffset; // new height, with children + // C2017-024 Wolf Creek wanted a hold point with out text and no extra blank lines in the caution/note box + // so if they put only a hard space in for the text, then we will print the note/caution box with only the tab text + // B2018-077 added check for parts under the note (ex. a table off of the note text) fix for Calvert OI-27B 6.11.B and 6.12.B + if (box.MyParent.MyItemInfo.MyContent.Text.StartsWith(@"\u160?") && box.MyParent.MyItemInfo.DisplayText.Length == 1 && box.MyParent.MyItemInfo.MyContent.ContentPartCount == 0) + { + box.Height -= 3 * vlnPrintObject.SixLinesPerInch; + yoff -= vlnPrintObject.SixLinesPerInch; + } + else + yoff += 2 * vlnPrintObject.SixLinesPerInch; + if (lastChild != null && lastChild.FormatStepData.AlwaysUseExtraLines && (lastChild.IsCaution || lastChild.IsNote)) + { + if (!lastChild.MyParent.IsHigh) + yoff += lastChild.ActiveFormat.PlantFormat.FormatData.StepDataList[2].StepLayoutData.STExtraSpace ?? 0; + } + } + // after the last child substep when doing a Component table row (FNP Component Lists), set the value + // of the yoff to be the bottom most line in the table. + if (didComponentTableRow) yoff = tableBottomMost; + ProfileTimer.Pop(profileDepth); + return yoff; + } + private float AddComponentTableSiblings(PdfContentByte cb, ItemInfo ii, float xoff, float yoff, int rnoLevel, int maxRNO, FormatInfo formatInfo, float yoffRight, PromsPrinter pp) + { + // Some of the data for the valve lists (BGE) and component lists (FARLEY) have + // sibling data within a column, rather than hard returns within the same paragraph. + float tableBottomMost = 0; + while (ii != null) + { + vlnParagraph para = new vlnParagraph(Parent, cb, ii, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRight, true, pp); + tableBottomMost = Math.Max(tableBottomMost, para.YBottomMost); + yoff = para.YBottomMost; + Add(para); + ii = ii.GetNextItem(); + } + return tableBottomMost; + } + public float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) + { + foreach (vlnParagraph child in this) + { + yPageStart = child.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + } + return yPageStart; + } + } + public partial class vlnParagraph : vlnPrintObject + { + // B2020-115 Create Static properties for vlnParagraph to limit the size of a figure and paginate large figures properly onto their own page. + public static float wMax = 0; + public static float hMax = 0; + private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + public override string ToString() => string.Format("{0} - {1} - {2} - '{3}'", this.MyItemInfo.ItemID, this.YTop, this.YSize, this.MyItemInfo.ShortPath); - public float ParagraphToPdf(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin) - { - // Don't print section titles for supplemental information because the title is 'Supplemental Information': - if (MyItemInfo.IsSection && MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.SupInfoPdfPrint) return yPageStart; - //if(PartsAbove.Count > 0 && PartsAbove[0] is vlnHeader) - // if (PartsLeft.Count > 0 && PartsLeft[0] is vlnTab) - // //if((PartsLeft[0] as vlnTab).Text[0] != '\u25CF') - // _MyLog.WarnFormat("NoteTab '{0}','{1}','{2}','{3}','{4}','{5}','{6}'", (PartsAbove[0] as vlnHeader).Text, (PartsLeft[0] as vlnTab).Text, MyItemInfo.MyProcedure.DisplayNumber, MyItemInfo.MyHLS.DisplayText, - // MyItemInfo.ShortPath, MyItemInfo.FormatStepData.TabData.IdentPrint, MyItemInfo.FormatStepData.TabData.IdentEdit); - // - // B2017-105 if a symbol character was set to a bigger font size, then the positioning of the larger symbol character was printing too high on the line - // found with Wolf Creek use of the empty box symbol - foreach (Chunk chk in IParagraph.Chunks) - { - if (chk.Font.Size > 16) chk.SetTextRise(-2f); - } - if (MyItemInfo.IsFootnote && Processed) return yPageStart; - int pagenumTran = 0; - if ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DontCountFoldoutPgs) == E_DocStructStyle.DontCountFoldoutPgs) - pagenumTran = MyPageHelper.CurrentPageNumberNoFoldouts; - else - pagenumTran = MyPageHelper.CurrentPageNumber; - if (MyItemInfo.PageNumber == -1) MyItemInfo.PageNumber = pagenumTran; - else if (MyItemInfo.PageNumberUsed != 0 && MyItemInfo.PageNumberUsed != pagenumTran) - { - if (PromsPrinter.TransPageNumProblems == null) PromsPrinter.TransPageNumProblems = new List(); - // C2017-018 Insert tabs between columns - string pnErr = string.Format("{0}\t{1}\t{2}\t{3}", MyItemInfo.ItemID, MyItemInfo.ShortPath, MyItemInfo.PageNumberUsed, pagenumTran); - PromsPrinter.TransPageNumProblems.Add(pnErr); - } - MyItemInfo.PageNumberNextPass = pagenumTran; - if (Processed) return yPageStart; - //float localYPageStart = yPageStart; - Processed = true; - if (_PartsAbove != null && _PartsAbove.Count > 0) - { - // For McGuire and Catawba, they use CustomSpacing which inserts a blank line before high level steps - // if we paginate on one of these blank lines, we want to skip that blank line so that there isn't an - // extra blank line at the top of the page. - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.CustomSpacing && - PartsAbove[0].YOffset + yTopMargin == yPageStart && PartsAbove[0].IParagraph.Content == " ") - { - if (MyItemInfo.IsHigh && ((YOffset - YTopMost) > SixLinesPerInch)) - { - //Console.WriteLine("==> {0} {1} MOST {2} DIF {3}", MyItemInfo.ShortPath, YOffset, YTopMost, YOffset - YTopMost); - yPageStart = yTopMargin + YTopMost; - } - else - yPageStart = yTopMargin + YOffset; - } - else - yPageStart = PartsAbove.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - } + public bool PageBreakOnStep { get; set; } = false; + private readonly bool HasCalvertMacro = false; // this step has the Calvert (BGE) Alarm CONDITION/RESPONSE macro associated with it + private readonly float WidthNoLimit = 0; - if (MyItemInfo.IsHigh && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) yPageStart -= SixLinesPerInch; - if (MyItemInfo.IsHigh && MyItemInfo.MyDocStyle.SpecialStepsFoldout) yPageStart -= SixLinesPerInch; - if (MyItemInfo.IsHigh && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.DoSTExtraAtTop && (yPageStart - YTopMost == yTopMargin)) - { - yPageStart += ((MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0); - // F2021-038: SHE/SHEA format - Less space after boxes: the AlwaysUseExtyraLines was removed in SHE/SHEA format, but the - // following adjustment to the y location of HLS when AT TOP of page is still needed, i.e. added the NoYBxAdjust check which is SHE/SHEA specific - if ((MyItemInfo.Cautions != null && (MyItemInfo.Cautions[0].FormatStepData.AlwaysUseExtraLines || MyItemInfo.Cautions[0].FormatStepData.NoYBxAdjust)) || (MyItemInfo.Notes != null && (MyItemInfo.Notes[0].FormatStepData.AlwaysUseExtraLines || MyItemInfo.Notes[0].FormatStepData.NoYBxAdjust))) - yPageStart -= ((MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0); - } - // Save the HLS & RNO string in case the pagelist item uses it (some of the backgrounds): - if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.PageBreakOnStep) - { - MyPageHelper.HLSTAB = MyItemInfo.HighLevelStepTabPageList; - // find the rno and use it's tab for the HLRNO part. - ItemInfo rno = MyItemInfo.RNOs != null && MyItemInfo.RNOs.Count > 0 ? MyItemInfo.RNOs[0] : null; - string rnotab = (rno == null) ? null : rno.DisplayText; - MyPageHelper.HLRNO = rno == null ? null : MyItemInfo.FormatStepData.TabData.RNOIdent + rnotab; - MyPageHelper.ResetSvg(); - } + public vlnTable MyGrid { get; set; } + public float SectYPageStart = 0; - float yLocation = CalculateYOffset(yPageStart, yTopMargin); - if (MyItemInfo.HasChangeBar && MyPageHelper.ChangeBarDefinition.MyChangeBarType != PrintChangeBar.Without) MyPageHelper.AddChangeBar(DoChangeBar(cb, MyItemInfo, MyPageHelper, XOffset, yLocation, MyPageHelper.MaxRNO, MyItemInfo.ActiveFormat), cbMess); - float retval = yLocation; - // 'doprint' will always be true if not doing NSP's {HLSTEXT} token in page list. The following code is used to prevent - // printing the High level step, if the high level step is printed from the pagelist using {HLSTEXT} token. - bool doprint = !(MyPageHelper.DidHLSText && MyItemInfo.ItemID == MyPageHelper.HasHLSTextId); - if (MyItemInfo.IsFigure) - { - yLocation -= (SixLinesPerInch * MyPageHelper.YMultiplier); - if (ImageText != null) - retval = DrawFigure(cb, yBottomMargin, yLocation, yPageStart, yTopMargin); - else - retval = DrawText(cb, ref yPageStart, yTopMargin, yBottomMargin, ref yLocation); - if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = retval; - } - else if (MyItemInfo.IsRtfRaw) - { - retval = DrawRaw(cb, yBottomMargin, yLocation, yPageStart, yTopMargin); - if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = retval * .6f; - } - else if (!MyItemInfo.IsStepSection - || (ShowSectionTitles - && !MyItemInfo.MyDocStyle.CancelSectTitle - && !MyItemInfo.MyDocStyle.SpecialStepsFoldout)) // Don't ouput the Step Section title - { - // if this is a section, then check the section config for printable header too. - if (MyItemInfo.IsSection) - { - SectionConfig sch = MyItemInfo.MyConfig as SectionConfig; - //if (!(ShowSectionTitles - // && !MyItemInfo.MyDocStyle.CancelSectTitle - // && !MyItemInfo.MyDocStyle.SpecialStepsFoldout - // && !MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) - // && - if (sch != null && sch.Section_PrintHdr != "Y") doprint = false; - } - if (MyItemInfo.MyContent.MyGrid != null) - { - int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.DrawGrid"); - // RHM20150507 Include Footer - retval = DrawGrid(cb, ref yPageStart, yTopMargin, yBottomMargin + (float)MyItemInfo.MyDocStyle.Layout.FooterLength, ref yLocation); // RHM20150429 - Table Scrunch - if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = (float)MyPageHelper.BottomContent - SixLinesPerInch; - ProfileTimer.Pop(profileDepth); - } - else - { - if (doprint) - { - int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.DrawText"); - IsCompressed = (MyPageHelper.YMultiplier != 1 && MyItemInfo != null && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.Font.Size >= 12 && (MyItemInfo.FormatStepData.Font.Style & E_Style.Underline) != 0); + public bool IsWordDocPara { get; set; } = false; + public static bool HasPrefPageBreak = false; // use to track page breaks for supp info + public bool PrefPageBreak = false; - retval = DrawText(cb, ref yPageStart, yTopMargin, yBottomMargin, ref yLocation); - // _yPageStartForSupInfo is used to move steps down the page for the supinfo pdf. Each supinfo step may not be related to previous in structure, so need this to set y location. - if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = retval; - // Wolf Creek Training format puts a separator line after printing the section number/title - if (MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining) - MyPageHelper.SectionSepLineYoffStart = retval - (SixLinesPerInch / 2); - SectionContinuePrinted = true; - ProfileTimer.Pop(profileDepth); - } - } - if (MyItemInfo.IsHigh) - { - // C2025-014 change the zoom setting on the bookmark of a step from FITBH to FITV so that instead of zooming in - // on the step it will zoom to the page level ( like it does when you select a bookmark on a section. - MyPageHelper.PageBookmarks.Add(MyItemInfo, (MyItemInfo.MyTab == null) ? "" : MyItemInfo.MyTab.CleanText + " " + MyItemInfo.DisplayText, - new PdfDestination(PdfDestination.FITV, yLocation + YVeryTop - YTopMost + SixLinesPerInch)); - } - } - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.WolfcreekCKLFormat) - { - DrawChkOrValveTableLines(cb, MyItemInfo, yPageStart, yTopMargin, yBottomMargin, yLocation); - } - if (MyItemInfo.IsSection) - { - SectionConfig sc = MyItemInfo.MyConfig as SectionConfig; - if ((MyItemInfo.MyDocStyle != null && MyItemInfo.MyDocStyle.IncludeInTOC && (sc == null || sc.Section_TOC != "Y")) - || ((MyItemInfo.MyDocStyle == null || !MyItemInfo.MyDocStyle.IncludeInTOC) && (sc != null && sc.Section_TOC == "Y"))) - { - string tocKey = string.Format("TOC{0}", MyItemInfo.ItemID); - if (MyPageHelper.MyTOCPageCounts.ContainsKey(tocKey)) - { - PageCount pc = MyPageHelper.MyTOCPageCounts[tocKey]; - if (pc.Total == 0) - { - pc.Total = MyPageHelper.CurrentTOCPageNumber + 1; - pc.DrawTemplates(); + public bool ShowSectionTitles { get; set; } - } - } - } - } - else if (MyItemInfo.IsHigh && MyItemInfo.MyDocStyle != null && MyItemInfo.MyDocStyle.IncludeInTOC) // && (MyItemInfo.MyActiveSection.MyConfig as SectionConfig).Section_HLS_on_TOC == "Y") - { - // C2021-015: Barakah High Level Steps in Table of Contents - SectionConfig sc = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - StepConfig stc = MyItemInfo.MyConfig as StepConfig; - if ((sc != null && sc.Section_TOC != "Y") && (stc != null && stc.Step_IncludeInTOC)) - { - string tocKey = string.Format("TOC{0}", MyItemInfo.ItemID); - if (MyPageHelper.MyTOCPageCounts.ContainsKey(tocKey)) - { - PageCount pc = MyPageHelper.MyTOCPageCounts[tocKey]; - if (pc.Total == 0) - { - pc.Total = MyPageHelper.CurrentTOCPageNumber + 1; - pc.DrawTemplates(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "retval kept for Debugging")] + public float ParagraphToPdf(PdfContentByte cb, float yPageStart, float yTopMargin, float yBottomMargin) + { + // Don't print section titles for supplemental information because the title is 'Supplemental Information': + if (MyItemInfo.IsSection && MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.SupInfoPdfPrint) return yPageStart; + //For Debugging: + //if(PartsAbove.Count > 0 && PartsAbove[0] is vlnHeader) + // if (PartsLeft.Count > 0 && PartsLeft[0] is vlnTab) + // //if((PartsLeft[0] as vlnTab).Text[0] != '\u25CF') + // _MyLog.WarnFormat("NoteTab '{0}','{1}','{2}','{3}','{4}','{5}','{6}'", (PartsAbove[0] as vlnHeader).Text, (PartsLeft[0] as vlnTab).Text, MyItemInfo.MyProcedure.DisplayNumber, MyItemInfo.MyHLS.DisplayText, + // MyItemInfo.ShortPath, MyItemInfo.FormatStepData.TabData.IdentPrint, MyItemInfo.FormatStepData.TabData.IdentEdit); + // + // B2017-105 if a symbol character was set to a bigger font size, then the positioning of the larger symbol character was printing too high on the line + // found with Wolf Creek use of the empty box symbol + foreach (Chunk chk in IParagraph.Chunks) + { + if (chk.Font.Size > 16) chk.SetTextRise(-2f); + } + if (MyItemInfo.IsFootnote && Processed) return yPageStart; + int pagenumTran; + if ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DontCountFoldoutPgs) == E_DocStructStyle.DontCountFoldoutPgs) + pagenumTran = MyPageHelper.CurrentPageNumberNoFoldouts; + else + pagenumTran = MyPageHelper.CurrentPageNumber; + if (MyItemInfo.PageNumber == -1) MyItemInfo.PageNumber = pagenumTran; + else if (MyItemInfo.PageNumberUsed != 0 && MyItemInfo.PageNumberUsed != pagenumTran) + { + if (PromsPrinter.TransPageNumProblems == null) PromsPrinter.TransPageNumProblems = new List(); + // C2017-018 Insert tabs between columns + string pnErr = string.Format("{0}\t{1}\t{2}\t{3}", MyItemInfo.ItemID, MyItemInfo.ShortPath, MyItemInfo.PageNumberUsed, pagenumTran); + PromsPrinter.TransPageNumProblems.Add(pnErr); + } + MyItemInfo.PageNumberNextPass = pagenumTran; + if (Processed) return yPageStart; + Processed = true; + if (_PartsAbove != null && _PartsAbove.Count > 0) + { + // For McGuire and Catawba, they use CustomSpacing which inserts a blank line before high level steps + // if we paginate on one of these blank lines, we want to skip that blank line so that there isn't an + // extra blank line at the top of the page. + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.CustomSpacing && + PartsAbove[0].YOffset + yTopMargin == yPageStart && PartsAbove[0].IParagraph.Content == " ") + { + if (MyItemInfo.IsHigh && ((YOffset - YTopMost) > SixLinesPerInch)) + { + //Console.WriteLine("==> {0} {1} MOST {2} DIF {3}", MyItemInfo.ShortPath, YOffset, YTopMost, YOffset - YTopMost); + yPageStart = yTopMargin + YTopMost; + } + else + yPageStart = yTopMargin + YOffset; + } + else + yPageStart = PartsAbove.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + } - } - } - } - } - if (!doprint) return yPageStart; - if (_PartsLeft != null && _PartsLeft.Count > 0) yPageStart = PartsLeft.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - if (_PartsRight != null && _PartsRight.Count > 0) yPageStart = PartsRight.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - if (_PartsBelow != null && _PartsBelow.Count > 0) yPageStart = PartsBelow.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - if (_PartsContainer != null && _PartsContainer.Count > 0) yPageStart = PartsContainer.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + if (MyItemInfo.IsHigh && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) yPageStart -= SixLinesPerInch; + if (MyItemInfo.IsHigh && MyItemInfo.MyDocStyle.SpecialStepsFoldout) yPageStart -= SixLinesPerInch; + if (MyItemInfo.IsHigh && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.DoSTExtraAtTop && (yPageStart - YTopMost == yTopMargin)) + { + yPageStart += ((MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0); + // F2021-038: SHE/SHEA format - Less space after boxes: the AlwaysUseExtyraLines was removed in SHE/SHEA format, but the + // following adjustment to the y location of HLS when AT TOP of page is still needed, i.e. added the NoYBxAdjust check which is SHE/SHEA specific + if ((MyItemInfo.Cautions != null && (MyItemInfo.Cautions[0].FormatStepData.AlwaysUseExtraLines || MyItemInfo.Cautions[0].FormatStepData.NoYBxAdjust)) || (MyItemInfo.Notes != null && (MyItemInfo.Notes[0].FormatStepData.AlwaysUseExtraLines || MyItemInfo.Notes[0].FormatStepData.NoYBxAdjust))) + yPageStart -= ((MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0); + } + // Save the HLS & RNO string in case the pagelist item uses it (some of the backgrounds): + if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.PageBreakOnStep) + { + MyPageHelper.HLSTAB = MyItemInfo.HighLevelStepTabPageList; + // find the rno and use it's tab for the HLRNO part. + ItemInfo rno = MyItemInfo.RNOs != null && MyItemInfo.RNOs.Count > 0 ? MyItemInfo.RNOs[0] : null; + string rnotab = rno?.DisplayText; + MyPageHelper.HLRNO = rno == null ? null : MyItemInfo.FormatStepData.TabData.RNOIdent + rnotab; + MyPageHelper.ResetSvg(); + } - //if (localYPageStart != yPageStart) DebugText.WriteLine("ParToPdf-yPagestartDiff:{0},{1},{2}", MyItemInfo.ItemID, localYPageStart, yPageStart); - return yPageStart; - } + float yLocation = CalculateYOffset(yPageStart, yTopMargin); + if (MyItemInfo.HasChangeBar && MyPageHelper.ChangeBarDefinition.MyChangeBarType != PrintChangeBar.Without) MyPageHelper.AddChangeBar(DoChangeBar(cb, MyItemInfo, MyPageHelper, XOffset, yLocation, MyPageHelper.MaxRNO, MyItemInfo.ActiveFormat), cbMess); + float retval = yLocation; + // 'doprint' will always be true if not doing NSP's {HLSTEXT} token in page list. The following code is used to prevent + // printing the High level step, if the high level step is printed from the pagelist using {HLSTEXT} token. + bool doprint = !(MyPageHelper.DidHLSText && MyItemInfo.ItemID == MyPageHelper.HasHLSTextId); + if (MyItemInfo.IsFigure) + { + yLocation -= (SixLinesPerInch * MyPageHelper.YMultiplier); + if (ImageText != null) + retval = DrawFigure(cb, yLocation, yPageStart, yTopMargin); + else + retval = DrawText(cb, ref yPageStart, yTopMargin, yBottomMargin, ref yLocation); + if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = retval; + } + else if (MyItemInfo.IsRtfRaw) + { + retval = DrawRaw(cb, yLocation); + if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = retval * .6f; + } + else if (!MyItemInfo.IsStepSection + || (ShowSectionTitles + && !MyItemInfo.MyDocStyle.CancelSectTitle + && !MyItemInfo.MyDocStyle.SpecialStepsFoldout)) // Don't ouput the Step Section title + { + // if this is a section, then check the section config for printable header too. + if (MyItemInfo.IsSection) + { + if (MyItemInfo.MyConfig is SectionConfig sch && sch.Section_PrintHdr != "Y") doprint = false; + } + if (MyItemInfo.MyContent.MyGrid != null) + { + int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.DrawGrid"); + // RHM20150507 Include Footer + retval = DrawGrid(cb, yTopMargin, yBottomMargin + (float)MyItemInfo.MyDocStyle.Layout.FooterLength, ref yLocation); // RHM20150429 - Table Scrunch + if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = (float)MyPageHelper.BottomContent - SixLinesPerInch; + ProfileTimer.Pop(profileDepth); + } + else + { + if (doprint) + { + int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.DrawText"); + IsCompressed = (MyPageHelper.YMultiplier != 1 && MyItemInfo != null && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.Font.Size >= 12 && (MyItemInfo.FormatStepData.Font.Style & E_Style.Underline) != 0); - private float DrawRaw(PdfContentByte cb, float yBottomMargin, float yLocation, float yPageStart, float yTopMargin) - { - if (DebugText.IsOpen) DebugText.WriteLine("{0},'{1}','{2}','<>'", MyItemInfo.ItemID, MyItemInfo.DBSequence, FormattedText); - float retval = yLocation; - System.Drawing.Size sz = RtfRawItem.GetRtfRawSize(MyItemInfo.MyContent.Text); - Height = sz.Height; - Width = sz.Width; - Volian.Controls.Library.RTF myRtb = new RTF(); - myRtb.Size = sz; - myRtb.Rtf = MyItemInfo.MyContent.Text; - try - { - System.Drawing.Image image = new System.Drawing.Bitmap((int)Width, (int)Height); - System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(image); - myRtb.RenderClipped(gr, new System.Drawing.Rectangle(0, 0, (int)Width, (int)Height)); - // B2017-116 Adjust Image Size by Scaler (Used for Facing Pages - Sup Info) - // B2017-241 Adjust Bottom Message Location for the raw figure (Equation or Visio) - MyPageHelper.BottomContent = yLocation - (.6F * Height * MyPageHelper.YMultiplier * ImageScaler); - retval = Rtf2Pdf.RtfRawAt(cb, image, XOffset + MyItemInfo.FormatStepData.Font.CharsToTwips, yLocation, Width * MyPageHelper.YMultiplier * ImageScaler, Height * MyPageHelper.YMultiplier * ImageScaler, DebugInfo, yBottomMargin, !MyItemInfo.FormatStepData.Type.ToUpper().Contains("BORDERLESS")); - } - catch (Exception ex) - { - return retval + 2 * SixLinesPerInch; // couldn't print equation, just print 2 blank lines. - } - return retval; - } - private bool _SectionContinuePrinted = false; + retval = DrawText(cb, ref yPageStart, yTopMargin, yBottomMargin, ref yLocation); + // _yPageStartForSupInfo is used to move steps down the page for the supinfo pdf. Each supinfo step may not be related to previous in structure, so need this to set y location. + if (MyItemInfo.IsInSupInfo) _yPageStartForSupInfo = retval; + // Wolf Creek Training format puts a separator line after printing the section number/title + if (MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining) + MyPageHelper.SectionSepLineYoffStart = retval - (SixLinesPerInch / 2); + SectionContinuePrinted = true; + ProfileTimer.Pop(profileDepth); + } + } + if (MyItemInfo.IsHigh) + { + // C2025-014 change the zoom setting on the bookmark of a step from FITBH to FITV so that instead of zooming in + // on the step it will zoom to the page level ( like it does when you select a bookmark on a section. + MyPageHelper.PageBookmarks.Add(MyItemInfo, (MyItemInfo.MyTab == null) ? "" : $"{MyItemInfo.MyTab.CleanText} {MyItemInfo.DisplayText}", + new PdfDestination(PdfDestination.FITV, yLocation + YVeryTop - YTopMost + SixLinesPerInch)); + } + } + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.WolfcreekCKLFormat) + { + DrawChkOrValveTableLines(cb, MyItemInfo, yPageStart, yBottomMargin, yLocation); + } + if (MyItemInfo.IsSection) + { + SectionConfig sc = MyItemInfo.MyConfig as SectionConfig; + if ((MyItemInfo.MyDocStyle != null && MyItemInfo.MyDocStyle.IncludeInTOC && (sc == null || sc.Section_TOC != "Y")) + || ((MyItemInfo.MyDocStyle == null || !MyItemInfo.MyDocStyle.IncludeInTOC) && (sc != null && sc.Section_TOC == "Y"))) + { + string tocKey = string.Format("TOC{0}", MyItemInfo.ItemID); + if (MyPageHelper.MyTOCPageCounts.ContainsKey(tocKey)) + { + PageCount pc = MyPageHelper.MyTOCPageCounts[tocKey]; + if (pc.Total == 0) + { + pc.Total = MyPageHelper.CurrentTOCPageNumber + 1; + pc.DrawTemplates(); - public bool SectionContinuePrinted - { - get { return _SectionContinuePrinted; } - set { _SectionContinuePrinted = value; } - } - private void DrawChkOrValveTableLines(PdfContentByte cb, ItemInfo ii, float yPageStart, float yTopMargin, float yBottomMargin, float yLocation) - { - if (!ii.IsStep || ii.IsCaution || ii.IsNote) return; + } + } + } + } + else if (MyItemInfo.IsHigh && MyItemInfo.MyDocStyle != null && MyItemInfo.MyDocStyle.IncludeInTOC) // && (MyItemInfo.MyActiveSection.MyConfig as SectionConfig).Section_HLS_on_TOC == "Y") + { + // C2021-015: Barakah High Level Steps in Table of Contents + if ((MyItemInfo.ActiveSection.MyConfig is SectionConfig sc && sc.Section_TOC != "Y") && (MyItemInfo.MyConfig is StepConfig stc && stc.Step_IncludeInTOC)) + { + string tocKey = string.Format("TOC{0}", MyItemInfo.ItemID); + if (MyPageHelper.MyTOCPageCounts.ContainsKey(tocKey)) + { + PageCount pc = MyPageHelper.MyTOCPageCounts[tocKey]; + if (pc.Total == 0) + { + pc.Total = MyPageHelper.CurrentTOCPageNumber + 1; + pc.DrawTemplates(); - Box bx = ii.ActiveFormat.PlantFormat.FormatData.BoxList[0]; - float lpi = MyPageHelper.YMultiplier == 1.0 ? SixLinesPerInch : _SevenLinesPerInch; - bool savedebug = Rtf2Pdf.PdfDebug; - Rtf2Pdf.PdfDebug = false; - // follow through in fixing an Out of Window Handles bug, use new function to see if - // we can retrieve the font from a dictionary instead a doing a New and using another - // window handle B2017-117 - //System.Drawing.Font symbFont = new System.Drawing.Font("VESymbFix", (float)ii.FormatStepData.Font.Size); - System.Drawing.Font symbFont = VE_Font.GetWinSysFont("VESymbFix", (float)ii.FormatStepData.Font.Size); - iTextSharp.text.Font iSymblFont = Volian.Svg.Library.VolianPdf.GetFont(symbFont); - iSymblFont.Color = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Black)); - // The vertPos array from the format defines the column locations: - string[] vertPos = ii.MyHLS.FormatStepData.VertPos.Split(",".ToCharArray()); - // Count how many vertical lines are in the checklist table: - int cntVertPos = vertPos.Length - 1; - while (vertPos[cntVertPos] == "0" && cntVertPos > 0) cntVertPos--; - cntVertPos++; - Paragraph paraVertLine = new Paragraph(ii.ActiveFormat.PlantFormat.FormatData.BoxList[0].BXVert, iSymblFont); - float lWidth = 100; - float csize = 6 - .3f; // added the .3 to make line up with 16bit. + } + } + } + } + if (!doprint) return yPageStart; + if (_PartsLeft != null && _PartsLeft.Count > 0) yPageStart = PartsLeft.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + if (_PartsRight != null && _PartsRight.Count > 0) yPageStart = PartsRight.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + if (_PartsBelow != null && _PartsBelow.Count > 0) yPageStart = PartsBelow.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + if (_PartsContainer != null && _PartsContainer.Count > 0) yPageStart = PartsContainer.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - // if High Level Step, just need to do edges for number of lines: - if (ii.IsHigh) - { - // count # of '{\par} commands in prefix and suffix. - int countLine = 0; - string preSuf_Fix = (ii.FormatStepData.Prefix != null && ii.FormatStepData.Prefix != "") ? ii.FormatStepData.Prefix : null; - if (preSuf_Fix != null) countLine++; // account for a line of prefix (if no \par) - // if this is a proportional font, need to 'draw' the prefix/suffix. NOTE that the suffix should - // just list the headers and the prefix can be 'empty'. - if (ii.FormatStepData.Font.FontIsProportional()) - { - float yLocVertLine = yLocation + (lpi * 1.5F); // +(lpi / 2); - // Prefix, i.e. Top line: - Paragraph topLeftLine = new Paragraph(bx.BXULC, iSymblFont); - Rtf2Pdf.TextAt(cb, topLeftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Paragraph topRightLine = new Paragraph(bx.BXURC, iSymblFont); - Rtf2Pdf.TextAt(cb, topRightLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Paragraph horzLine = new Paragraph(bx.BXHorz, iSymblFont); - float thPos = float.Parse(vertPos[0]) + csize; - while (thPos < float.Parse(vertPos[cntVertPos - 1])) - { - Rtf2Pdf.TextAt(cb, horzLine, thPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - thPos += csize; - } + //if (localYPageStart != yPageStart) DebugText.WriteLine("ParToPdf-yPagestartDiff:{0},{1},{2}", MyItemInfo.ItemID, localYPageStart, yPageStart); + return yPageStart; + } - // Vertical Lines around HLS - //int countLine = (int)(this.Height / lpi); - yLocVertLine = yLocation + (lpi/2);// -(lpi / 2); - for (int i = 0; i < 1; i++) - { - Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - yLocVertLine -= lpi; - } + private float DrawRaw(PdfContentByte cb, float yLocation) + { + if (DebugText.IsOpen) DebugText.WriteLine("{0},'{1}','{2}','<>'", MyItemInfo.ItemID, MyItemInfo.DBSequence, FormattedText); + float retval = yLocation; + System.Drawing.Size sz = RtfRawItem.GetRtfRawSize(MyItemInfo.MyContent.Text); + Height = sz.Height; + Width = sz.Width; + Volian.Controls.Library.RTF myRtb = new RTF + { + Size = sz, + Rtf = MyItemInfo.MyContent.Text + }; + try + { + System.Drawing.Image image = new System.Drawing.Bitmap((int)Width, (int)Height); + System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(image); + myRtb.RenderClipped(gr, new System.Drawing.Rectangle(0, 0, (int)Width, (int)Height)); + // B2017-116 Adjust Image Size by Scaler (Used for Facing Pages - Sup Info) + // B2017-241 Adjust Bottom Message Location for the raw figure (Equation or Visio) + MyPageHelper.BottomContent = yLocation - (.6F * Height * MyPageHelper.YMultiplier * ImageScaler); + retval = Rtf2Pdf.RtfRawAt(cb, image, XOffset + MyItemInfo.FormatStepData.Font.CharsToTwips, yLocation, Width * MyPageHelper.YMultiplier * ImageScaler, Height * MyPageHelper.YMultiplier * ImageScaler, DebugInfo, !MyItemInfo.FormatStepData.Type.ToUpper().Contains("BORDERLESS")); + } + catch (Exception) + { + return retval + 2 * SixLinesPerInch; // couldn't print equation, just print 2 blank lines. + } + return retval; + } - // Suffix, i.e. Column headers. - // first do left/right side chars above and below column headers - //countLine = (int)(this.Height / lpi); - Paragraph sideLeftLine = new Paragraph(bx.BXMLS, iSymblFont); - Rtf2Pdf.TextAt(cb, sideLeftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Rtf2Pdf.TextAt(cb, sideLeftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - (2 * lpi), lWidth, 100, null, yBottomMargin); - Paragraph sideRightLine = new Paragraph(bx.BXMRS, iSymblFont); - Rtf2Pdf.TextAt(cb, sideRightLine, float.Parse(vertPos[6]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Rtf2Pdf.TextAt(cb, sideRightLine, float.Parse(vertPos[6]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - (2 * lpi), lWidth, 100, null, yBottomMargin); + public bool SectionContinuePrinted { get; set; } = false; + private void DrawChkOrValveTableLines(PdfContentByte cb, ItemInfo ii, float yPageStart, float yBottomMargin, float yLocation) + { + if (!ii.IsStep || ii.IsCaution || ii.IsNote) return; - // now do the lines with the 'T' type lines for top/bottom of vertical lines. - thPos = float.Parse(vertPos[0]) + csize; - while (thPos < float.Parse(vertPos[cntVertPos - 1])) - { - Rtf2Pdf.TextAt(cb, horzLine, thPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Rtf2Pdf.TextAt(cb, horzLine, thPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - (2 * lpi), lWidth, 100, null, yBottomMargin); - thPos += csize; - } + Box bx = ii.ActiveFormat.PlantFormat.FormatData.BoxList[0]; + float lpi = MyPageHelper.YMultiplier == 1.0 ? SixLinesPerInch : _SevenLinesPerInch; + bool savedebug = Rtf2Pdf.PdfDebug; + Rtf2Pdf.PdfDebug = false; + // follow through in fixing an Out of Window Handles bug, use new function to see if + // we can retrieve the font from a dictionary instead a doing a New and using another + // window handle B2017-117 + //System.Drawing.Font symbFont = new System.Drawing.Font("VESymbFix", (float)ii.FormatStepData.Font.Size); + System.Drawing.Font symbFont = VE_Font.GetWinSysFont("VESymbFix", (float)ii.FormatStepData.Font.Size); + iTextSharp.text.Font iSymblFont = Volian.Svg.Library.VolianPdf.GetFont(symbFont); + iSymblFont.Color = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Black)); + // The vertPos array from the format defines the column locations: + string[] vertPos = ii.MyHLS.FormatStepData.VertPos.Split(",".ToCharArray()); + // Count how many vertical lines are in the checklist table: + int cntVertPos = vertPos.Length - 1; + while (vertPos[cntVertPos] == "0" && cntVertPos > 0) cntVertPos--; + cntVertPos++; + Paragraph paraVertLine = new Paragraph(ii.ActiveFormat.PlantFormat.FormatData.BoxList[0].BXVert, iSymblFont); + float lWidth = 100; + float csize = 6 - .3f; // added the .3 to make line up with 16bit. - // now do the vertical bar between header words and the column header words. - yLocVertLine -= lpi; - string[] colHdrs = _MyItemInfo.FormatStepData.Suffix.Substring(_MyItemInfo.FormatStepData.Suffix.IndexOf(";") + 1).Split(",".ToCharArray()); - iTextSharp.text.Font iHdrFont = Volian.Svg.Library.VolianPdf.GetFont(_MyItemInfo.FormatStepData.Font.WindowsFont); - iHdrFont.Color = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Black)); + // if High Level Step, just need to do edges for number of lines: + if (ii.IsHigh) + { + // count # of '{\par} commands in prefix and suffix. + int countLine = 0; + string preSuf_Fix = (ii.FormatStepData.Prefix != null && ii.FormatStepData.Prefix != "") ? ii.FormatStepData.Prefix : null; + if (preSuf_Fix != null) countLine++; // account for a line of prefix (if no \par) + // if this is a proportional font, need to 'draw' the prefix/suffix. NOTE that the suffix should + // just list the headers and the prefix can be 'empty'. + if (ii.FormatStepData.Font.FontIsProportional()) + { + float yLocVertLine = yLocation + (lpi * 1.5F); // +(lpi / 2); + // Prefix, i.e. Top line: + Paragraph topLeftLine = new Paragraph(bx.BXULC, iSymblFont); + Rtf2Pdf.TextAt(cb, topLeftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Paragraph topRightLine = new Paragraph(bx.BXURC, iSymblFont); + Rtf2Pdf.TextAt(cb, topRightLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Paragraph horzLine = new Paragraph(bx.BXHorz, iSymblFont); + float thPos = float.Parse(vertPos[0]) + csize; + while (thPos < float.Parse(vertPos[cntVertPos - 1])) + { + Rtf2Pdf.TextAt(cb, horzLine, thPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + thPos += csize; + } - Paragraph topT = new Paragraph(bx.BXUMID, iSymblFont); - Paragraph crossT = new Paragraph(bx.BXMID, iSymblFont); + // Vertical Lines around HLS + yLocVertLine = yLocation + (lpi / 2);// -(lpi / 2); + for (int i = 0; i < 1; i++) + { + Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + yLocVertLine -= lpi; + } - for (int i = 0; i < cntVertPos; i++) - { - // do vertical line: - Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - // do the column header text - center it: - if (i < colHdrs.Length) - { - Paragraph parColHdr = new Paragraph(colHdrs[i], iHdrFont); - // find the center point of column header and subtract 1/2 width of the text to locate the text. - float hloc = (float.Parse(vertPos[i]) + ((float.Parse(vertPos[i + 1]) - float.Parse(vertPos[i])) / 2)); - Chunk chk = (Chunk)parColHdr.Chunks[0]; - hloc = hloc - (chk.GetWidthPoint() / 2); - Rtf2Pdf.TextAt(cb, parColHdr, hloc + (float)ii.MyDocStyle.Layout.LeftMargin, yLocVertLine, lWidth, 100, null, yBottomMargin); - } - // Do the crosswise table characters, i.e. T and + - if (i > 0 && i < colHdrs.Length) - { - Rtf2Pdf.TextAt(cb, topT, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine + lpi, lWidth, 100, null, yBottomMargin); - Rtf2Pdf.TextAt(cb, crossT, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - lpi, lWidth, 100, null, yBottomMargin); - } - } - } - else - #region OriginalHLS - { - int hIndx = preSuf_Fix.IndexOf(@"{\par}"); - while (preSuf_Fix != null && hIndx >= 0) - { - hIndx = preSuf_Fix.IndexOf(@"{\par}", hIndx + 1); - countLine++; - } - preSuf_Fix = (ii.FormatStepData.Suffix != null && ii.FormatStepData.Suffix != "") ? ii.FormatStepData.Suffix : null; - if (preSuf_Fix != null) countLine++; // account for a line of suffix (if no \par) - hIndx = preSuf_Fix.IndexOf(@"{\par}"); - while (preSuf_Fix != null && hIndx >= 0) - { - hIndx = preSuf_Fix.IndexOf(@"{\par}", hIndx + 1); - countLine++; - } - // get first and last vertpos for location of lines: - // for each line of text, draw the start & end box line: - countLine = (int)(this.Height / lpi) - countLine; - float yLocVertLine = yLocation - lpi / 2; - for (int i = 0; i < countLine; i++) - { - Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); - yLocVertLine -= lpi; - } - } - #endregion OriginalHLS - } - else - { - // This section of code draws the lines around the substeps (the actual table part) - Paragraph horzLine = new Paragraph(ii.ActiveFormat.PlantFormat.FormatData.BoxList[0].BXHorz, iSymblFont); - bool bottomOfTable = ii.NextItem == null || - (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].MyItemInfo.ItemID == ii.NextItem.ItemID); - // if bottom of table use different cross/beg/end chars than if in middle of table. - Paragraph leftLine = new Paragraph(bottomOfTable ? bx.BXLLC : bx.BXMLS, iSymblFont); - Paragraph rightLine = new Paragraph(bottomOfTable ? bx.BXLRC : bx.BXMRS, iSymblFont); + // Suffix, i.e. Column headers. + // first do left/right side chars above and below column headers + //For Debugging: countLine = (int)(this.Height / lpi); + Paragraph sideLeftLine = new Paragraph(bx.BXMLS, iSymblFont); + Rtf2Pdf.TextAt(cb, sideLeftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Rtf2Pdf.TextAt(cb, sideLeftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - (2 * lpi), lWidth, 100, null, yBottomMargin); + Paragraph sideRightLine = new Paragraph(bx.BXMRS, iSymblFont); + Rtf2Pdf.TextAt(cb, sideRightLine, float.Parse(vertPos[6]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Rtf2Pdf.TextAt(cb, sideRightLine, float.Parse(vertPos[6]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - (2 * lpi), lWidth, 100, null, yBottomMargin); - // If this item is in the leftmost column in table, this is determined by looking at its parent, - // its parent must be a HLS, do the vertical lines since all cells have all vertical lines. - // Lines should be drawn from current to ybottommost. Also draw the bottom line. - if (ii.MyParent.IsHigh) - { - // first do the vertical bars. - float curY = yLocation; - while (curY > (yPageStart - this.YBottomMost + lpi)) - { - for (int i = 0; i < cntVertPos; i++) - Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, curY + 3, lWidth, 100, null, yBottomMargin); - curY -= lpi; - } - // Now do the bottom line for this item. - Paragraph crossLine = new Paragraph(bottomOfTable ? bx.BXLMID : bx.BXMID, iSymblFont); - float yloc = yPageStart - this.YBottomMost + 18; - Rtf2Pdf.TextAt(cb, leftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); - float hPos = float.Parse(vertPos[0]) + csize; - int doHorizCnt = 0; - while (doHorizCnt < cntVertPos - 1) - { - while (hPos < float.Parse(vertPos[doHorizCnt + 1])) - { - Rtf2Pdf.TextAt(cb, horzLine, hPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); - hPos += csize; - } + // now do the lines with the 'T' type lines for top/bottom of vertical lines. + thPos = float.Parse(vertPos[0]) + csize; + while (thPos < float.Parse(vertPos[cntVertPos - 1])) + { + Rtf2Pdf.TextAt(cb, horzLine, thPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Rtf2Pdf.TextAt(cb, horzLine, thPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - (2 * lpi), lWidth, 100, null, yBottomMargin); + thPos += csize; + } - // put out middle piece, i.e. + (cross) lines or bottom line - hPos = float.Parse(vertPos[doHorizCnt + 1]); - if (doHorizCnt < cntVertPos - 2) // don't put out crossLine on last one. - Rtf2Pdf.TextAt(cb, crossLine, float.Parse(vertPos[doHorizCnt + 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); - hPos += csize; - doHorizCnt++; - } - // put out the right side piece - Rtf2Pdf.TextAt(cb, rightLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); - } - // Now handle middle parts of the table. For whatever sub level we're at, draw the cross character - // and the horizontal. This is case where the component number may have multiple descriptions,positions, etc. associated - // with it. - if (!ii.MyParent.IsHigh && ii.NextItem != null) - { - // draw horizontally from this sublevel to the end. - int sublev = 0; - ItemInfo par = this.MyItemInfo; - while (!par.IsHigh) - { - sublev++; - par = par.MyParent; - } - sublev--; - float ylocs = yPageStart - this.YBottomMost + 15; - for (int i = sublev; i < cntVertPos - 1; i++) - { - float hPos = float.Parse(vertPos[i]) + csize; - Rtf2Pdf.TextAt(cb, leftLine, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, ylocs, lWidth, 100, null, yBottomMargin); - while (hPos < float.Parse(vertPos[i + 1])) - { - // do the horizontal line - Rtf2Pdf.TextAt(cb, horzLine, hPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, ylocs, lWidth, 100, null, yBottomMargin); - hPos += csize; - } - } - // Do the last cross character - Rtf2Pdf.TextAt(cb, rightLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, ylocs, lWidth, 100, null, yBottomMargin); - } - } - Rtf2Pdf.PdfDebug = savedebug; - } - private float DrawGrid(PdfContentByte cb, ref float yPageStart, float yTopMargin, float yBottomMargin, ref float yLocation) - { - //DebugText.WriteLine("{0},'{1}','{2}','<>'", MyItemInfo.ItemID, MyItemInfo.ShortPath, FormattedText); - if (DebugText.IsOpen) DebugText.WriteLine("{0},'{1}','{2}','<>',{3}", MyItemInfo.ItemID, MyItemInfo.ShortPath, MyItemInfo.MyContent.Text, XOffset); - //if (MyItemInfo.InList(11019,11024,111026)) // RHM20150507 Table Scrunch - // Console.WriteLine("here"); - float heightBefore = (MyGrid.Height + 4) * MyPageHelper.YMultiplier; // B2020-014 added parenthesis was calculating wrong for 7lpi Callaway FSG-7 Attachment 7 - // B2018-033 Account for bottom continue message when seeing if a scrunched table will fit - float ySizeBtmCtnMess = GetBottomContinueMessageSize(MyItemInfo.MyDocStyle); - // B2018-085 Ignore the bottom continue message if the Table is the last part of the step. - if(ySizeBtmCtnMess > 0 && MyParent.MyItemInfo.IsHigh && YBottomMost == MyParent.YBottomMost) ySizeBtmCtnMess = 0; - // TableScrunch Phase 1: Is height of table greater than what will fit on current page. - if (Rtf2Pdf.GetTableScrunchingStatus(TableScrunching.Phase1) && heightBefore > (yLocation - (yBottomMargin + ySizeBtmCtnMess))) - { - // TooBig is the amount of height that the grid is larger than the amount of space on the page. It is set to - // (height of grid w/ compressed setting if needed + line) - (how much room on page) - // NOTE TooBig actually will do the adjustments of the row heights by eliminating the blank space! - MyGrid.TooBig = SixLinesPerInch + MyGrid.Height * MyPageHelper.YMultiplier - (yLocation - yBottomMargin - ySizeBtmCtnMess); - float heightAfter = (MyGrid.Height + 4) * MyPageHelper.YMultiplier; // B2020-014 added parenthesis was calculating wrong for 7lpi Callaway FSG-7 Attachment 7 - MyPageHelper.TableAdjustment += (heightBefore - heightAfter); - MyPageHelper.AdjustedTable = this; // B2020-059 - save the information of the table that is being compressed (used in RTF2PDF.cs TextAt()) - MyPageHelper.AdjustedTableYtop = yLocation; // B2020-059 save the top location of the compressed table (used in RTF2PDF.cs TextAt()) - //B2018-092 Determine if the Table is too big by checking it including either 6 LPI or 7 LPI as appropriate - if (heightAfter * MyPageHelper.YMultiplier < (yLocation - yBottomMargin - ySizeBtmCtnMess)) - { - // B2018-081 - Removed error log message if the code was able to properly adjust the table - //_MyLog.WarnFormat("\r\n==> Table is too big to fit on page, Vertical Padding adjusted to fit in\r\n" + - // " [{0}] {1}\r\n" + - // " in {2}\r\n" + - // " Height Before={3:N2} Height After={4:N2} SpaceAvailable={5:N2}\r\n" + - // " No action necessary", - // MyItemInfo.ItemID,_MyItemInfo.ShortPath, - // _MyItemInfo.SearchDVPath.Replace("\a", "/"), heightBefore / 72, MyGrid.Height / 72, (yTopMargin - yBottomMargin) / 72); - //_MyLog.ErrorFormat("<<< WARNING >>> Table is too big to fit on page, Vertical Padding adjusted to fit\r\n==>'Table Adjusted',{0},'{1}','{2}',{3},{4},{5}" - // , MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath, heightBefore, MyGrid.Height, (yTopMargin - yBottomMargin)); - } - else - MyGrid.IsTooBig = true; - if (MyItemInfo.HasChangeBar && MyPageHelper.ChangeBarDefinition.MyChangeBarType != PrintChangeBar.Without) - { - foreach (vlnChangeBar vcb in MyPageHelper.MyChangeBars) - { - if (vcb.Height == heightBefore / MyPageHelper.YMultiplier - 4) - { - float heightDif = (heightBefore - heightAfter); - vcb.YChangeBarBottom += heightDif; - FixMessages(vcb, heightDif); - break; - } - } - } - } - //B2018-092 Correct the location of the bottom continue message including either 6 LPI or 7 LPI as appropriate - MyPageHelper.BottomContent = yLocation - (MyGrid.Height + 4) * MyPageHelper.YMultiplier; - float retval = Rtf2Pdf.GridAt(cb, MyGrid, XOffset, yLocation, Width, 100, DebugInfo, yBottomMargin, !MyItemInfo.FormatStepData.Type.Contains("Borderless")); - //B2018-092 Determine if the Table is too big by checking it including either 6 LPI or 7 LPI as appropriate - if ((MyGrid.Height + 4)* MyPageHelper.YMultiplier > (yLocation - yBottomMargin - ySizeBtmCtnMess)) - { - // B2018-081 Changed the Error Log Message to be more useful when a table is too big. - _MyLog.ErrorFormat("\r\n===> Table is too big to fit on page, expect pagination problems in\r\n" + - " 1> Item [{0}] {1}\r\n" + - " 2> in {2}\r\n" + - " 3> Height Before={3:N2} Height After={4:N2} SpaceAvailable={5:N2}\r\n" + - " 4> ACTION REQUIRED: Table should be restructured or split over multiple pages", - MyItemInfo.ItemID, _MyItemInfo.ShortPath, - _MyItemInfo.SearchDVPath.Replace("\a", "/"), heightBefore/72, MyGrid.Height/72, (yTopMargin - yBottomMargin)/72); - //_MyLog.ErrorFormat("<<< ERROR >>> Table is too big to fit on page, expect pagination problems\r\n==>'Table Too Big',{0},'{1}','{2}',{3},{4},{5}" // RHM20150429 - Table Scrunch - // , MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath, heightBefore, MyGrid.Height, (yTopMargin - yBottomMargin)); - } - return retval; - } + // now do the vertical bar between header words and the column header words. + yLocVertLine -= lpi; + string[] colHdrs = MyItemInfo.FormatStepData.Suffix.Substring(MyItemInfo.FormatStepData.Suffix.IndexOf(";") + 1).Split(",".ToCharArray()); + iTextSharp.text.Font iHdrFont = Volian.Svg.Library.VolianPdf.GetFont(MyItemInfo.FormatStepData.Font.WindowsFont); + iHdrFont.Color = new iTextSharp.text.Color(PrintOverride.OverrideTextColor(System.Drawing.Color.Black)); - private void FixMessages(vlnChangeBar vcb, float heightDif) - { - SortedDictionary msd = vcb.Messages; - vcb.Messages = new SortedDictionary(); - foreach (float key in msd.Keys) - { - vcb.Messages.Add(key + heightDif, msd[key]); - } - } - private float DrawText(PdfContentByte cb, ref float yPageStart, float yTopMargin, float yBottomMargin, ref float yLocation) - { - if (DebugText.IsOpen) DebugText.WriteLine("{0},'{1}','{2}','<>'", MyItemInfo.ItemID, MyItemInfo.DBSequence, FormattedText); - //Console.WriteLine("{0},{1},'{2}','<>'", MyItemInfo.ItemID, MyItemInfo.DBSequence, IParagraph.Content); - float retval = yLocation; - if (MyItemInfo.IsRtfRaw) - { - retval = Rtf2Pdf.TextAt(cb, IParagraph, XOffset, yLocation, Width, 100, DebugInfo + string.Format(",YLines = {0}", YSize / SixLinesPerInch), yBottomMargin, MyItemInfo.ItemID); // C2018-004 ItemID for create meta file for baseline compares - return retval; - } + Paragraph topT = new Paragraph(bx.BXUMID, iSymblFont); + Paragraph crossT = new Paragraph(bx.BXMID, iSymblFont); - // Calvert Alarms have a special case, center text if the next/previous is not the same type of caution or note. - // Calvert Alarms have a note1 that is a warning. if a regular note preceeded it, this regular note was not centered. - // F2023-126: Vogtle Alarms - center single line caution/note if more than one type exist off step, added the check for NoteCautionCenterOneAllTypes - bool doAlign = false; - if ((MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert || MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoteCautionCenterOneAllTypes) && (MyItemInfo.IsCaution || MyItemInfo.IsNote || MyItemInfo.IsNote1)) - { - bool diffAsPrev = MyItemInfo.MyPrevious == null || (MyItemInfo.MyPrevious != null && MyItemInfo.MyContent.Type != MyItemInfo.MyPrevious.MyContent.Type); - bool diffAsNext = MyItemInfo.NextItem == null || (MyItemInfo.NextItem != null && MyItemInfo.MyContent.Type != MyItemInfo.NextItem.MyContent.Type); - if (diffAsPrev && diffAsNext) doAlign = true; - } - // Check if only one line, i.e. "Height < (1.2F * IParagraph.Leading". The Leading can be for six or seven lines per inch, so the 1.2 - // multiplier accounts for both. - // B2021-091 added a null reference check - MyItemInfo was a section and didn't have FormatStepData - // F2021-042: Added FormatStepData.AlwaysCenter for BNPP1 - Critical Step text always must be centered - // B2022-146: Left Justify Note & Caution text that has sub-steps (for Beaver Valley) - bool cnWithChildren = !MyItemInfo.IsStepSection && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.CenterOnlyIfNoSubs && MyItemInfo.HasChildren; - if (!MyItemInfo.IsStepSection && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.CenterOneLineOnly && !cnWithChildren && ((MyItemInfo.MyPrevious == null && MyItemInfo.NextItem == null) - || MyItemInfo.FormatStepData.SeparateBox || doAlign || MyItemInfo.FormatStepData.AlwaysCenter) && Height < (1.2F * IParagraph.Leading)) - IParagraph.Alignment = Element.ALIGN_CENTER; - // if this step is centered, but not part of the checklist or valvelist format, use itextsharp to center it. - // if it was part of the checklist or valvelist, then the centering is based on the column definitions for the table and - // was calculated when the paragraph was made. - // B2021-091 added a null reference check - MyItemInfo was a section and didn't have FormatStepData - if (!MyItemInfo.IsStepSection && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.StepPrintData.Justify == "Center" && !MyItemInfo.FormatStepData.StepLayoutData.AlignWithParentTab) - IParagraph.Alignment = Element.ALIGN_CENTER; - if (PrefixSpecialCharacter && IParagraph.Chunks.Count > 0) - { - Chunk chk = IParagraph.Chunks[0] as Chunk; - if (chk.Content == " ") - { - PrefixSpecialCharacter = false; - //Console.WriteLine("Special {0}", MyItemInfo.MyHLS.DisplayText); - IParagraph.Chunks.RemoveAt(0); - } - } - // if printing checklist header, adjust ypagestart & ylocation so that won't get forced pagination (pagination is already ok) - //Console.WriteLine("'Q1',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - if (PrintHeader) - { - yPageStart = yTopMargin + YVeryTop; - yLocation = yPageStart - YOffset; // yLocation is physical location from bottom of page. - } - if (yLocation - Height < 24) - { - if (DebugPagination.IsOpen) - DebugPagination.WriteLine("Very Low {0},{1},{2},{3},{4},{5}", MyItemInfo.ShortPath, MyItemInfo.ItemID, yLocation, Height, yLocation - Height, yTopMargin - MyItemInfo.MyDocStyle.Layout.PageLength); - //C2018-015 add debug pagination to meta file - if (BaselineMetaFile.IsOpen) - BaselineMetaFile.WriteLine("!! Very Low {0},{1},{2},{3},{4},{5}", MyItemInfo.ShortPath, MyItemInfo.ItemID, yLocation, Height, yLocation - Height, yTopMargin - MyItemInfo.MyDocStyle.Layout.PageLength); - } - int profileDepth = ProfileTimer.Push(">>>> Rtf2Pdf.TextAt"); - // ooooooooo. oooooooooo. oooooooooooo ooooooooooooo o8o . o8o - // `888 `Y88. `888' `Y8b `888' `8 8' 888 `8 `"' .o8 `"' - // 888 .d88' 888 888 888 888 oooo d8b .oooo. ooo. .oo. .oooo.o oooo .o888oo oooo .ooooo. ooo. .oo. .oooo.o - // 888ooo88P' 888 888 888oooo8 888 `888""8P `P )88b `888P"Y88b d88( "8 `888 888 `888 d88' `88b `888P"Y88b d88( "8 - // 888 888 888 888 " 888 888 .oP"888 888 888 `"Y88b. 888 888 888 888 888 888 888 `"Y88b. - // 888 888 d88' 888 888 888 d8( 888 888 888 o. )88b 888 888 . 888 888 888 888 888 o. )88b - // o888o o888bood8P' o888o o888o d888b `Y888""8o o888o o888o 8""888P' o888o "888" o888o `Y8bod8P' o888o o888o 8""888P' - // - // Design Suggestion: - // During vlnParagraaph Constuctor Build an end point dictionary - // During toPdf check for end points before adding GoTos for Local - // Need to have a way to get to sections which do not have any output (header only) - // Need to have a way to identify procedures - // - // B2018-034 The following code previously used IParagraph rather than _IParagraph. If the variable IsCompressed (7LPI) is true for this step - // IParagraph would be refreshed each time it was referenced. Thus the link information would be lost when the IParagraph was re-created. - // This resulted in PDFLinks to steps that were not not identified with a LocalDestination. This was changed from the original code to - // fix B2015-076 when the Byron Flex Procedure 0BFSG-6 was printed. The issue for this bug was that the underlining at 7LPI was overlaping the - // top of the next line of text. I was not able to find the case referencedd in the source safe document. However, by adding a line of - // text "One more line" to the end of step 2 in attachment C, I was able to see the effect. - if (_IParagraph.Chunks.Count > 0 && MyPageHelper.MyPromsPrinter.SaveLinks) - { - // B2018-034 The following code previously used IParagraph rather than _IParagraph. See first Comment - Chunk chk1 = _IParagraph.Chunks[0] as Chunk; - if (MyItemInfo.MyContent.Text.ToUpper().Contains("LINK:TR") && MyItemInfo.MyContent.ContentTransitionCount==0) - Console.WriteLine("Missing Transition {0}", MyItemInfo.ItemID); - chk1.SetLocalDestination(string.Format("ItemID={0}", MyItemInfo.ItemID)); // Destination - // B2019-052: If multiple ROs/Transitions within a step, each should have a their own link rather than all linking to same thing. - // Note the pdf link code that was here was moved to Rtf2iTextSharp.cs in DoVisitText so that each 'chunk' could have a link. - // The code that remained here was the code that marks the destination for each step & the code that does the pdf links for - // enhanced steps. - // Also, the method GetDefaultItemInfo was moved to Rtf2iTextSharp.cs also - it was only called from code that was moved. - - StepConfig sc = new StepConfig(MyItemInfo.MyContent.Config); - DVEnhancedDocuments dveds = MyItemInfo.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; - foreach (EnhancedDocument ed in sc.MyEnhancedDocuments) - { - DVEnhancedDocument dved = dveds.GetByType(ed.Type); - AddLinkToEnhancedDocument(cb, yLocation, ed.ItemID, dved.PdfToken, dved.PdfX); - } - // MyPageHelper.BottomContent = yLocation - Height; - //if (MyItemInfo.InList(39048)) Console.WriteLine("Here"); - } - MyPageHelper.BottomContent = yLocation - (Height * MyPageHelper.YMultiplier); - retval = Rtf2Pdf.TextAt(cb, IParagraph, XOffset, yLocation, Width, 100, DebugInfo + string.Format(",YLines = {0}", YSize / SixLinesPerInch), yBottomMargin, MyItemInfo.ItemID); // C2018-004 ItemID for create meta file for baseline compares - ProfileTimer.Pop(profileDepth); - if (retval == 0) // problem occurred - paragraph was not able to be printed on page - { // pagination logic needs to be fixed. - // oooooooooooo ooooooooo. o8o . o8o - // `888' `8 `888 `Y88. `"' .o8 `"' - // 888 .ooooo. oooo d8b .ooooo. .ooooo. 888 .d88' .oooo. .oooooooo oooo ooo. .oo. .oooo. .o888oo oooo .ooooo. ooo. .oo. - // 888oooo8 d88' `88b `888""8P d88' `"Y8 d88' `88b 888ooo88P' `P )88b 888' `88b `888 `888P"Y88b `P )88b 888 `888 d88' `88b `888P"Y88b - // 888 " 888 888 888 888 888ooo888 888 .oP"888 888 888 888 888 888 .oP"888 888 888 888 888 888 888 - // 888 888 888 888 888 .o8 888 .o 888 d8( 888 `88bod8P' 888 888 888 d8( 888 888 . 888 888 888 888 888 - // o888o `Y8bod8P' d888b `Y8bod8P' `Y8bod8P' o888o `Y888""8o `8oooooo. o888o o888o o888o `Y888""8o "888" o888o `Y8bod8P' o888o o888o - // d" YD - // "Y88888P' - ForcePagination(cb, ref yPageStart, yTopMargin, yBottomMargin, ref yLocation, ref retval); - } - else - { - if (MyItemInfo.IsStepSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert && (MyItemInfo.ActiveSection as SectionInfo).HasInitials) - { - if (MyPageHelper.PrintInitials(cb, yLocation, (float)MyItemInfo.MyDocStyle.Layout.LeftMargin)) - { - //if(yLocation != yTopMargin) - // Console.WriteLine("'{0}',{1},'{2}',{3},{4},{5},{6}", MyItemInfo.MyProcedure.DisplayNumber, MyItemInfo.ItemID - // , MyItemInfo.DisplayNumber, yLocation,yTopMargin,MyItemInfo.HasCautionOrNote,MyPageHelper.CurrentPageNumber+1); - } - } - } - return retval; - } - private static void AddLinkToEnhancedDocument(PdfContentByte cb, float yLocation, int itemID, String token, int xLocation) - { - ItemInfo ii = ItemInfo.Get(itemID); - //B2020-133 if "ii" is null, then the itemid was not found- probable enhanced step was deleted. so just return with out creating a link - if (ii == null) return; - string prefix = ii.MyDocVersion.DocVersionConfig.Print_PDFFilePrefix ?? ""; - string suffix = ii.MyDocVersion.DocVersionConfig.Print_PDFFileSuffix ?? ""; - ColumnText ct = new ColumnText(cb); - ct.SetSimpleColumn(xLocation, yLocation - 12, xLocation + 30, 12 + yLocation); - iTextSharp.text.Font font = FontFactory.GetFont("Arial", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); - Chunk chk = new Chunk(token); - chk.SetRemoteGoto(prefix + ii.MyProcedure.DisplayNumber.Replace("/", "_") + suffix + ".pdf", string.Format("ItemID={0}", itemID)); - chk.SetBackground(new Color(System.Drawing.Color.LemonChiffon)); - ct.AddElement(chk); - cb.SetColorFill(Color.BLUE); - ct.Go(); + for (int i = 0; i < cntVertPos; i++) + { + // do vertical line: + Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + // do the column header text - center it: + if (i < colHdrs.Length) + { + Paragraph parColHdr = new Paragraph(colHdrs[i], iHdrFont); + // find the center point of column header and subtract 1/2 width of the text to locate the text. + float hloc = (float.Parse(vertPos[i]) + ((float.Parse(vertPos[i + 1]) - float.Parse(vertPos[i])) / 2)); + Chunk chk = (Chunk)parColHdr.Chunks[0]; + hloc -= (chk.GetWidthPoint() / 2); + Rtf2Pdf.TextAt(cb, parColHdr, hloc + (float)ii.MyDocStyle.Layout.LeftMargin, yLocVertLine, lWidth, 100, null, yBottomMargin); + } + // Do the crosswise table characters, i.e. T and + + if (i > 0 && i < colHdrs.Length) + { + Rtf2Pdf.TextAt(cb, topT, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine + lpi, lWidth, 100, null, yBottomMargin); + Rtf2Pdf.TextAt(cb, crossT, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine - lpi, lWidth, 100, null, yBottomMargin); + } + } + } + else + #region OriginalHLS + { + int hIndx = preSuf_Fix.IndexOf(@"{\par}"); + while (preSuf_Fix != null && hIndx >= 0) + { + hIndx = preSuf_Fix.IndexOf(@"{\par}", hIndx + 1); + countLine++; + } + preSuf_Fix = (ii.FormatStepData.Suffix != null && ii.FormatStepData.Suffix != "") ? ii.FormatStepData.Suffix : null; + if (preSuf_Fix != null) countLine++; // account for a line of suffix (if no \par) + hIndx = preSuf_Fix.IndexOf(@"{\par}"); + while (preSuf_Fix != null && hIndx >= 0) + { + hIndx = preSuf_Fix.IndexOf(@"{\par}", hIndx + 1); + countLine++; + } + // get first and last vertpos for location of lines: + // for each line of text, draw the start & end box line: + countLine = (int)(this.Height / lpi) - countLine; + float yLocVertLine = yLocation - lpi / 2; + for (int i = 0; i < countLine; i++) + { + Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yLocVertLine, lWidth, 100, null, yBottomMargin); + yLocVertLine -= lpi; + } + } + #endregion OriginalHLS + } + else + { + // This section of code draws the lines around the substeps (the actual table part) + Paragraph horzLine = new Paragraph(ii.ActiveFormat.PlantFormat.FormatData.BoxList[0].BXHorz, iSymblFont); + bool bottomOfTable = ii.NextItem == null || + (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].MyItemInfo.ItemID == ii.NextItem.ItemID); + // if bottom of table use different cross/beg/end chars than if in middle of table. + Paragraph leftLine = new Paragraph(bottomOfTable ? bx.BXLLC : bx.BXMLS, iSymblFont); + Paragraph rightLine = new Paragraph(bottomOfTable ? bx.BXLRC : bx.BXMRS, iSymblFont); - //foreach (Chunk chk in IParagraph.Chunks) - //{ - // chk.SetRemoteGoto(ii.MyProcedure.DisplayNumber.Replace("/", "_") + ".pdf", string.Format("ItemID={0}",ii.ItemID)); - // chk.SetBackground(new Color(System.Drawing.Color.LemonChiffon)); - //} - } - private static bool _MissingInitials = false; + // If this item is in the leftmost column in table, this is determined by looking at its parent, + // its parent must be a HLS, do the vertical lines since all cells have all vertical lines. + // Lines should be drawn from current to ybottommost. Also draw the bottom line. + if (ii.MyParent.IsHigh) + { + // first do the vertical bars. + float curY = yLocation; + while (curY > (yPageStart - this.YBottomMost + lpi)) + { + for (int i = 0; i < cntVertPos; i++) + Rtf2Pdf.TextAt(cb, paraVertLine, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, curY + 3, lWidth, 100, null, yBottomMargin); + curY -= lpi; + } + // Now do the bottom line for this item. + Paragraph crossLine = new Paragraph(bottomOfTable ? bx.BXLMID : bx.BXMID, iSymblFont); + float yloc = yPageStart - this.YBottomMost + 18; + Rtf2Pdf.TextAt(cb, leftLine, float.Parse(vertPos[0]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); + float hPos = float.Parse(vertPos[0]) + csize; + int doHorizCnt = 0; + while (doHorizCnt < cntVertPos - 1) + { + while (hPos < float.Parse(vertPos[doHorizCnt + 1])) + { + Rtf2Pdf.TextAt(cb, horzLine, hPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); + hPos += csize; + } - public static bool MissingInitials - { - get { return vlnParagraph._MissingInitials; } - set { vlnParagraph._MissingInitials = value; } - } - public static void TextAt(PdfContentByte cb, VlnSvgPageHelper myPageHelper, PageItem pi, float yloc, float leftMargin) - { - System.Drawing.Color sysColor = PrintOverride.OverrideSvgColor(System.Drawing.Color.Black); - cb.SaveState(); - if (myPageHelper.PageListLayer != null) cb.BeginLayer(myPageHelper.PageListLayer); - ColumnText ct = new ColumnText(cb); - iTextSharp.text.Font font; - int fontStyle = 0; - bool underline = false; - if (pi == null) // The header for the signoffs is missing in the current section format. - // An Example can currently be found in Calvert OI-34 - { - if (!MissingInitials) // Only show this once. - { - _MyLog.WarnFormat("Initials Header Missing" + - "\r\nInitials header missing for section {0}" + - "\r\nfrom format [{1}], {2}, subformat {3}" + - "\r\nA default Arial font and a default location will be used." + - "\r\nPerhaps another section format should be used.", - myPageHelper.MySection.ShortPath, - myPageHelper.MySection.ActiveFormat.Name, - myPageHelper.MySection.ActiveFormat.Description, - myPageHelper.MySection.MyDocStyle.Name); - MissingInitials = true; - } - ct.SetSimpleColumn(450 + leftMargin, yloc + 6.9F, 550 + leftMargin, yloc - 50); - font = FontFactory.GetFont("Arial", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10F); - } - else - { - ct.SetSimpleColumn((float)pi.Col + leftMargin, yloc + 6.9F, (float)pi.Col + 100 + leftMargin, yloc - 50); - fontStyle = (pi.Font.WindowsFont.Bold ? iTextSharp.text.Font.BOLD : 0) + (pi.Font.WindowsFont.Italic ? iTextSharp.text.Font.ITALIC : 0); - font = FontFactory.GetFont(pi.Font.Family, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, (float)pi.Font.Size, fontStyle); - underline = pi.Font.WindowsFont.Underline; - } - Chunk chk = new Chunk("INITIALS", font); - if (underline) - chk.SetUnderline(new iTextSharp.text.Color(sysColor), 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND); // Relative Based upon font size - Phrase ph = new Phrase(chk); - ct.AddElement(ph); - cb.SetColorFill(new iTextSharp.text.Color(sysColor)); - ct.Go(); - if (myPageHelper.PageListLayer != null) cb.EndLayer(); - cb.RestoreState(); - } - private bool _PrintHeader = false; - public bool PrintHeader - { - get { return _PrintHeader; } - set { _PrintHeader = value; } - } - private bool CalvertPrintedSubSectTitle = false; // B2020-123 - private static List myAttributes = new List(); - private static void AddAttribute(string attr) - { - if (myAttributes.Contains(attr)) - return; - //Console.WriteLine("Attribute = \"{0}\"", attr); - myAttributes.Add(attr); - } - private void CheckAttributes(System.Collections.Hashtable attributes) - { - foreach (string attr in attributes.Keys) - { - AddAttribute(attr); - } - } - private string FormattedText - { - get - { - bool subscript = false; - //if (_MyItemInfo.ItemID == 467) - // Console.Write(""); - StringBuilder sb = new StringBuilder(); - //if (IParagraph.Chunks.Count > 1) - // Console.WriteLine("{0} Chunks", IParagraph.Chunks.Count); - foreach (Chunk chk in IParagraph.Chunks) - { - string prefix = ""; - string suffix = ""; - CheckAttributes(chk.Attributes); - if (chk.Font.BaseFont != null && chk.Font.BaseFont.PostscriptFontName.ToUpper().Contains("BOLD")) - { - prefix += "\xD5"; - suffix = "\xD6" + suffix; - } - if (chk.Attributes.ContainsKey("SUBSUPSCRIPT")) - { - float sup = (float)(chk.Attributes["SUBSUPSCRIPT"]); - if (sup > 0) - { - prefix += "\xA6"; - suffix = "\xD1" + suffix; - } - else if (sup < 0) - { - prefix += "\xD1"; - suffix = "\xA6" + suffix; - } + // put out middle piece, i.e. + (cross) lines or bottom line + hPos = float.Parse(vertPos[doHorizCnt + 1]); + if (doHorizCnt < cntVertPos - 2) // don't put out crossLine on last one. + Rtf2Pdf.TextAt(cb, crossLine, float.Parse(vertPos[doHorizCnt + 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); + hPos += csize; + doHorizCnt++; + } + // put out the right side piece + Rtf2Pdf.TextAt(cb, rightLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, yloc, lWidth, 100, null, yBottomMargin); + } + // Now handle middle parts of the table. For whatever sub level we're at, draw the cross character + // and the horizontal. This is case where the component number may have multiple descriptions,positions, etc. associated + // with it. + if (!ii.MyParent.IsHigh && ii.NextItem != null) + { + // draw horizontally from this sublevel to the end. + int sublev = 0; + ItemInfo par = this.MyItemInfo; + while (!par.IsHigh) + { + sublev++; + par = par.MyParent; + } + sublev--; + float ylocs = yPageStart - this.YBottomMost + 15; + for (int i = sublev; i < cntVertPos - 1; i++) + { + float hPos = float.Parse(vertPos[i]) + csize; + Rtf2Pdf.TextAt(cb, leftLine, float.Parse(vertPos[i]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, ylocs, lWidth, 100, null, yBottomMargin); + while (hPos < float.Parse(vertPos[i + 1])) + { + // do the horizontal line + Rtf2Pdf.TextAt(cb, horzLine, hPos + (float)ii.MyDocStyle.Layout.LeftMargin - csize, ylocs, lWidth, 100, null, yBottomMargin); + hPos += csize; + } + } + // Do the last cross character + Rtf2Pdf.TextAt(cb, rightLine, float.Parse(vertPos[cntVertPos - 1]) + (float)ii.MyDocStyle.Layout.LeftMargin - csize, ylocs, lWidth, 100, null, yBottomMargin); + } + } + Rtf2Pdf.PdfDebug = savedebug; + } + private float DrawGrid(PdfContentByte cb, float yTopMargin, float yBottomMargin, ref float yLocation) + { + //DebugText.WriteLine("{0},'{1}','{2}','<>'", MyItemInfo.ItemID, MyItemInfo.ShortPath, FormattedText); + if (DebugText.IsOpen) DebugText.WriteLine("{0},'{1}','{2}','<>',{3}", MyItemInfo.ItemID, MyItemInfo.ShortPath, MyItemInfo.MyContent.Text, XOffset); + //if (MyItemInfo.InList(11019,11024,111026)) // RHM20150507 Table Scrunch + // Console.WriteLine("here"); + float heightBefore = (MyGrid.Height + 4) * MyPageHelper.YMultiplier; // B2020-014 added parenthesis was calculating wrong for 7lpi Callaway FSG-7 Attachment 7 + // B2018-033 Account for bottom continue message when seeing if a scrunched table will fit + float ySizeBtmCtnMess = GetBottomContinueMessageSize(MyItemInfo.MyDocStyle); + // B2018-085 Ignore the bottom continue message if the Table is the last part of the step. + if (ySizeBtmCtnMess > 0 && MyParent.MyItemInfo.IsHigh && YBottomMost == MyParent.YBottomMost) ySizeBtmCtnMess = 0; + // TableScrunch Phase 1: Is height of table greater than what will fit on current page. + if (Rtf2Pdf.GetTableScrunchingStatus(TableScrunching.Phase1) && heightBefore > (yLocation - (yBottomMargin + ySizeBtmCtnMess))) + { + // TooBig is the amount of height that the grid is larger than the amount of space on the page. It is set to + // (height of grid w/ compressed setting if needed + line) - (how much room on page) + // NOTE TooBig actually will do the adjustments of the row heights by eliminating the blank space! + MyGrid.TooBig = SixLinesPerInch + MyGrid.Height * MyPageHelper.YMultiplier - (yLocation - yBottomMargin - ySizeBtmCtnMess); + float heightAfter = (MyGrid.Height + 4) * MyPageHelper.YMultiplier; // B2020-014 added parenthesis was calculating wrong for 7lpi Callaway FSG-7 Attachment 7 + MyPageHelper.TableAdjustment += (heightBefore - heightAfter); + MyPageHelper.AdjustedTable = this; // B2020-059 - save the information of the table that is being compressed (used in RTF2PDF.cs TextAt()) + MyPageHelper.AdjustedTableYtop = yLocation; // B2020-059 save the top location of the compressed table (used in RTF2PDF.cs TextAt()) + //B2018-092 Determine if the Table is too big by checking it including either 6 LPI or 7 LPI as appropriate + if (heightAfter * MyPageHelper.YMultiplier < (yLocation - yBottomMargin - ySizeBtmCtnMess)) + { + // B2018-081 - Removed error log message if the code was able to properly adjust the table + //_MyLog.WarnFormat("\r\n==> Table is too big to fit on page, Vertical Padding adjusted to fit in\r\n" + + // " [{0}] {1}\r\n" + + // " in {2}\r\n" + + // " Height Before={3:N2} Height After={4:N2} SpaceAvailable={5:N2}\r\n" + + // " No action necessary", + // MyItemInfo.ItemID,_MyItemInfo.ShortPath, + // _MyItemInfo.SearchDVPath.Replace("\a", "/"), heightBefore / 72, MyGrid.Height / 72, (yTopMargin - yBottomMargin) / 72); + //_MyLog.ErrorFormat("<<< WARNING >>> Table is too big to fit on page, Vertical Padding adjusted to fit\r\n==>'Table Adjusted',{0},'{1}','{2}',{3},{4},{5}" + // , MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath, heightBefore, MyGrid.Height, (yTopMargin - yBottomMargin)); + } + else + MyGrid.IsTooBig = true; + if (MyItemInfo.HasChangeBar && MyPageHelper.ChangeBarDefinition.MyChangeBarType != PrintChangeBar.Without) + { + foreach (vlnChangeBar vcb in MyPageHelper.MyChangeBars) + { + if (vcb.Height == heightBefore / MyPageHelper.YMultiplier - 4) + { + float heightDif = (heightBefore - heightAfter); + vcb.YChangeBarBottom += heightDif; + FixMessages(vcb, heightDif); + break; + } + } + } + } + //B2018-092 Correct the location of the bottom continue message including either 6 LPI or 7 LPI as appropriate + MyPageHelper.BottomContent = yLocation - (MyGrid.Height + 4) * MyPageHelper.YMultiplier; + float retval = Rtf2Pdf.GridAt(cb, MyGrid, XOffset, yLocation, Width, 100, DebugInfo, yBottomMargin, !MyItemInfo.FormatStepData.Type.Contains("Borderless")); + //B2018-092 Determine if the Table is too big by checking it including either 6 LPI or 7 LPI as appropriate + if ((MyGrid.Height + 4) * MyPageHelper.YMultiplier > (yLocation - yBottomMargin - ySizeBtmCtnMess)) + { + // B2018-081 Changed the Error Log Message to be more useful when a table is too big. + _MyLog.ErrorFormat("\r\n===> Table is too big to fit on page, expect pagination problems in\r\n" + + " 1> Item [{0}] {1}\r\n" + + " 2> in {2}\r\n" + + " 3> Height Before={3:N2} Height After={4:N2} SpaceAvailable={5:N2}\r\n" + + " 4> ACTION REQUIRED: Table should be restructured or split over multiple pages", + MyItemInfo.ItemID, MyItemInfo.ShortPath, + MyItemInfo.SearchDVPath.Replace("\a", "/"), heightBefore / 72, MyGrid.Height / 72, (yTopMargin - yBottomMargin) / 72); + //_MyLog.ErrorFormat("<<< ERROR >>> Table is too big to fit on page, expect pagination problems\r\n==>'Table Too Big',{0},'{1}','{2}',{3},{4},{5}" // RHM20150429 - Table Scrunch + // , MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath, heightBefore, MyGrid.Height, (yTopMargin - yBottomMargin)); + } + return retval; + } - } - if (chk.Attributes.ContainsKey("UNDERLINE")) - { - prefix += "\x16"; - suffix = "\x16" + suffix; ; - } - sb.Append(prefix + chk.Content + suffix); - } - string retval = sb.ToString(); - retval = retval.Replace("\xD1\xA6", "");// Remove Multiple Superscript commands in a row - retval = retval.Replace("\xA6\xD1", "");// Remove Multiple Superscript commands in a row - retval = retval.Replace("\xD6\xD5", ""); - retval = retval.Replace("\xD6\x16\xD5", "\x16"); - return retval; - } - } - private float _ImageScaler = 1F; - /// - /// Scaler used to adjust the Image Size on Sup Info (Facing Pages) - /// - public float ImageScaler - { - get { return _ImageScaler; } - set { _ImageScaler = value; } - } - //private bool _TextDebug = false; //true; this will turn on a writeline with debug in DrawText() - private float DrawFigure(PdfContentByte cb, float yBottomMargin, float yLocation, float yPageStart, float yTopMargin) - { - int profileDepth = ProfileTimer.Push("vlnParagraph.DrawFigure"); - float retval = yLocation; - if (ImageText != null) - { - if (ImageText == "figure") - { - ImageConfig ic = new ImageConfig(MyItemInfo.MyContent.MyImage); - // B2016-277: add a try catch in case of there being 'bad' data in the text field for an image/figure - try - { - byte[] idata = (ic != null && ic.Image_DataSize > 0) ? ROImageInfo.Decompress(MyItemInfo.MyContent.MyImage.Data, ic.Image_DataSize) : MyItemInfo.MyContent.MyImage.Data; - MemoryStream ms = new MemoryStream(idata); - System.Drawing.Image img = System.Drawing.Image.FromStream(ms); - Width = img.Width; - Height = img.Height; - if (ic != null && ic.Image_Height != 0) - { - Width = ic.Image_Width; - Height = ic.Image_Height; - } - // B2020-115 Limit the figure size to the space available in a page. - float mult = 1.0F; - if (Width > (vlnParagraph.wMax-12)) mult = (vlnParagraph.wMax-24) / Width; - if (Height > (vlnParagraph.hMax-36)) mult = Math.Min(mult, (vlnParagraph.hMax-36) / Height); - if (mult < 1.0F) - { - Width = Width * mult; - Height = Height * mult; - } - iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(idata); - // B2017-241 Adjust Bottom Message Location for the figure - MyPageHelper.BottomContent = yLocation - (Height * MyPageHelper.YMultiplier); - // B2017-112 Adjust Image Size by Scaler (Used for Facing Pages - Sup Info) - retval = Rtf2Pdf.FigureAt(cb, it_image, XOffset + MyItemInfo.FormatStepData.Font.CharsToTwips, yLocation, Width * MyPageHelper.YMultiplier * ImageScaler, Height * MyPageHelper.YMultiplier * ImageScaler, DebugInfo, yBottomMargin, !MyItemInfo.FormatStepData.Type.Contains("Borderless"), MyItemInfo.ItemID, SixLinesPerInch); // C2018-004 added ItemID for create meta file for baseline compares - } - catch - { - retval += SixLinesPerInch; - } - } - else - { - string[] vals = ImageText.Split("\n".ToCharArray()); - ProcedureInfo proc = MyItemInfo.MyProcedure; - DocVersionInfo dvi = proc.ActiveParent as DocVersionInfo; - ROFstInfo rofst = dvi.DocVersionAssociations[0].MyROFst; - ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); - if (roImage == null) roImage = rofst.GetROImageByFilename(vals[0], MyItemInfo);// need code to go and get an ROImaage if it exists - if (roImage != null) - { - ROImageConfig rc = new ROImageConfig(roImage); - int size = Convert.ToInt32(rc.Image_Size); - byte[] cnt = roImage.Content; - byte[] dcnt = ROImageInfo.Decompress(cnt, size); - iTextSharp.text.Image it_image = null; - try - { - it_image = iTextSharp.text.Image.GetInstance(dcnt); - } - catch - { - MemoryStream ms = new MemoryStream(dcnt); - System.Drawing.Bitmap bm = new System.Drawing.Bitmap(ms); - using (MemoryStream ms2 = new MemoryStream()) - { - bm.Save(ms2, System.Drawing.Imaging.ImageFormat.Png); - ms2.Seek(0, SeekOrigin.Begin); - byte[] newdcnt = new byte[ms2.Length]; - ms2.Read(newdcnt, 0, (int)ms2.Length); - try - { - it_image = iTextSharp.text.Image.GetInstance(newdcnt); - } - catch (Exception ex) - { - _MyLog.Error(string.Format("{0}", roImage.FileName), ex); - return yLocation; - } - } - } - StepInfo si = (StepInfo)MyItemInfo; - StepConfig sc = new StepConfig(si.MyContent.Config); - if (sc != null && sc.Step_ImageWidth != 0) - { - Width = sc.Step_ImageWidth; - Height = sc.Step_ImageHeight; - } - // B2017-241 Adjust Bottom Message Location for the figure - MyPageHelper.BottomContent = yLocation - (Height * MyPageHelper.YMultiplier); - retval = Rtf2Pdf.FigureAt(cb, it_image, XOffset + MyItemInfo.FormatStepData.Font.CharsToTwips, yLocation, Width * MyPageHelper.YMultiplier, Height * MyPageHelper.YMultiplier, DebugInfo, yBottomMargin, !MyItemInfo.FormatStepData.Type.Contains("Borderless"), MyItemInfo.ItemID, SixLinesPerInch); - } - } - // The following code was added to fix B2016-219 (for VCS, the centerline drew through a figure). The 'top' value was taken from the code - // that draws the vlnBoxes (Caution/Note, etc) - // The adjustments, adjtop & adjbottom, were necessary to get the vertical centerline to meet up correctly with the top/bottom of the figure. These - // numbers were determined by trial and error. + private void FixMessages(vlnChangeBar vcb, float heightDif) + { + SortedDictionary msd = vcb.Messages; + vcb.Messages = new SortedDictionary(); + foreach (float key in msd.Keys) + { + vcb.Messages.Add(key + heightDif, msd[key]); + } + } - // only add gap if centered, i.e. in 2 column mode & table is centered - if (MyItemInfo.ColumnMode > 0 && (!MyItemInfo.FormatStepData.Type.Contains("AER") && !MyItemInfo.IsInRNO)) - { - float top = CalculateYOffset(yPageStart, yTopMargin) - (7 * MyPageHelper.YMultiplier); - float adjtop = 0; - float adjbottom = 0; - if (MyPageHelper.YMultiplier == 1) - adjtop = -3; - else - adjbottom = -1; - MyPageHelper.MyGaps.Add(new Gap(top + adjtop, top - Height - Rtf2Pdf.Offset.Y + adjbottom)); - } - } - ProfileTimer.Pop(profileDepth); - return retval; - } - private string DebugInfo - { - get - { - if (!Rtf2Pdf.PdfDebug) return "No Path"; - int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.DebugInfo"); - string retval = string.Format("DebugID = {0}, ID={1} Type={2} TypeName='{3}' StepLevel={4} ShortPath={5} Width={6} Left={7} YOffset={8}, PaginationLevel = {9}, yPageSize = {10}", - DebugId, MyItemInfo.ItemID, MyItemInfo.FormatStepType, MyItemInfo.FormatStepData == null ? "NoStepData" : MyItemInfo.FormatStepData.Type, MyItemInfo.StepLevel, MyItemInfo.ShortPath, Width, XOffset, YOffset, levelForPagination, yPageSizeForPagination); - ProfileTimer.Pop(profileDepth); - return retval; - } - } - private void ResetDocStyleAndValues(ref float yTopMargin, ref float yBottomMargin) - { - float _PointsPerPage = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize); // C2020-002 paper size is now set in the format files - // if this document style has another style that is for pages other than first, we need to - // reset the document style off of this section AND reset docstyle values used. - // C2018-003 fixed use of getting the active section - if (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Where & E_DocStyleUse.UseOnFirstPage) > 0) - { - ItemInfo ii = (ItemInfo)MyItemInfo.ActiveSection; - int indx = (int)MyItemInfo.ActiveSection.MyDocStyle.IndexOtherThanFirstPage; - foreach (DocStyle ds in ii.ActiveFormat.PlantFormat.DocStyles.DocStyleList) - { - if (ds.Index == indx) - { - // C2018-004 create meta file for baseline compares - // B2020-008: removed some code that was causing the header to not get refreshed, and uncommented - // out the ResetSvg command below. - Volian.Base.Library.BaselineMetaFile.WriteLine("Reset DocStyle to \"{0}\"",ds.Name); - MyItemInfo.ActiveSection.MyDocStyle = ds; - MyPageHelper.MySection = MyItemInfo.ActiveSection as SectionInfo; - MyPageHelper.MySection.MyDocStyle = ds; - MyPageHelper.ResetSvg(); - break; - } - } - MyPageHelper.DidFirstPageDocStyle = true; - if (DebugPagination.IsOpen) DebugPagination.WriteLine("ResetDocStyleAndValues"); - if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! ResetDocStyleAndValues"); //C2018-015 add debug pagination to meta file - MyPageHelper.MySection = (SectionInfo)MyItemInfo.ActiveSection; - yTopMargin = _PointsPerPage - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin; - yBottomMargin = Math.Max(0, yTopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); - } - // B2020-047 move check of PrintSectionPage to after the ResetSvg - // B2020-152 un-did the change for B2020-047 which was put in for Westinghouse. The issue reported for B2020-047 remained corrected - else if (MyPageHelper.PrintedSectionPage > 0) - { - MyPageHelper.ResetSvg(); - if (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PrintSectOnFirst) == E_DocStructStyle.DSS_PrintSectOnFirst) - { - yTopMargin = _PointsPerPage - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin + MyPageHelper.PrintedSectionPage; - MyPageHelper.YTopMargin = yTopMargin; - yBottomMargin = Math.Max(0, _PointsPerPage - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); - } - } - } - private string GetSectCombinedTab(ItemInfo tmp) - { - ItemInfo itemInfo = tmp; - if (itemInfo.IsCautionOrNotePart) itemInfo = itemInfo.ActiveParent as ItemInfo; // if caution/note get to its associated step - itemInfo = itemInfo.ActiveParent as ItemInfo; // don't want this one in the combined tab, start at parent - // B2018-084: continue message had bullets in it that didn't have correct font. The message should not have had bullets at - // all - in the following line, there was an 'if' rather than a 'while' - go up parents until find the correct step type - // don't just go up 1 level. - while (!itemInfo.IsHigh && !itemInfo.IsSequential && !itemInfo.IsSection) itemInfo = itemInfo.ActiveParent as ItemInfo; - string prTab = ""; - string thisTab = itemInfo.MyTab.CleanText.Trim(); - if (!itemInfo.IsSection || itemInfo.IsSeparateSubsection) - { - ItemInfo mypar = itemInfo.MyParent; - while (mypar != null && !mypar.IsProcedure) - { - // The following check was added for BGE/OI34. Their APPENDIX sections had the subsections - // printing with incorrect tab in the SectionTitleContinued message. Before this - // fix the tabs were A.B Procedure (Continued) rather than B. Procedure (Continued). - // Unfortunately there was not enough time to make the 'if' statement based on config - // or format settings. - bool addTab = true; - if (mypar.IsSection && mypar.DisplayNumber.ToUpper().Contains("APPENDIX ")) - { - SectionConfig sch = mypar.MyConfig as SectionConfig; - addTab = (sch == null || sch.Section_PrintHdr == "Y");// && !mypar.MyDocStyle.CancelSectTitle; - } - if (addTab) - { - string pTab = mypar.MyTab.CleanText.Trim(); - if (pTab.Length > 0 && char.IsLetterOrDigit(pTab[0])) - { - pTab = pTab.TrimEnd(" .".ToCharArray()) + "."; - prTab = pTab + prTab; - } - else - { - // There' a bullet or some other graphics character. - // clear out the tab we are building so the we can build - // a continue tab up to this bullet or graphic character. - prTab = ""; - thisTab = ""; - } - } - mypar = (mypar.IsSection && !mypar.IsSeparateSubsection) ? null : mypar.MyParent; - } - } - return (prTab + thisTab.Trim()).TrimEnd(".".ToCharArray()); - } - private static bool DoSubs = true; // flag whether to print substeps (don't if doing continued checklist header) - public float AdjustForXBlankW1stLevSub = 0; // B2020-112 this & next line - protected float _ContinueHeight = 0; - public virtual float ContinueHeight - { - get - { - int profileDepth = ProfileTimer.Push(">>>> vlnPrintObject.ContinueHeight"); - if (_ContinueHeight == 0 - && MyItemInfo.MyDocStyle.Continue.Top.Message != null - && MyItemInfo.MyDocStyle.Continue.Top.Message.Contains("%s") - && MyItemInfo.MyDocStyle.Continue.Top.Message.ToUpper().EndsWith(" (Continued)".ToUpper())) - { - string suffix = MyItemInfo.MyDocStyle.Continue.Top.Message.Replace("%sR", "").Replace("%s", ""); - _ContinueHeight = GetParagraphHeight(MyContentByte, IParagraph, suffix, Width); - } - ProfileTimer.Pop(profileDepth); - return _ContinueHeight; - } - set { _Height = value; } - } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "retval kept for Debugging")] + private float DrawText(PdfContentByte cb, ref float yPageStart, float yTopMargin, float yBottomMargin, ref float yLocation) + { + if (DebugText.IsOpen) DebugText.WriteLine("{0},'{1}','{2}','<>'", MyItemInfo.ItemID, MyItemInfo.DBSequence, FormattedText); + //Console.WriteLine("{0},{1},'{2}','<>'", MyItemInfo.ItemID, MyItemInfo.DBSequence, IParagraph.Content); + float retval = yLocation; + if (MyItemInfo.IsRtfRaw) + { + retval = Rtf2Pdf.TextAt(cb, IParagraph, XOffset, yLocation, Width, 100, DebugInfo + string.Format(",YLines = {0}", YSize / SixLinesPerInch), yBottomMargin, MyItemInfo.ItemID); // C2018-004 ItemID for create meta file for baseline compares + return retval; + } + + // Calvert Alarms have a special case, center text if the next/previous is not the same type of caution or note. + // Calvert Alarms have a note1 that is a warning. if a regular note preceeded it, this regular note was not centered. + // F2023-126: Vogtle Alarms - center single line caution/note if more than one type exist off step, added the check for NoteCautionCenterOneAllTypes + bool doAlign = false; + if ((MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert || MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoteCautionCenterOneAllTypes) && (MyItemInfo.IsCaution || MyItemInfo.IsNote || MyItemInfo.IsNote1)) + { + bool diffAsPrev = MyItemInfo.MyPrevious == null || (MyItemInfo.MyPrevious != null && MyItemInfo.MyContent.Type != MyItemInfo.MyPrevious.MyContent.Type); + bool diffAsNext = MyItemInfo.NextItem == null || (MyItemInfo.NextItem != null && MyItemInfo.MyContent.Type != MyItemInfo.NextItem.MyContent.Type); + if (diffAsPrev && diffAsNext) doAlign = true; + } + // Check if only one line, i.e. "Height < (1.2F * IParagraph.Leading". The Leading can be for six or seven lines per inch, so the 1.2 + // multiplier accounts for both. + // B2021-091 added a null reference check - MyItemInfo was a section and didn't have FormatStepData + // F2021-042: Added FormatStepData.AlwaysCenter for BNPP1 - Critical Step text always must be centered + // B2022-146: Left Justify Note & Caution text that has sub-steps (for Beaver Valley) + bool cnWithChildren = !MyItemInfo.IsStepSection && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.CenterOnlyIfNoSubs && MyItemInfo.HasChildren; + if (!MyItemInfo.IsStepSection && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.CenterOneLineOnly && !cnWithChildren && ((MyItemInfo.MyPrevious == null && MyItemInfo.NextItem == null) + || MyItemInfo.FormatStepData.SeparateBox || doAlign || MyItemInfo.FormatStepData.AlwaysCenter) && Height < (1.2F * IParagraph.Leading)) + IParagraph.Alignment = Element.ALIGN_CENTER; + // if this step is centered, but not part of the checklist or valvelist format, use itextsharp to center it. + // if it was part of the checklist or valvelist, then the centering is based on the column definitions for the table and + // was calculated when the paragraph was made. + // B2021-091 added a null reference check - MyItemInfo was a section and didn't have FormatStepData + if (!MyItemInfo.IsStepSection && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.StepPrintData.Justify == "Center" && !MyItemInfo.FormatStepData.StepLayoutData.AlignWithParentTab) + IParagraph.Alignment = Element.ALIGN_CENTER; + if (PrefixSpecialCharacter && IParagraph.Chunks.Count > 0) + { + Chunk chk = IParagraph.Chunks[0] as Chunk; + if (chk.Content == " ") + { + PrefixSpecialCharacter = false; + //Console.WriteLine("Special {0}", MyItemInfo.MyHLS.DisplayText); + IParagraph.Chunks.RemoveAt(0); + } + } + // if printing checklist header, adjust ypagestart & ylocation so that won't get forced pagination (pagination is already ok) + //Console.WriteLine("'Q1',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); + if (PrintHeader) + { + yPageStart = yTopMargin + YVeryTop; + yLocation = yPageStart - YOffset; // yLocation is physical location from bottom of page. + } + if (yLocation - Height < 24) + { + if (DebugPagination.IsOpen) + DebugPagination.WriteLine("Very Low {0},{1},{2},{3},{4},{5}", MyItemInfo.ShortPath, MyItemInfo.ItemID, yLocation, Height, yLocation - Height, yTopMargin - MyItemInfo.MyDocStyle.Layout.PageLength); + //C2018-015 add debug pagination to meta file + if (BaselineMetaFile.IsOpen) + BaselineMetaFile.WriteLine("!! Very Low {0},{1},{2},{3},{4},{5}", MyItemInfo.ShortPath, MyItemInfo.ItemID, yLocation, Height, yLocation - Height, yTopMargin - MyItemInfo.MyDocStyle.Layout.PageLength); + } + int profileDepth = ProfileTimer.Push(">>>> Rtf2Pdf.TextAt"); + // ooooooooo. oooooooooo. oooooooooooo ooooooooooooo o8o . o8o + // `888 `Y88. `888' `Y8b `888' `8 8' 888 `8 `"' .o8 `"' + // 888 .d88' 888 888 888 888 oooo d8b .oooo. ooo. .oo. .oooo.o oooo .o888oo oooo .ooooo. ooo. .oo. .oooo.o + // 888ooo88P' 888 888 888oooo8 888 `888""8P `P )88b `888P"Y88b d88( "8 `888 888 `888 d88' `88b `888P"Y88b d88( "8 + // 888 888 888 888 " 888 888 .oP"888 888 888 `"Y88b. 888 888 888 888 888 888 888 `"Y88b. + // 888 888 d88' 888 888 888 d8( 888 888 888 o. )88b 888 888 . 888 888 888 888 888 o. )88b + // o888o o888bood8P' o888o o888o d888b `Y888""8o o888o o888o 8""888P' o888o "888" o888o `Y8bod8P' o888o o888o 8""888P' + // + // Design Suggestion: + // During vlnParagraaph Constuctor Build an end point dictionary + // During toPdf check for end points before adding GoTos for Local + // Need to have a way to get to sections which do not have any output (header only) + // Need to have a way to identify procedures + // + // B2018-034 The following code previously used IParagraph rather than _IParagraph. If the variable IsCompressed (7LPI) is true for this step + // IParagraph would be refreshed each time it was referenced. Thus the link information would be lost when the IParagraph was re-created. + // This resulted in PDFLinks to steps that were not not identified with a LocalDestination. This was changed from the original code to + // fix B2015-076 when the Byron Flex Procedure 0BFSG-6 was printed. The issue for this bug was that the underlining at 7LPI was overlaping the + // top of the next line of text. I was not able to find the case referencedd in the source safe document. However, by adding a line of + // text "One more line" to the end of step 2 in attachment C, I was able to see the effect. + if (_IParagraph.Chunks.Count > 0 && MyPageHelper.MyPromsPrinter.SaveLinks) + { + // B2018-034 The following code previously used IParagraph rather than _IParagraph. See first Comment + Chunk chk1 = _IParagraph.Chunks[0] as Chunk; + if (MyItemInfo.MyContent.Text.ToUpper().Contains("LINK:TR") && MyItemInfo.MyContent.ContentTransitionCount == 0) + Console.WriteLine("Missing Transition {0}", MyItemInfo.ItemID); + chk1.SetLocalDestination(string.Format("ItemID={0}", MyItemInfo.ItemID)); // Destination + // B2019-052: If multiple ROs/Transitions within a step, each should have a their own link rather than all linking to same thing. + // Note the pdf link code that was here was moved to Rtf2iTextSharp.cs in DoVisitText so that each 'chunk' could have a link. + // The code that remained here was the code that marks the destination for each step & the code that does the pdf links for + // enhanced steps. + // Also, the method GetDefaultItemInfo was moved to Rtf2iTextSharp.cs also - it was only called from code that was moved. + + StepConfig sc = new StepConfig(MyItemInfo.MyContent.Config); + DVEnhancedDocuments dveds = MyItemInfo.MyDocVersion.DocVersionConfig.MyEnhancedDocuments; + foreach (EnhancedDocument ed in sc.MyEnhancedDocuments) + { + DVEnhancedDocument dved = dveds.GetByType(ed.Type); + AddLinkToEnhancedDocument(cb, yLocation, ed.ItemID, dved.PdfToken, dved.PdfX); + } + } + MyPageHelper.BottomContent = yLocation - (Height * MyPageHelper.YMultiplier); + retval = Rtf2Pdf.TextAt(cb, IParagraph, XOffset, yLocation, Width, 100, DebugInfo + string.Format(",YLines = {0}", YSize / SixLinesPerInch), yBottomMargin, MyItemInfo.ItemID); // C2018-004 ItemID for create meta file for baseline compares + ProfileTimer.Pop(profileDepth); + if (retval == 0) // problem occurred - paragraph was not able to be printed on page + { // pagination logic needs to be fixed. + // oooooooooooo ooooooooo. o8o . o8o + // `888' `8 `888 `Y88. `"' .o8 `"' + // 888 .ooooo. oooo d8b .ooooo. .ooooo. 888 .d88' .oooo. .oooooooo oooo ooo. .oo. .oooo. .o888oo oooo .ooooo. ooo. .oo. + // 888oooo8 d88' `88b `888""8P d88' `"Y8 d88' `88b 888ooo88P' `P )88b 888' `88b `888 `888P"Y88b `P )88b 888 `888 d88' `88b `888P"Y88b + // 888 " 888 888 888 888 888ooo888 888 .oP"888 888 888 888 888 888 .oP"888 888 888 888 888 888 888 + // 888 888 888 888 888 .o8 888 .o 888 d8( 888 `88bod8P' 888 888 888 d8( 888 888 . 888 888 888 888 888 + // o888o `Y8bod8P' d888b `Y8bod8P' `Y8bod8P' o888o `Y888""8o `8oooooo. o888o o888o o888o `Y888""8o "888" o888o `Y8bod8P' o888o o888o + // d" YD + // "Y88888P' + ForcePagination(cb, ref yPageStart, yTopMargin, yBottomMargin, ref yLocation, ref retval); + } + else + { + if (MyItemInfo.IsStepSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert && (MyItemInfo.ActiveSection as SectionInfo).HasInitials) + { + if (MyPageHelper.PrintInitials(cb, yLocation, (float)MyItemInfo.MyDocStyle.Layout.LeftMargin)) + { + //if(yLocation != yTopMargin) + // Console.WriteLine("'{0}',{1},'{2}',{3},{4},{5},{6}", MyItemInfo.MyProcedure.DisplayNumber, MyItemInfo.ItemID + // , MyItemInfo.DisplayNumber, yLocation,yTopMargin,MyItemInfo.HasCautionOrNote,MyPageHelper.CurrentPageNumber+1); + } + } + } + return retval; + } + private static void AddLinkToEnhancedDocument(PdfContentByte cb, float yLocation, int itemID, String token, int xLocation) + { + ItemInfo ii = ItemInfo.Get(itemID); + //B2020-133 if "ii" is null, then the itemid was not found- probable enhanced step was deleted. so just return with out creating a link + if (ii == null) return; + string prefix = ii.MyDocVersion.DocVersionConfig.Print_PDFFilePrefix ?? ""; + string suffix = ii.MyDocVersion.DocVersionConfig.Print_PDFFileSuffix ?? ""; + ColumnText ct = new ColumnText(cb); + ct.SetSimpleColumn(xLocation, yLocation - 12, xLocation + 30, 12 + yLocation); + Chunk chk = new Chunk(token); + chk.SetRemoteGoto($"{prefix}{ii.MyProcedure.DisplayNumber.Replace("/", "_")}{suffix}.pdf", string.Format("ItemID={0}", itemID)); + chk.SetBackground(new Color(System.Drawing.Color.LemonChiffon)); + ct.AddElement(chk); + cb.SetColorFill(Color.BLUE); + ct.Go(); + + } + + public static bool MissingInitials { get; set; } = false; + public static void TextAt(PdfContentByte cb, VlnSvgPageHelper myPageHelper, PageItem pi, float yloc, float leftMargin) + { + System.Drawing.Color sysColor = PrintOverride.OverrideSvgColor(System.Drawing.Color.Black); + cb.SaveState(); + if (myPageHelper.PageListLayer != null) cb.BeginLayer(myPageHelper.PageListLayer); + ColumnText ct = new ColumnText(cb); + iTextSharp.text.Font font; + bool underline = false; + if (pi == null) // The header for the signoffs is missing in the current section format. + // An Example can currently be found in Calvert OI-34 + { + if (!MissingInitials) // Only show this once. + { + _MyLog.WarnFormat("Initials Header Missing" + + "\r\nInitials header missing for section {0}" + + "\r\nfrom format [{1}], {2}, subformat {3}" + + "\r\nA default Arial font and a default location will be used." + + "\r\nPerhaps another section format should be used.", + myPageHelper.MySection.ShortPath, + myPageHelper.MySection.ActiveFormat.Name, + myPageHelper.MySection.ActiveFormat.Description, + myPageHelper.MySection.MyDocStyle.Name); + MissingInitials = true; + } + ct.SetSimpleColumn(450 + leftMargin, yloc + 6.9F, 550 + leftMargin, yloc - 50); + font = FontFactory.GetFont("Arial", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10F); + } + else + { + ct.SetSimpleColumn((float)pi.Col + leftMargin, yloc + 6.9F, (float)pi.Col + 100 + leftMargin, yloc - 50); + int fontStyle = (pi.Font.WindowsFont.Bold ? iTextSharp.text.Font.BOLD : 0) + (pi.Font.WindowsFont.Italic ? iTextSharp.text.Font.ITALIC : 0); + font = FontFactory.GetFont(pi.Font.Family, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, (float)pi.Font.Size, fontStyle); + underline = pi.Font.WindowsFont.Underline; + } + Chunk chk = new Chunk("INITIALS", font); + if (underline) + chk.SetUnderline(new iTextSharp.text.Color(sysColor), 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND); // Relative Based upon font size + Phrase ph = new Phrase(chk); + ct.AddElement(ph); + cb.SetColorFill(new iTextSharp.text.Color(sysColor)); + ct.Go(); + if (myPageHelper.PageListLayer != null) cb.EndLayer(); + cb.RestoreState(); + } + + public bool PrintHeader { get; set; } = false; + private bool CalvertPrintedSubSectTitle = false; // B2020-123 + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private static List myAttributes = new List(); + private static void AddAttribute(string attr) + { + if (myAttributes.Contains(attr)) + return; + //Console.WriteLine("Attribute = \"{0}\"", attr); + myAttributes.Add(attr); + } + private void CheckAttributes(System.Collections.Hashtable attributes) + { + foreach (string attr in attributes.Keys) + { + AddAttribute(attr); + } + } + private string FormattedText + { + get + { + StringBuilder sb = new StringBuilder(); + //if (IParagraph.Chunks.Count > 1) + // Console.WriteLine("{0} Chunks", IParagraph.Chunks.Count); + foreach (Chunk chk in IParagraph.Chunks) + { + string prefix = ""; + string suffix = ""; + CheckAttributes(chk.Attributes); + if (chk.Font.BaseFont != null && chk.Font.BaseFont.PostscriptFontName.ToUpper().Contains("BOLD")) + { + prefix += "\xD5"; + suffix = "\xD6" + suffix; + } + if (chk.Attributes.ContainsKey("SUBSUPSCRIPT")) + { + float sup = (float)(chk.Attributes["SUBSUPSCRIPT"]); + if (sup > 0) + { + prefix += "\xA6"; + suffix = "\xD1" + suffix; + } + else if (sup < 0) + { + prefix += "\xD1"; + suffix = "\xA6" + suffix; + } + + } + if (chk.Attributes.ContainsKey("UNDERLINE")) + { + prefix += "\x16"; + suffix = "\x16" + suffix; ; + } + sb.Append(prefix + chk.Content + suffix); + } + string retval = sb.ToString(); + retval = retval.Replace("\xD1\xA6", "");// Remove Multiple Superscript commands in a row + retval = retval.Replace("\xA6\xD1", "");// Remove Multiple Superscript commands in a row + retval = retval.Replace("\xD6\xD5", ""); + retval = retval.Replace("\xD6\x16\xD5", "\x16"); + return retval; + } + } + + /// + /// Scaler used to adjust the Image Size on Sup Info (Facing Pages) + /// + public float ImageScaler { get; set; } = 1F; + //private bool _TextDebug = false; //true; this will turn on a writeline with debug in DrawText() + private float DrawFigure(PdfContentByte cb, float yLocation, float yPageStart, float yTopMargin) + { + int profileDepth = ProfileTimer.Push("vlnParagraph.DrawFigure"); + float retval = yLocation; + if (ImageText != null) + { + if (ImageText == "figure") + { + ImageConfig ic = new ImageConfig(MyItemInfo.MyContent.MyImage); + // B2016-277: add a try catch in case of there being 'bad' data in the text field for an image/figure + try + { + byte[] idata = (ic != null && ic.Image_DataSize > 0) ? ROImageInfo.Decompress(MyItemInfo.MyContent.MyImage.Data, ic.Image_DataSize) : MyItemInfo.MyContent.MyImage.Data; + MemoryStream ms = new MemoryStream(idata); + System.Drawing.Image img = System.Drawing.Image.FromStream(ms); + Width = img.Width; + Height = img.Height; + if (ic != null && ic.Image_Height != 0) + { + Width = ic.Image_Width; + Height = ic.Image_Height; + } + // B2020-115 Limit the figure size to the space available in a page. + float mult = 1.0F; + if (Width > (vlnParagraph.wMax - 12)) mult = (vlnParagraph.wMax - 24) / Width; + if (Height > (vlnParagraph.hMax - 36)) mult = Math.Min(mult, (vlnParagraph.hMax - 36) / Height); + if (mult < 1.0F) + { + Width *= mult; + Height *= mult; + } + iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(idata); + // B2017-241 Adjust Bottom Message Location for the figure + MyPageHelper.BottomContent = yLocation - (Height * MyPageHelper.YMultiplier); + // B2017-112 Adjust Image Size by Scaler (Used for Facing Pages - Sup Info) + retval = Rtf2Pdf.FigureAt(cb, it_image, XOffset + MyItemInfo.FormatStepData.Font.CharsToTwips, yLocation, Width * MyPageHelper.YMultiplier * ImageScaler, Height * MyPageHelper.YMultiplier * ImageScaler, DebugInfo, !MyItemInfo.FormatStepData.Type.Contains("Borderless"), MyItemInfo.ItemID, SixLinesPerInch); // C2018-004 added ItemID for create meta file for baseline compares + } + catch + { + retval += SixLinesPerInch; + } + } + else + { + string[] vals = ImageText.Split("\n".ToCharArray()); + ProcedureInfo proc = MyItemInfo.MyProcedure; + DocVersionInfo dvi = proc.ActiveParent as DocVersionInfo; + ROFstInfo rofst = dvi.DocVersionAssociations[0].MyROFst; + ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]) ?? rofst.GetROImageByFilename(vals[0], MyItemInfo); + if (roImage != null) + { + ROImageConfig rc = new ROImageConfig(roImage); + int size = Convert.ToInt32(rc.Image_Size); + byte[] cnt = roImage.Content; + byte[] dcnt = ROImageInfo.Decompress(cnt, size); + iTextSharp.text.Image it_image = null; + try + { + it_image = iTextSharp.text.Image.GetInstance(dcnt); + } + catch + { + MemoryStream ms = new MemoryStream(dcnt); + System.Drawing.Bitmap bm = new System.Drawing.Bitmap(ms); + using (MemoryStream ms2 = new MemoryStream()) + { + bm.Save(ms2, System.Drawing.Imaging.ImageFormat.Png); + ms2.Seek(0, SeekOrigin.Begin); + byte[] newdcnt = new byte[ms2.Length]; + ms2.Read(newdcnt, 0, (int)ms2.Length); + try + { + it_image = iTextSharp.text.Image.GetInstance(newdcnt); + } + catch (Exception ex) + { + _MyLog.Error(string.Format("{0}", roImage.FileName), ex); + return yLocation; + } + } + } + StepInfo si = (StepInfo)MyItemInfo; + StepConfig sc = new StepConfig(si.MyContent.Config); + if (sc != null && sc.Step_ImageWidth != 0) + { + Width = sc.Step_ImageWidth; + Height = sc.Step_ImageHeight; + } + // B2017-241 Adjust Bottom Message Location for the figure + MyPageHelper.BottomContent = yLocation - (Height * MyPageHelper.YMultiplier); + retval = Rtf2Pdf.FigureAt(cb, it_image, XOffset + MyItemInfo.FormatStepData.Font.CharsToTwips, yLocation, Width * MyPageHelper.YMultiplier, Height * MyPageHelper.YMultiplier, DebugInfo, !MyItemInfo.FormatStepData.Type.Contains("Borderless"), MyItemInfo.ItemID, SixLinesPerInch); + } + } + // The following code was added to fix B2016-219 (for VCS, the centerline drew through a figure). The 'top' value was taken from the code + // that draws the vlnBoxes (Caution/Note, etc) + // The adjustments, adjtop & adjbottom, were necessary to get the vertical centerline to meet up correctly with the top/bottom of the figure. These + // numbers were determined by trial and error. + + // only add gap if centered, i.e. in 2 column mode & table is centered + if (MyItemInfo.ColumnMode > 0 && (!MyItemInfo.FormatStepData.Type.Contains("AER") && !MyItemInfo.IsInRNO)) + { + float top = CalculateYOffset(yPageStart, yTopMargin) - (7 * MyPageHelper.YMultiplier); + float adjtop = 0; + float adjbottom = 0; + if (MyPageHelper.YMultiplier == 1) + adjtop = -3; + else + adjbottom = -1; + MyPageHelper.MyGaps.Add(new Gap(top + adjtop, top - Height - Rtf2Pdf.Offset.Y + adjbottom)); + } + } + ProfileTimer.Pop(profileDepth); + return retval; + } + private string DebugInfo + { + get + { + if (!Rtf2Pdf.PdfDebug) return "No Path"; + int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.DebugInfo"); + string retval = string.Format("DebugID = {0}, ID={1} Type={2} TypeName='{3}' StepLevel={4} ShortPath={5} Width={6} Left={7} YOffset={8}, PaginationLevel = {9}, yPageSize = {10}", + DebugId, MyItemInfo.ItemID, MyItemInfo.FormatStepType, MyItemInfo.FormatStepData == null ? "NoStepData" : MyItemInfo.FormatStepData.Type, MyItemInfo.StepLevel, MyItemInfo.ShortPath, Width, XOffset, YOffset, levelForPagination, yPageSizeForPagination); + ProfileTimer.Pop(profileDepth); + return retval; + } + } + private void ResetDocStyleAndValues(ref float yTopMargin, ref float yBottomMargin) + { + float _PointsPerPage = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize); // C2020-002 paper size is now set in the format files + // if this document style has another style that is for pages other than first, we need to + // reset the document style off of this section AND reset docstyle values used. + // C2018-003 fixed use of getting the active section + if (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Where & E_DocStyleUse.UseOnFirstPage) > 0) + { + ItemInfo ii = (ItemInfo)MyItemInfo.ActiveSection; + int indx = (int)MyItemInfo.ActiveSection.MyDocStyle.IndexOtherThanFirstPage; + foreach (DocStyle ds in ii.ActiveFormat.PlantFormat.DocStyles.DocStyleList) + { + if (ds.Index == indx) + { + // C2018-004 create meta file for baseline compares + // B2020-008: removed some code that was causing the header to not get refreshed, and uncommented + // out the ResetSvg command below. + Volian.Base.Library.BaselineMetaFile.WriteLine("Reset DocStyle to \"{0}\"", ds.Name); + MyItemInfo.ActiveSection.MyDocStyle = ds; + MyPageHelper.MySection = MyItemInfo.ActiveSection as SectionInfo; + MyPageHelper.MySection.MyDocStyle = ds; + MyPageHelper.ResetSvg(); + break; + } + } + MyPageHelper.DidFirstPageDocStyle = true; + if (DebugPagination.IsOpen) DebugPagination.WriteLine("ResetDocStyleAndValues"); + if (BaselineMetaFile.IsOpen) BaselineMetaFile.WriteLine("!! ResetDocStyleAndValues"); //C2018-015 add debug pagination to meta file + MyPageHelper.MySection = (SectionInfo)MyItemInfo.ActiveSection; + yTopMargin = _PointsPerPage - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin; + yBottomMargin = Math.Max(0, yTopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); + } + // B2020-047 move check of PrintSectionPage to after the ResetSvg + // B2020-152 un-did the change for B2020-047 which was put in for Westinghouse. The issue reported for B2020-047 remained corrected + else if (MyPageHelper.PrintedSectionPage > 0) + { + MyPageHelper.ResetSvg(); + if (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PrintSectOnFirst) == E_DocStructStyle.DSS_PrintSectOnFirst) + { + yTopMargin = _PointsPerPage - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin + MyPageHelper.PrintedSectionPage; + MyPageHelper.YTopMargin = yTopMargin; + yBottomMargin = Math.Max(0, _PointsPerPage - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); + } + } + } + private string GetSectCombinedTab(ItemInfo tmp) + { + ItemInfo itemInfo = tmp; + if (itemInfo.IsCautionOrNotePart) itemInfo = itemInfo.ActiveParent as ItemInfo; // if caution/note get to its associated step + itemInfo = itemInfo.ActiveParent as ItemInfo; // don't want this one in the combined tab, start at parent + // B2018-084: continue message had bullets in it that didn't have correct font. The message should not have had bullets at + // all - in the following line, there was an 'if' rather than a 'while' - go up parents until find the correct step type + // don't just go up 1 level. + while (!itemInfo.IsHigh && !itemInfo.IsSequential && !itemInfo.IsSection) itemInfo = itemInfo.ActiveParent as ItemInfo; + string prTab = ""; + string thisTab = itemInfo.MyTab.CleanText.Trim(); + if (!itemInfo.IsSection || itemInfo.IsSeparateSubsection) + { + ItemInfo mypar = itemInfo.MyParent; + while (mypar != null && !mypar.IsProcedure) + { + // The following check was added for BGE/OI34. Their APPENDIX sections had the subsections + // printing with incorrect tab in the SectionTitleContinued message. Before this + // fix the tabs were A.B Procedure (Continued) rather than B. Procedure (Continued). + // Unfortunately there was not enough time to make the 'if' statement based on config + // or format settings. + bool addTab = true; + if (mypar.IsSection && mypar.DisplayNumber.ToUpper().Contains("APPENDIX ")) + { + addTab = (!(mypar.MyConfig is SectionConfig sch) || sch.Section_PrintHdr == "Y");// && !mypar.MyDocStyle.CancelSectTitle; + } + if (addTab) + { + string pTab = mypar.MyTab.CleanText.Trim(); + if (pTab.Length > 0 && char.IsLetterOrDigit(pTab[0])) + { + pTab = $"{pTab.TrimEnd(" .".ToCharArray())}."; + prTab = pTab + prTab; + } + else + { + // There' a bullet or some other graphics character. + // clear out the tab we are building so the we can build + // a continue tab up to this bullet or graphic character. + prTab = ""; + thisTab = ""; + } + } + mypar = (mypar.IsSection && !mypar.IsSeparateSubsection) ? null : mypar.MyParent; + } + } + return (prTab + thisTab.Trim()).TrimEnd(".".ToCharArray()); + } + private static bool DoSubs = true; // flag whether to print substeps (don't if doing continued checklist header) + public float AdjustForXBlankW1stLevSub = 0; // B2020-112 this & next line + protected float _ContinueHeight = 0; + public virtual float ContinueHeight + { + get + { + int profileDepth = ProfileTimer.Push(">>>> vlnPrintObject.ContinueHeight"); + if (_ContinueHeight == 0 + && MyItemInfo.MyDocStyle.Continue.Top.Message != null + && MyItemInfo.MyDocStyle.Continue.Top.Message.Contains("%s") + && MyItemInfo.MyDocStyle.Continue.Top.Message.ToUpper().EndsWith(" (Continued)".ToUpper())) + { + string suffix = MyItemInfo.MyDocStyle.Continue.Top.Message.Replace("%sR", "").Replace("%s", ""); + _ContinueHeight = GetParagraphHeight(MyContentByte, IParagraph, suffix, Width); + } + ProfileTimer.Pop(profileDepth); + return _ContinueHeight; + } + set { _Height = value; } + } // Check if the parent section has both an editable steps section and a sub-section private bool ParentHasSectionAndSteps() { @@ -1606,5774 +1517,5454 @@ namespace Volian.Print.Library SectionInfo parent = MyItemInfo.ActiveParent as SectionInfo; bool hasSteps = false; bool hasSections = false; - foreach(PartInfo pi in parent.MyContent.ContentParts) + foreach (PartInfo pi in parent.MyContent.ContentParts) { if (pi.FromType == (int)E_FromType.Step && parent.SectionConfig.SubSection_Edit == "Y") hasSteps = true; if (pi.FromType == (int)E_FromType.Section) hasSections = true; } return hasSteps && hasSections; } - public override float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) - { - int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.ToPdf"); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "yLocation and yPageStart kept for Debugging")] + public override float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) + { + int profileDepth = ProfileTimer.Push(">>>> vlnParagraph.ToPdf"); if (MyItemInfo.ActiveFormat.Name.ToUpper().StartsWith("FNP") && MyItemInfo.IsSection && ParentHasSectionAndSteps()) MyPageHelper.BottomMessage.Clear(); // B2017-266 reset the END message on the sub-section - if (MyItemInfo.IsFootnote && Processed) - { - ProfileTimer.Pop(profileDepth); - return yPageStart; - } - if (MyItemInfo.IsInSupInfo) // if generating the pdf for supinfos (facing page) pdf, need a different cb to go to that file. - { - MyContentByte = cb; - MyPageHelper = null; - } - bool doThreeContinues = false; - // For BGE, the very first subsection's pagelist items were not correct - the section/meta section titles were - // at the wrong level. Reset the page helper's section. - if (MyItemInfo.IsStepSection) - { - if (MyItemInfo.IsSection && MyItemInfo.MyPrevious == null && MyItemInfo.MyParent.IsSection && !MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseWestinghouse) - { - // don't do the following for the WCN training format: - // if parent was continuous & this is separate, don't reset document style to subsection (next page) type - // this was putting incorrect pagelist item on parent section's page. This occurred in BGE/OI3 set/OI-7 procedure/10.0 Attachments. + if (MyItemInfo.IsFootnote && Processed) + { + ProfileTimer.Pop(profileDepth); + return yPageStart; + } + if (MyItemInfo.IsInSupInfo) // if generating the pdf for supinfos (facing page) pdf, need a different cb to go to that file. + { + MyContentByte = cb; + MyPageHelper = null; + } + bool doThreeContinues = false; + // For BGE, the very first subsection's pagelist items were not correct - the section/meta section titles were + // at the wrong level. Reset the page helper's section. + if (MyItemInfo.IsStepSection) + { + if (MyItemInfo.IsSection && MyItemInfo.MyPrevious == null && MyItemInfo.MyParent.IsSection && !MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseWestinghouse) + { + // don't do the following for the WCN training format: + // if parent was continuous & this is separate, don't reset document style to subsection (next page) type + // this was putting incorrect pagelist item on parent section's page. This occurred in BGE/OI3 set/OI-7 procedure/10.0 Attachments. // B2017-273 added a check for Farley format, we don't want the subsection pagelist infor to appear on the parent section page - works with Paginate() logic - (section has steps and a sub-section ex: FNP-2-EEP-0 Attachment 4) if (!MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining && !MyItemInfo.ActiveFormat.Name.ToUpper().StartsWith("FNP") && (MyParent.MyItemInfo as SectionInfo).IsSeparatePagination() || !(MyItemInfo as SectionInfo).IsSeparatePagination()) - { - MyPageHelper.MySection = MyItemInfo as SectionInfo; - MyPageHelper.ResetSvg(); - } - } - } - // For Calvert Alarms: A macro exists around the CONDITION/RESPONSE portion. If the page break occurs so that - // this 'table' moved to the following page AND there is an associated note/caution that is not on the next page, - // remove the macro so that the header macro doesn't print on the page with the note (without this, an extraneous - // header for the 'table'is printed. - if (PartsLeft.Count != 0 && (PartsLeft[0] is vlnMacro) && MyPageHelper.ParaBreaks.Count != 0 && MyPageHelper.ParaBreaks[0].MyItemInfo.MyPrevious == null) - if (!MyPageHelper.ParaBreaks[0].MyItemInfo.IsNote && !MyPageHelper.ParaBreaks[0].MyItemInfo.IsCaution) - { - // Only clear the header if it is the first child below - if (ChildrenBelow[0].MyItemInfo.ItemID == MyPageHelper.ParaBreaks[0].MyItemInfo.ItemID) - PartsLeft.Clear(); - //else - // _MyLog.WarnFormat("Would Have Cleared PageHeader '{0}','{1}'", MyItemInfo.MyProcedure.DisplayNumber, MyItemInfo.MyHLS.DisplayText); - } - if (IsWordDocPara) - { - SectionInfo si = SectionInfo.Get(MyItemInfo.ItemID); - //Changing this caused Header issues for FNP FNP-1-FRP-1.3 Attachment 3 (Word Sub-Sections) - //SectionInfo si1 = MyItemInfo.GetSectionInfo(); - //CompareSectionInfo(si, si1); - MyPromsPrinter.NewPage(true); - //_MyLog.InfoFormat("NewPage 9 {0}", cb.PdfWriter.CurrentPageNumber); - // Add Bookmark for Word Subsections - MyPageHelper.PageBookmarks.Add(si, ((si.DisplayNumber ?? "") == "" ? "" : si.DisplayNumber + " - ") + si.DisplayText, null); - MyPageHelper.MyPromsPrinter.CreateWordDocPdf(cb, si); - Processed = true; - { - ProfileTimer.Pop(profileDepth); - return yPageStart; - } - } - float yLocalypagestart = yPageStart; - // yPageStart is offset into roll; YTopMost is offset of topmost of this paragraph. - float yLocation = yPageStart - YTopMost; - - // If this document style has a pagelist item with a continue (some IP2BCK docstyles), clear - // out the variable that flags a continue message - MyPageHelper.OldTemplateContMsg = false; - - if (DebugText.IsOpen) DebugText.WriteLine("ToPdf1:{0},'{1}',{2},{3},{4},{5}", MyItemInfo.ItemID, MyItemInfo.ShortPath, XOffset, yLocation, yPageStart, YTopMost); - int profileDepth1 = ProfileTimer.Push(">>>> vlnParagraph.Paginate"); - int paginate = Paginate(yLocation, yTopMargin, yBottomMargin); - ProfileTimer.Pop(profileDepth1); - bool firstHighLevelStep = MyItemInfo.IsHigh && (MyItemInfo.MyPrevious == null); - bool doSectionTitleContinued = false; // will add " Continued" to the section title if format flag is set - DocStyle docstyle = null; - // If SAMG facing page print & doing first pass to generate page break list of supplemental info and - // there was a page break in the step section, but not an associated supinfo item, do the page break when the - // next supinfo item is found: - SectionInfo supInfoSect = MyItemInfo.ActiveSection as SectionInfo; // C2018-003 fixed use of getting the active section - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks && MyPromsPrinter.NeedSupInfoBreak && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) - { - // if this has a caution/note with supinfo, that is id that needs to go in pagination list, unless it is in there. - int aboveSupinfoId = ChildrenAboveHaveSupInfo(); - if (supInfoSect != null) - { - if (supInfoSect.StepSectPageBreaksForSupInfo.Contains(aboveSupinfoId)) aboveSupinfoId = -1; - supInfoSect.StepSectPageBreaksForSupInfo.Add(aboveSupinfoId != -1 ? aboveSupinfoId : MyItemInfo.SupInfos[0].ItemID); - } - MyPromsPrinter.NeedSupInfoBreak = false; - } - bool itemIsPrinted = false; - switch (paginate) - { - // .oooooo. .oooo. - // d8P' `Y8b d8P'`Y8b - // 888 .oooo. .oooo.o .ooooo. 888 888 - // 888 `P )88b d88( "8 d88' `88b 888 888 - // 888 .oP"888 `"Y88b. 888ooo888 888 888 - // `88b ooo d8( 888 o. )88b 888 .o `88b d88' - // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' `Y8bd8P' - case 0: // No page break - if (MyItemInfo.IsSection) - { - SectionInfo si = MyItemInfo as SectionInfo; - MyPageHelper.PageBookmarks.Add(MyItemInfo, ((si.DisplayNumber ?? "") == "" ? "" : si.DisplayNumber + " - ") + si.DisplayText, null); - DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); - } - // SupInfo has its own pagination and ylocation handling, reset ypagestart & ylocation if continuing on current page. - // The value used was saved when the previous SupInfo step was printed. - if (MyItemInfo.IsSupInfoPart) - { - yPageStart = _yPageStartForSupInfo - SixLinesPerInch; - yLocation = yPageStart - YTopMost; - } - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge) - { - // printing a procedure with section(s) that have supplemental information - determine facing page needed to be merged in. For - // case 0, it is typically at the beginning of the section since the page break occurred in the code that calls this. - // Note that if the procedure has any sections with supinfo, then the entire procedure will need facing pages, either blank page - // or supinfo steps. - // If the section title is printed, then need to get the facing page before the section title is printed and if - // this is the hls where the section title was printed, don't do the facing page. - bool titlePrinted = false; - if (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null)) - { - // see if the section title is printed. - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - titlePrinted = (sch == null || sch.Section_PrintHdr == "Y") || !(MyItemInfo.MyActiveSection as SectionInfo).HasSupInfoSteps; - titlePrinted &= (ShowSectionTitles && !MyItemInfo.MyDocStyle.CancelSectTitle); - } - // If this is first step section and there is no supinfo, the blank page was done in proms printer. - // If this is first step section and there is supinfo, it needs to be put out - bool notFirstOrFirstHasSupInfo = false; - bool firstSec = true; - foreach (SectionInfo sec in MyItemInfo.MyProcedure.Sections) - { - if (sec.IsStepSection) - { - if (MyItemInfo.ActiveSection != null && sec.ItemID == MyItemInfo.ActiveSection.ItemID) break; // C2018-003 fixed use of getting the active section - firstSec = false; - break; - } - } - notFirstOrFirstHasSupInfo = !firstSec || (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection as SectionInfo).HasSupInfoSteps); // C2018-003 fixed use of getting the active section - if (notFirstOrFirstHasSupInfo && ((MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null && !titlePrinted) || (MyItemInfo.IsStepSection && titlePrinted)) && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) - { - // If there is supplemental information to be printed on the facing page, then get the id that has supinfo - // so that it can be retrieved from the pdf for the supinfos for this section. - int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); - if (sid != -1) - { - MyPromsPrinter.DoSupInfoPage(cb, "TEMP", MyPageHelper.TextLayer, MyPageHelper, sid, true); - } - else - { - MyPromsPrinter.InsertBlankPage(cb); - } - } - } - if (MyItemInfo.IsHigh && MyItemInfo.MyPrevious != null && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) - yPageStart -= SixLinesPerInch; - if (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].CompressFirstPartOfStep) - MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - if (CompressFoldout) - MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - - ///else - /// MyPageHelper.YMultiplier = 1; - break; - // .oooooo. .o - // d8P' `Y8b o888 - //888 .oooo. .oooo.o .ooooo. 888 - //888 `P )88b d88( "8 d88' `88b 888 - //888 .oP"888 `"Y88b. 888ooo888 888 - //`88b ooo d8( 888 o. )88b 888 .o 888 - // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' o888o - case 1: // Break on High Level Step - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) - { - // page break here, determine if there is caution/note above where the page break actually needs to go: - int aboveSupinfoId = ChildrenAboveHaveSupInfo(); - if (supInfoSect!=null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0 && aboveSupinfoId > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(aboveSupinfoId); - else if (supInfoSect != null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); - else MyPromsPrinter.NeedSupInfoBreak = true; - if (supInfoSect!=null) supInfoSect.StepSectPageBreaks.Add(MyItemInfo.ItemID); - } - YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); - docstyle = MyItemInfo.MyDocStyle; - if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yLocation, yTopMargin); - bool doSectionContinue = !MyItemInfo.IsSection && ((docstyle.StructureStyle.Style & E_DocStructStyle.BottomSectionContinue) == E_DocStructStyle.BottomSectionContinue); - if (doSectionContinue) DoBottomContinueMsg(cb, yBottomMargin, yLocation, docstyle, false); - MyPromsPrinter.NewPage(); - //_MyLog.InfoFormat("NewPage 10 {0}", cb.PdfWriter.CurrentPageNumber); - if (MyItemInfo.IsSection && MyParent != null && MyParent.MyItemInfo.IsSection && (MyItemInfo as SectionInfo).IsSeparatePagination()) - { - // F2023-015 for Beaver Valley as two sub-sections that are printed continuously followed by a third sub-section printed - // with separate pagination. This section type uses a different pagelist for the pages after the first page. - // Needed to call ResetDocStyleAndValues to set the new page with the other pagelist sytle. - ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); - RefreshDocStyle(); - yTopMargin = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize) - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin; // C2018-003 fixed use of getting the active section // C2020-002 paper size is now set in the format files - yBottomMargin = Math.Max(0, yTopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); // C2018-003 fixed use of getting the active section - yPageStart = yTopMargin; - } - else if (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious != null)) //do not reset for 1st step - { - //Console.WriteLine("'b1',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); - //Console.WriteLine("'a1',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - } - DebugText.WriteLine("Paginate1"); - if (MyItemInfo.IsSection) - { - SectionInfo si = MyItemInfo as SectionInfo; - MyPageHelper.PageBookmarks.Add(MyItemInfo, ((si.DisplayNumber ?? "") == "" ? "" : si.DisplayNumber + " - ") + si.DisplayText, null); - - } - // Only do foldout page if not done for section break, i.e. check the there's a previous step. - if (MyItemInfo.MyPrevious != null && MyItemInfo.FoldoutIndex() > -1) - MyPromsPrinter.DoFoldoutPage(cb, "HLS", MyPageHelper.TextLayer, MyPageHelper, MyItemInfo.FoldoutIndex(), false); - // B2018-108 if paginating on first step don't add blank page (it was already added at this point) - // B2023-011: Beaver Valley - continuous section printing on its own page throws off CAS/blank pages - // added the IsSection check to the else if - else if (PromsPrinter.MyFoldoutReader.Count > 0 && MyPageHelper.MyPromsPrinter.InsertBlankPages && (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious != null))) - { - // insert a blank page if this step section had a foldout associated and the checkbox - // on the print dialog, to add blank pages, is checked AND the page did NOT have a - // preceeding foldout. - if (MyItemInfo.FoldoutIndex() <= -1) - { - MyPromsPrinter.InsertBlankPage(cb); - //_MyLog.InfoFormat("NewPage 10 blank {0}", cb.PdfWriter.CurrentPageNumber); - } - } - // See comments under case 0 explaining supinfo/facing page processing. - itemIsPrinted = IsPrintedStepItemForSupInfo(); - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage && itemIsPrinted /*&& !MyItemInfo.IsSection*/ && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) - { - int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); - if (sid != -1) - { - MyPromsPrinter.DoSupInfoPage(cb, "TEMP", MyPageHelper.TextLayer, MyPageHelper, sid, true); - } - else - { - MyPromsPrinter.InsertBlankPage(cb); // C2019-004: Allow user to define duplex blank page text - } - } - if (MyItemInfo.MyDocStyle.LandscapePageList) - { - System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix(0, 1, -1, 0, cb.PdfDocument.PageSize.Height, 0); - cb.Transform(myMatrix); - } - yPageStart = yTopMargin + YTopMost; - // B2020-001 Catawba had an extra line at the top of a page that paginated on a section (EP/1/A/5000/E0 section B) - // Needed to remove the extra line spacing that is before the start of section B - (section is set for continuous pagination) - if (MyItemInfo.IsSection && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing) - yPageStart += (float)MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[25].StepLayoutData.STExtraSpace; - DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); - SectionTopMessage(cb, yTopMargin, yLocation); // does wcntraining & suppinfo section title - if (MyPageHelper.CreatingSupInfoPage) yPageStart -= (2 * SixLinesPerInch); - if (doSectionContinue) DoTopContinueMsg(cb, ref yPageStart, yTopMargin, docstyle, null); - // If "ContinueSectionHeader" (format flag) is true then print the section title with "(Continued)" appended to it - // B2020-164 added check for SpecialCaseCalvert to bypass IsSeparateSubsection STP O-67B-2 step 6.5 - // B2025-060 no section continue message if previous was not in same section or sub-section - // fixes Vogtle units 3&4 3-AOP-116 Attachments 2 & 3 - if ((!MyItemInfo.IsSection || MyItemInfo.IsSubsection) && - (MyItemInfo.MyPrevious != null && MyItemInfo.ActiveSection == MyItemInfo.MyPrevious.ActiveSection) && - MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader && - (!MyItemInfo.IsSection || (MyItemInfo.IsSeparateSubsection || MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert))) - { - // B2020-162 - SpecialCaseCalvert flag affect single column procedures, use SpecialCaseCalvertPagination for Two Column procedures instead - // B2020-163 - above bug (162) section header breaking from HLS caused forced pagination. turned out we didn't need to change this for B2020-162. - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; - //B2020-123 - Calvert - set CalvertPrintedSubSectTitle flag to fix section continue bug - //B2020-166 - Calvert - only set CalvertPrintedSubSectTitle flag if doSectionTitleContinued is set - if (doSectionTitleContinued && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) CalvertPrintedSubSectTitle = true; // B2020-123 - } - - if (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].CompressFirstPartOfStep) - MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - else - MyPageHelper.YMultiplier = 1; - break; - // .oooooo. .oooo. - // d8P' `Y8b .dP""Y88b - // 888 .oooo. .oooo.o .ooooo. ]8P' - // 888 `P )88b d88( "8 d88' `88b .d8P' - // 888 .oP"888 `"Y88b. 888ooo888 .dP' - // `88b ooo d8( 888 o. )88b 888 .o .oP .o - // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' 8888888888 - case 2: // Break within a Step' - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) - { - if (supInfoSect!=null&& MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); - else MyPromsPrinter.NeedSupInfoBreak = true; - if (supInfoSect!=null) supInfoSect.StepSectPageBreaks.Add(MyItemInfo.ItemID); - } - YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); - docstyle = MyItemInfo.MyDocStyle; - bool doAlarmBox = false; - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - { - // Recognize that the break occurred WITHIN the CONDITION/RESPONSE table. - // Otherwise, we get extraneous header/top of box lines in pdf. - if (MyPageHelper.AlarmYoffStart > 0) - { - // if the first step in box is what broke to next page, then - // don't print the box on this page, only print it on next page: - doAlarmBox = true; - if (MyItemInfo.MyPrevious == null && MyParent.HasCalvertMacro) - MyPageHelper.AlarmYoffStart = 0; - else if (MyPageHelper.AlarmYoffEnd == 0) - { - // doThreeContinues flags when continue messages are printed in the - // bottom of the CONDITION/RESPONSE table columns. - doThreeContinues = MyItemInfo.StepLevel > 1; - MyPageHelper.AlarmYoffEnd = CalculateYLocation(yLocation, yTopMargin); - } - else if (MyPageHelper.AlarmYoffEnd > 0) - doAlarmBox = false; - - } - } - } - if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yLocation, yTopMargin); - // B2019-115 Locate Bottom Continue Message below AER Table if necesssary - float bcm_yLocation = TableBottom == -1 ? yLocation: Math.Min(TableBottom,yLocation); - DoBottomContinueMsg(cb, yBottomMargin, bcm_yLocation, docstyle, doThreeContinues); - MyPromsPrinter.NewPage(); - // C2018-003 fixed use of getting the active section - // F2023-112 Vogtle Units 3 & 4 background document format DSS_PageListBkgndStpContMsg to print continue message next to step number - if (MyItemInfo.IsStep && (MyItemInfo.ActiveSection != null && - ((MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) || - ((MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListBkgndStpContMsg) == E_DocStructStyle.DSS_PageListBkgndStpContMsg))) - { - // check if parent (can be HLS, Caution or Note) has the UseOldTemplate. If so, - // flag that a continue message should be printed as part of a pagelist header (if pagelist - // has CM: page list item) - ItemInfo itm = MyItemInfo; - while (itm.IsStep && !itm.FormatStepData.UseOldTemplate) itm = itm.MyParent; - // don't put out continue if the page break item is the same as background step item (caution/note or hls) - if (itm.IsStep && itm.ItemID != MyItemInfo.ItemID) - { - MyPageHelper.OldTemplateContMsg = true; - MyPageHelper.ResetSvg(); - } - } - //_MyLog.InfoFormat("NewPage 11 {0}", cb.PdfWriter.CurrentPageNumber); - //Console.WriteLine("'b2',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); - //Console.WriteLine("'a2',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - - DebugText.WriteLine("Paginate2"); - if (MyItemInfo.MyHLS.FoldoutIndex() > -1) - MyPromsPrinter.DoFoldoutPage(cb, "Break within Step", MyPageHelper.TextLayer, MyPageHelper, MyItemInfo.MyHLS.FoldoutIndex(), false); // temporary foldout - else if (PromsPrinter.MyFoldoutReader.Count > 0 && MyPageHelper.MyPromsPrinter.InsertBlankPages) - { - MyPromsPrinter.InsertBlankPage(cb); - _MyLog.InfoFormat("NewPage Break within step blank {0}", cb.PdfWriter.CurrentPageNumber); - } - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage && !MyItemInfo.IsSection && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) - { - int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); - if (sid != -1) - { - MyPromsPrinter.DoSupInfoPage(cb, "TEMP", MyPageHelper.TextLayer, MyPageHelper, sid, true); - } - else - { - MyPromsPrinter.InsertBlankPage(cb); - } - } - // if there is a 'container vlnbox' around the HLS, flag that the drawn box must also break: - if (MyHighLevelParagraph != null && MyHighLevelParagraph.PartsContainer != null && MyHighLevelParagraph.PartsContainer.Count > 0 && - !((MyHighLevelParagraph.MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) - { - foreach (vlnPrintObject vpo in MyHighLevelParagraph.PartsContainer) - { - vlnBox vb = vpo as vlnBox; - if (vb != null) - { - vb.ContainsPageBreak = true; - PartsContainer.Add(vb); - } - } - } - - // If there is a box, adjust the yTopMost to include it. - float yTopMost = YTopMost; - if ((MyItemInfo.IsCautionPart || MyItemInfo.IsNotePart) && MyParent.PartsAbove.Count > 0) - yTopMost = MyParent.PartsAbove[0].YOffset; - yTopMost = Math.Min(yTopMost, YVeryTop); - yPageStart = yTopMargin + yTopMost;// -2 * SixLinesPerInch; - DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); - if (EmptyTopMostPart) yPageStart += SixLinesPerInch; - bool addExtraLines = false; - // If "ContinueSectionHeader" (format flag) is true then print the section title with "(Continued)" appended to it - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader) - { - // if this is calvert OI/STP, then also check that docstyle has a top continue message - // in the document style that includes 'Continued' - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - { - string myMsg = MyItemInfo.MyDocStyle.Continue.Top.Message; - if (myMsg == null || myMsg == "") - { - // There is no message, but still need to check if there is a Section Title Continued message: - // This was added for BGE OI34 (if break was within step, no section title continue message was printed) - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader) - { - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; - } - else - doSectionTitleContinued = false; - } - else - { - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; - } - } - else - { - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; - } - } - addExtraLines = SectionTopMessage(cb, yTopMargin, yLocation); // this does wcntraining top section continue message and supplemental info message - if (MyPageHelper.CreatingSupInfoPage) yPageStart -= (2 * SixLinesPerInch); - if (!addExtraLines && (!doSectionTitleContinued || !SectionShowTitles)) - addExtraLines = DoTopContinueMsg(cb, ref yPageStart, yTopMargin, docstyle, doThreeContinues && MyItemInfo.MyParent != null && MyItemInfo.MyParent.MyTab != null ? MyItemInfo.MyParent.MyTab.CleanText : null); - // B2020-128: If compression flag is on RNO, see if there is an AER to the left and do the 7lpi multiplier - if (CompressPartOfStep || CompressRnoWithAerToTheLeft()) - { - MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - CompressPartOfStep = false; - } - else - MyPageHelper.YMultiplier = 1; - - // For Calvert Alarms, if there was a page break and there is an box around the current - // step, need to add the header for the box, which is stored in a macro. Also set the - // 'AlarmYoffStart' value to where the vertical lines of the box start on this page. - if (doAlarmBox && MyItemInfo.StepLevel > 1) - { - float alrmY = yTopMargin - (2 * SixLinesPerInch); // CalculateYOffset(yPageStart, yTopMargin); - vlnMacro vlnm = new vlnMacro((float)docstyle.Layout.LeftMargin - 12, alrmY, "H4"); - vlnm.UseInternalY = true; // B2020-121: Account for Header on Caution or Note - PartsLeft.Add(vlnm); - MyPageHelper.AlarmYoffStart = alrmY - SixLinesPerInch; - yPageStart -= (4 * SixLinesPerInch); - if(ChildrenRight.Count>0 && ChildrenRight[0].ChildrenAbove.Count > 0 && ChildrenRight[0].ChildrenAbove[0].MyItemInfo.IsCautionOrNotePart) - yPageStart += (SixLinesPerInch); // B2020-121: Account for Header on Caution or Note - } - // For Calvert Alarms, if there is no box & this is top of page, if previous step - // had box (macro), adjust up page. The constructor (vlnParagraph), inserted these - // lines after the box so that the following text did not print right next to box. - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - if (MyItemInfo.MyPrevious != null && MyItemInfo.MyPrevious.TemplateIndex > 0 && MyItemInfo.ActiveFormat.PlantFormat.FormatData.Templates[MyItemInfo.MyPrevious.TemplateIndex].hmacro > 0) - yPageStart += (3 * SixLinesPerInch); - } - // Now check if this is a template type step & if so, add the HLS's prefix/suffix to it. - // Since the entire checklist HLS (checklist table header) is printed as part of the - // continue, create a new paragraph to handle pagination and printing. - if (MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.FormatStepData.UseSmartTemplate) - { - DoSubs = false; - vlnParagraph smartPara = new vlnParagraph(MyParent.MyParent, cb, MyItemInfo.MyHLS, MyParent.XOffset, yPageStart, 0, 0, MyParent.MyItemInfo.ActiveFormat, null, " (Continued)", 0, false, MyPromsPrinter); - smartPara.PrintHeader = true; - float mytmpfloat = smartPara.ParagraphToPdf(cb, yPageStart, yTopMargin, yBottomMargin); - yPageStart -= smartPara.Height; - DoSubs = true; - } - if (addExtraLines) yPageStart -= (2 * SixLinesPerInch); - if (MyItemInfo.IsRNOPart && MyItemInfo.FormatStepData.DoubleSpace && MyItemInfo.FormatStepData.SpaceDouble) yPageStart += SixLinesPerInch; - break; - // .oooooo. .oooo. - // d8P' `Y8b .dP""Y88b - // 888 .oooo. .oooo.o .ooooo. ]8P' - // 888 `P )88b d88( "8 d88' `88b <88b. - // 888 .oP"888 `"Y88b. 888ooo888 `88b. - // `88b ooo d8( 888 o. )88b 888 .o o. .88P - // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' `8bd88P' - case 3: // Break on High Level Step (SevenLinesPerInch) - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) - { - if (supInfoSect!=null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); - else MyPromsPrinter.NeedSupInfoBreak = true; - if(supInfoSect!=null) supInfoSect.StepSectPageBreaks.Add(MyItemInfo.ItemID); - } - if (!firstHighLevelStep || (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage)) // B2017-229: Added supinfo print check to run facing page logic - { - YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); - if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yLocation, yTopMargin); - MyPromsPrinter.NewPage(); // HLS (7 lpi) breakif (MyItemInfo.IsSection) - //_MyLog.InfoFormat("NewPage 12 {0}", cb.PdfWriter.CurrentPageNumber); - //Console.WriteLine("'b3',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); - //Console.WriteLine("'a3',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - DebugText.WriteLine("Paginate3"); - if (MyItemInfo.IsSection) - { - SectionInfo si = MyItemInfo as SectionInfo; - MyPageHelper.PageBookmarks.Add(MyItemInfo, ((si.DisplayNumber ?? "") == "" ? "" : si.DisplayNumber + " - ") + si.DisplayText, null); - } - if (MyItemInfo.FoldoutIndex() > -1) - MyPromsPrinter.DoFoldoutPage(cb, "HLS (7 lpi) break", MyPageHelper.TextLayer, MyPageHelper, MyItemInfo.FoldoutIndex(), false); - else if (PromsPrinter.MyFoldoutReader.Count > 0 && MyPageHelper.MyPromsPrinter.InsertBlankPages) - { - // insert a blank page if this step section had a foldout associated and the checkbox - // on the print dialog, to add blank pages, is checked - MyPromsPrinter.InsertBlankPage(cb); - //_MyLog.InfoFormat("NewPage 12 lpi blank {0}", cb.PdfWriter.CurrentPageNumber); - } - // See comments under case 0 explaining supinfo/facing page processing. - itemIsPrinted = IsPrintedStepItemForSupInfo(); - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage && itemIsPrinted /*&& !MyItemInfo.IsSection */ && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) - { - int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); - if (sid != -1) - { - MyPromsPrinter.DoSupInfoPage(cb, "TEMP", MyPageHelper.TextLayer, MyPageHelper, sid, true); - } - else - { - // B2020-031: Don't put out an extra blank page if section has title that is printed (blank page is output then) - bool titlePrinted = false; - if (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null)) - { - // see if the section title is printed. - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - titlePrinted = (sch == null || sch.Section_PrintHdr == "Y") || !(MyItemInfo.MyActiveSection as SectionInfo).HasSupInfoSteps; - titlePrinted &= (ShowSectionTitles && !MyItemInfo.MyDocStyle.CancelSectTitle); - } - if (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null && !titlePrinted) - MyPromsPrinter.InsertBlankPage(cb); - } - } - if (MyItemInfo.MyDocStyle.LandscapePageList) - { - System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix(0, 1, -1, 0, cb.PdfDocument.PageSize.Height, 0); - cb.Transform(myMatrix); - } - - // If "ContinueSectionHeader" (format flag) is true then print the section title with "(Continued)" appended to it - if (!MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader) - { - SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; - doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; - } - } - // if printing the section title, we already have the y location (note that only do this for the - // first step in the section. - if (MyItemInfo.MyPrevious == null && MyItemInfo.MyParent != null && MyItemInfo.MyParent.IsStepSection && - ShowSectionTitles - && !MyItemInfo.MyDocStyle.CancelSectTitle - && !MyItemInfo.MyDocStyle.SpecialStepsFoldout) - yPageStart = yPageStart; - else - yPageStart = yTopMargin + YTopMost; - MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); - break; - } - // If "doSectionTitleContinued" is true then print the section title with "(Continued)" appended to it - // format must have ContinueSectinHeader format flag set to true - //B2025-048 Problem with Printing CAS Steps - // skip this if printing CAS or CTAS - was causing it to - // skip/overwrite data - if (doSectionTitleContinued) - { - vlnParagraph sectContPara; - string contMsg = (MyItemInfo.ActiveSection != null) ? MyItemInfo.ActiveSection.MyDocStyle.Continue.SectionTitle.AppendToTitle : ""; // C2018-003 fixed use of getting the active section - // For Calvert, the xoffset will be the highest level sections xoffset (there are metasections, - // don't use their xoffset or the continue message is indented too much) - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - { - float secContinueTabXoff = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin; - float secContinueXoff = 0f; - float secContinueTabWidth = 0f; - vlnParagraph fndTopSect = this; - while (fndTopSect.MyParent != null) - { - fndTopSect = fndTopSect.MyParent; - } - if (fndTopSect != null && fndTopSect.MyTab != null) - { - secContinueTabXoff = fndTopSect.MyTab.XOffset; - secContinueTabWidth = fndTopSect.MyTab.Width; - secContinueXoff = fndTopSect.XOffset; - } - // get to the correct section for the message, i.e. if on a section, the message should be the parent - // section (not the activesection which is myself); if on a step, the message should be the active section - ItemInfo sectForCont = MyItemInfo.IsSection && MyItemInfo.MyParent.IsSection ? MyItemInfo.MyParent : MyItemInfo.ActiveSection; - //B2025-054 Wrong Page Numbers in CAS Summary - // when section title continued and CAS - //to avoid overwriting data - // - this will be built at a different call to vlnParagraph - if (MyPromsPrinter.PromsPrinterPrintType != PromsPrinterPrintType.Normal) - MyPromsPrinter.ShouldPrint_CAS_CTAS = false; - sectContPara = new vlnParagraph(MyParent.MyParent, cb, sectForCont, MyParent.XOffset, 0, 0, 0, MyParent.MyItemInfo.ActiveFormat, null, (contMsg == null || contMsg == "") ? " (Continued)" : contMsg, 0, false, MyPromsPrinter); - if (sectContPara.PartsLeft.Count > 0) - { - vlnTab vt = sectContPara.MyTab; - string ctab = GetSectCombinedTab(MyItemInfo); - vt.Rtf = GetRtf(ctab, vt.MyFont); - float wd = vt.GetTextWidth(vt.MyFont, ctab); - vt.XOffset = secContinueTabXoff; - vt.Width = secContinueXoff - secContinueTabXoff; - sectContPara.XOffset = secContinueXoff; - if ((wd + 12) > secContinueXoff - secContinueTabXoff) // 12 is 2 characters - { - float dif = wd + 12 - (secContinueXoff - secContinueTabXoff); - vt.Width += dif; - sectContPara.XOffset += dif; - sectContPara.Width -= dif; - } - - } - float mytmpfloat = sectContPara.ParagraphToPdf(cb, yTopMargin, yTopMargin, yBottomMargin); - if (sectContPara.SectionContinuePrinted) - yPageStart -= sectContPara.Height + SixLinesPerInch; - } - else - { - //B2025-054 Wrong Step Numbers - // when section title continued and CAS - //to avoid overwriting data - // - this will be built at a different call to vlnParagraph - if (MyPromsPrinter.PromsPrinterPrintType != PromsPrinterPrintType.Normal) - MyPromsPrinter.ShouldPrint_CAS_CTAS = false; - sectContPara = new vlnParagraph(MyParent.MyParent, cb, MyItemInfo.ActiveSection, MyParent.XOffset, 0, 0, 0, MyParent.MyItemInfo.ActiveFormat, null, (contMsg == null || contMsg == "") ? " (Continued)" : contMsg, 0, false, MyPromsPrinter); - float mytmpfloat = sectContPara.ParagraphToPdf(cb, yTopMargin, yTopMargin, yBottomMargin); - if (sectContPara.SectionContinuePrinted) - yPageStart -= sectContPara.Height + SixLinesPerInch; - } - } - //out of section title section - reset this back to true (default) - MyPromsPrinter.ShouldPrint_CAS_CTAS = true; - - // see if this hls has footnotes, add to the footnote datastructure for processing at end of page. - if (MyItemInfo.IsHigh && MyPageHelper.NotesToFootNotesHLS.ContainsKey(MyItemInfo.ItemID)) AddFootNote(cb); - - yPageStart = ChildrenAbove.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - // B2017-122: if doing supinfo pagebreaks, if there should be a break on a step (not hls) that has a caution/note do it here: - if (!MyItemInfo.IsHigh && ChildrenAbove != null && ChildrenAbove.Count > 0 && MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks && MyPromsPrinter.NeedSupInfoBreak && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) - { - // if this has a caution/note with supinfo, that is id that needs to go in pagination list, unless it is in there. - int aboveSupinfoId = ChildrenAboveHaveSupInfo(); - if (supInfoSect != null) - { - if (supInfoSect.StepSectPageBreaksForSupInfo.Contains(aboveSupinfoId)) aboveSupinfoId = -1; - supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); - } - MyPromsPrinter.NeedSupInfoBreak = false; - } - yPageStart = ChildrenLeft.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - - // Handle the PageBreakOnStep flag for a HLS. This will put out the page break right before - // a HLS. One example of this use is for backgrounds (CALBCK). - // 'this' below is a highlevel step, and the only time that ParaBreaks[0] will == 'this' is - // when the PageBreakOnStep flag is true. - if (MyPageHelper.ParaBreaks != null && MyPageHelper.ParaBreaks.Count > 0 && - MyPageHelper.ParaBreaks[0] == this && this.MyItemInfo.FormatStepData.PageBreakOnStep)// B2017-224 Top Continue Messages Add check for PageBreakOnStep 9/26/2017 Ginna SAMGs SAG-8 Step 4 - { - ShowPageBreak(1, CheckForCompression("PageBreakOnStep/Caution/Note HLS"), "Yes", YTop - YBottomMost, yTopMargin - yBottomMargin, yTopMargin - yBottomMargin, false); - YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); - MyPageHelper.BottomMessage.Clear(); - MyPageHelper.TopMessage = null; - MyPromsPrinter.NewPage(); - if (CompressPartOfStep) - { - MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - CompressPartOfStep = false; - } - MyPageHelper.ParaBreaks.RemoveAt(0); - yPageStart = yTopMargin + YTop; - } - // The following sets the beginning/ending y location for the lines around the - // CONDITION/RESPONSE text for Calvert Alarm format - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - int tindx = MyItemInfo.TemplateIndex; - if (tindx >= 0) - { - // save this position to start drawing the alarm box lines around substeps: - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.Templates[MyItemInfo.TemplateIndex].row > 0) - MyPageHelper.AlarmYoffStart = CalculateYOffset(yPageStart, yTopMargin) - SixLinesPerInch; - else if (MyPageHelper.AlarmYoffStart > 0 && MyPageHelper.AlarmYoffEnd == 0) - MyPageHelper.AlarmYoffEnd = CalculateYOffset(yPageStart, yTopMargin) + (2 * SixLinesPerInch); - } - } - int profileDepth2 = ProfileTimer.Push(">>>> vlnParagraph.ParagraphToPdf"); - // B2020-162 - SpecialCaseCalvert flag affect single column procedures, use SpecialCaseCalvertPagination for Two Column procedures instead - if (MyItemInfo.IsSubsection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination) CalvertPrintedSubSectTitle = true; // B2020-123 - yPageStart = ParagraphToPdf(cb, yPageStart, yTopMargin, yBottomMargin); - ProfileTimer.Pop(profileDepth2); - // If the yPageStart changes by more than a small amount (pagination) in the RNO (right column), then update - // yPageStart for the AER (left column). - float yPageStartRNO = ChildrenRight.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - if (yPageStartRNO - yPageStart > 24) // 24 is two lines - yPageStart = yPageStartRNO; - yPageStart = ChildrenBelow.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - - if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null) // last hls, add the 'end' message, if there is one - { - docstyle = MyItemInfo.MyDocStyle; - // if the EndForSingle format flag is set to false, then we do not print an End message if the section - // is a single column section. - //bool _skipEndMessage = MyPageHelper.MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; - SectionInfo si = MyItemInfo.ActiveSection as SectionInfo; // C2018-003 fixed use of getting the active section - // B2017-201 if si is null we need to get it via the ItemID - if (si == null) - si = SectionInfo.Get(MyItemInfo.MyActiveSection.ItemID); // MyActiveSection does not try to resolve anything - ActiveSection is call above and will resolve and set MyActiveSection - bool _skipEndMessage = (si == null ||si.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One) && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; - bool _lastSect = true; - if (si != null && si.MyActiveParent.IsSection) // is this meta/subsection. Only put end message out on last section - { - ItemInfo mysect = si as ItemInfo; - if (mysect.NextItem != null && !docstyle.End.EndMessageOnEachSubSection) _lastSect = false; - } - string myMsg = (docstyle.End == null) ? null : docstyle.End.FixedMessage; - if (myMsg != null && !_skipEndMessage && _lastSect) - { - // If the flag is 0 or 1, just put the end message out right below this vlnParagraph: - float msg_yLocation = CalculateYLocation(yPageStart - YBottomMost, yTopMargin); - //if (MyPageHelper.YMultiplier < 1) - // msg_yLocation += 4;// Robinson - if the page is compressed, we need this adjustment. - - // the following is for IP3 - it was commented out so that an update could be put on - // before this was tested. - // if end message has {par}, remove these but add a line for each. - //int parindx = myMsg.IndexOf("{par}"); - //bool foundpar = false; - //while (parindx > -1) - //{ - // foundpar = true; - // msg_yLocation += SixLinesPerInch; - // parindx = myMsg.IndexOf("{par}", parindx + 1); - //} - //if (foundpar) myMsg = myMsg.Replace("{par}", ""); - // use the 'flag' to position the message. - if (docstyle.End.Flag > 2) // >2 position at an absolute location defined by docstyle.End.Flag. - { - msg_yLocation = yTopMargin - (float)(docstyle.End.Flag * SixLinesPerInch); - } - float adjMsgY = 0; - if (docstyle.End.Flag < 0) // Adjust this many lines down the page. - { - adjMsgY = (float)(-docstyle.End.Flag * SixLinesPerInch); - if (msg_yLocation - adjMsgY > docstyle.Layout.FooterLength) msg_yLocation = msg_yLocation - adjMsgY; - } - if (myMsg.Contains("{Section Number}")) myMsg = myMsg.Replace("{Section Number}", MyItemInfo.ActiveSection.DisplayNumber); - //jcb code - //if (myMsg.Contains("%-8s")) - // myMsg = myMsg.Replace("%-8s", MyItemInfo.MyProcedure.DisplayNumber.PadRight(8)); - if (myMsg.Contains("%-12s")) - myMsg = myMsg.Replace("%-12s", MyItemInfo.MyProcedure.DisplayNumber.PadRight(12)); - float xpos = 0; - if (yTopMargin - docstyle.Layout.PageLength >= msg_yLocation && docstyle.End.Message != null && docstyle.End.Message != "" && docstyle.End.Flag <= 2) - { - // B2018-037: adjust location of end message to bottom of page if it is too low. This occurs when data just doesn't - // fit on the page, but will locate end message at a more reasonable location. - msg_yLocation = (float)yTopMargin - (float)docstyle.Layout.PageLength; - _MyLog.WarnFormat("End Message LOW on page: {0}, {1}, {2}, Page {3}", msg_yLocation, MyItemInfo.ItemID, MyItemInfo.ShortPath, MyPageHelper.CurrentPageNumber + 1); - } - if ((docstyle.End.Margin ?? 0) != 0) - { - xpos = (float)docstyle.Layout.LeftMargin + (float)docstyle.End.Margin; - MyPageHelper.BottomMessage.Add(new vlnText(cb, this, myMsg, myMsg, xpos, msg_yLocation, docstyle.End.Font)); - } - else - { // Center the bottom message - float wtpm = (float)docstyle.Layout.PageWidth - (float)docstyle.Layout.LeftMargin; - //B2022-126 was using the wrong font definition to calaculate the centering position - // ** B2023-099 commented out and restored the previous calculation. This caused problems centering the END message in Ginna - // their END message prints with the Prestige Elite font but he centering calc uses Courier New - //xpos = XOffsetBox + (float)docstyle.Layout.LeftMargin + (wtpm - (myMsg.Length * docstyle.End.Font.CharsToTwips)) / 2; - xpos = XOffsetBox + (float)docstyle.Layout.LeftMargin + (wtpm - (myMsg.Length * MyItemInfo.FormatStepData.Font.CharsToTwips)) / 2; - xpos = Math.Max(xpos, XOffsetBox + (float)docstyle.Layout.LeftMargin); - vlnText vttmp = new vlnText(cb, this, myMsg, myMsg, xpos, msg_yLocation, docstyle.End.Font); - MyPageHelper.BottomMessage.Add(vttmp); - MyPageHelper.MyGaps.Add(new Gap(msg_yLocation, msg_yLocation - vttmp.Height)); - yPageStart -= (vttmp.Height + adjMsgY); - } - } - } - if (yLocalypagestart != yPageStart) DebugText.WriteLine("ToPdf-yPagestartDiff:{0},{1},{2},{3}", MyPageHelper.MyPdfContentByte.PdfWriter.CurrentPageNumber, MyItemInfo.ItemID, yLocalypagestart, yPageStart); - - // if doing NotesToFootnotes (Calvert valve list format), get the bottom location so that - // footnotes will be printed after last text on page. This is used for the end of the section. - // Pages that broke within pagination logic above had footnote location set during pagination code. - if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) - MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yPageStart - YBottomMost, yTopMargin); - ProfileTimer.Pop(profileDepth); - return yPageStart; - } - // B2020-128: If compression flag is on RNO, see if there is an AER to the left and do the 7lpi multiplier - private bool CompressRnoWithAerToTheLeft() - { - if (!MyItemInfo.IsInRNO) return false; - foreach (vlnParagraph vPara in MyPageHelper.MyParagraphs.Values) - { - if (!vPara.Processed) - { - if (vPara.YOffset <= YOffset && vPara.CompressPartOfStep) return true; - } - } - return false; - } - private bool IsPrintedStepItemForSupInfo() - { - bool printedMySectTitle = true; - if (MyItemInfo.IsSection) - { - // see if the section title is printed. - SectionConfig sch = (MyItemInfo.ActiveSection != null) ? MyItemInfo.ActiveSection.MyConfig as SectionConfig : null; // C2018-003 fixed use of getting the active section - printedMySectTitle = (sch == null || sch.Section_PrintHdr == "Y") || !(MyItemInfo.ActiveSection as SectionInfo).HasSupInfoSteps; - printedMySectTitle &= (ShowSectionTitles && !MyItemInfo.MyDocStyle.CancelSectTitle); - } - return printedMySectTitle; - } - private int ChildrenAboveHaveSupInfo() - { - if (ChildrenAbove == null || ChildrenAbove.Count < 1) return -1; - foreach (vlnParagraph p in ChildrenAbove) - { - if (p.MyItemInfo.SupInfos != null && p.MyItemInfo.SupInfos.Count > 0) return p.MyItemInfo.SupInfos[0].ItemID; - } - return -1; - } - // Find the step that has supplemental information from this step down page until a preferred page break is found - // or a regular page break. - // It is used to determine whether there is a supinfo facing page or if there should be a blank page. - private bool FoundStepPageBreak = false; - private int GetIdThatHasSupInfoItems(ItemInfo ii, int startid) - { - if (ii == null) return -1; - FoundStepPageBreak = false; - // if this item has supinfo, return its id - if (ii.SupInfos != null && ii.SupInfos.Count > 0) return ii.SupInfos[0].ItemID; - - // see if any substeps of this item have supinfo, and if so, return the substep's id - int id = GetSubThatHasSupInfoItems(ii, startid); - if (id != -1) return id; - if (FoundStepPageBreak) return -1; // Set in GetSubThatHasSupInfoItems - - // Now go to the next item, check if it or any of its substeps have supinfo, and if so, return the id - ItemInfo sib = ii.NextItem; - id = GetIdThatHasSupInfoItemsSibNext(sib, startid); - if (id != -1) return id; - if (FoundStepPageBreak) return -1; // Set in GetIdThatHasSupInfoItemsSibNext - - // B2017-122: if this is a note or caution off substep, check if substep has supinfo: - if ((ii.IsNote || ii.IsCaution) && !ii.MyParent.IsHigh) - { - if (ii.MyParent.SupInfos != null && ii.MyParent.SupInfos.Count > 0) return ii.MyParent.SupInfos[0].ItemID; - int sbfromNC = GetSubThatHasSupInfoItems(ii.MyParent, startid); - if (sbfromNC != -1) return sbfromNC; - if (FoundStepPageBreak) return -1; // Set in GetSubThatHasSupInfoItems - } - - // Go to the parent, and find its next and check if it or any of its substeps or next steps or any of their substeps have supinfo, - // and if so, return the id. - ItemInfo par = ii.MyParent; - ItemInfo parsnxt = par.GetNext(); - //B2023-068 check if we are already at the section or procedure level - if (!par.IsSection && !par.IsProcedure && parsnxt != null) - { - par = parsnxt; - while (par != null && !par.IsSection) - { - id = GetIdThatHasSupInfoItemsSibNext(par, startid); - if (id != -1) return id; - par = par.MyParent; - ItemInfo sparsnxt = par.GetNext(); - if (!par.IsSection && sparsnxt != null) par = sparsnxt; - else return -1; - } - } - return -1; - } - - private int GetIdThatHasSupInfoItemsSibNext(ItemInfo ii, int startid) - { - int id = -1; - while (ii != null) - { - SectionInfo supInfoSect = ii.ActiveSection as SectionInfo; - // B2017-193 Error occured when a section in the MRU was being loaded as an iteminfo - if (supInfoSect == null) supInfoSect = SectionInfo.Get(ii.ActiveSection.ItemID); - // if there is a pagebreak on this step section step, quit looking for supinfos. The - // break has to occur here. - if (supInfoSect.StepSectPageBreaks.Contains(ii.ItemID)) - { - FoundStepPageBreak = true; - return -1; - } - if (ii.SupInfos != null && ii.SupInfos.Count > 0) - { - // check if this is in the list of page breaks for supinfos, if not it may have one of its cautions/notes rather than its id: - if (!supInfoSect.StepSectPageBreaksForSupInfo.Contains(ii.SupInfos[0].ItemID)) - { - if (ii.Cautions != null) - { - foreach (ItemInfo caution in ii.Cautions) - if (caution.SupInfos != null && caution.SupInfos.Count > 0 && supInfoSect.StepSectPageBreaksForSupInfo.Contains(caution.SupInfos[0].ItemID)) return caution.SupInfos[0].ItemID; - } - if (ii.Notes != null) - { - foreach (ItemInfo note in ii.Notes) - if (note.SupInfos != null && note.SupInfos.Count > 0 && supInfoSect.StepSectPageBreaksForSupInfo.Contains(note.SupInfos[0].ItemID)) return note.SupInfos[0].ItemID; - } - } - return ii.SupInfos[0].ItemID; - } - id = GetSubThatHasSupInfoItems(ii, startid); - if (id == -2) return -1; - if (id != -1) return id; - ii = ii.NextItem; - } - return -1; - } - private int GetSubThatHasSupInfoItems(ItemInfo ii, int startid) - { - if (ii.MyContent.ContentParts != null) - { - SectionInfo supInfoSect = ii.ActiveSection as SectionInfo; - if (supInfoSect == null) supInfoSect = SectionInfo.Get(ii.ActiveSection.ItemID); - foreach (PartInfo pi in ii.MyContent.ContentParts) - { - if ((E_FromType)pi.FromType != E_FromType.SupInfo) - { - foreach (ItemInfo iic in pi.MyItems) - { - // B2018-021: added code to be sure that check isn't on current step, i.e. startid != iic.ItemID & - // flag when the following page break is found so the next supplemental information page isn't printed - // on a step where the step is on the following page from the one we are looking for. - if (startid != iic.ItemID) - { - if (supInfoSect.StepSectPageBreaks.Contains(iic.ItemID)) - { - FoundStepPageBreak = true; - return -1; - } - if (iic.SupInfos != null && iic.SupInfos.Count > 0) return iic.SupInfos[0].ItemID; - int id = GetSubThatHasSupInfoItems(iic, startid); - if (id != -1) return id; - } - } - } - } - } - return -1; - } - private float GetSectionTopMessageSize() - { - // B2016-134: Account for wcntraining section top continue if item has container - float retval = 0; - if (MyItemInfo.MyDocStyle.SectTop != null && MyItemInfo.MyDocStyle.SectTop.Message != null) - { - if (PartsContainer != null && PartsContainer.Count > 0) retval = SixLinesPerInch * 1; - } - return retval; - } - // For WCNTRN (Wolf Creek Training format): the following prints the section number (and continued, if - // section is continued from previous page) in the Responsibility column. - private bool SectionTopMessage(PdfContentByte cb, float yTopMargin, float yLocation) - { - if (MyPageHelper.CreatingSupInfoPage) - { - float scttopWidths = "Supplemental Information".Length * 6; - float ctrs = ((float)MyItemInfo.MyDocStyle.Layout.PageWidth - (float)MyItemInfo.MyDocStyle.Layout.LeftMargin) / 2; - float sctcntrXs = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ctrs - (scttopWidths / 2); - VE_Font vf = MyItemInfo.MyDocStyle.Font; - // F2017-039: The following null check was added in case the format's doc style does not have a font defined: - if (vf == null || vf.Style == null || vf.Family == null || vf.Size == null || vf.CPI == null) vf = MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font; - E_Style sty = E_Style.Underline; - if (vf != null && vf.Style != null) sty = (E_Style)(vf.Style | E_Style.Underline); - vf = new VE_Font(vf.Family, (int)vf.Size, sty, (float)vf.CPI); - MyPageHelper.TopMessage = new vlnText(cb, this, "Supplemental Information", "Supplemental Information", sctcntrXs, yTopMargin + 0.1F, vf); - return true; - } - bool addextra = false; - if (MyItemInfo.MyDocStyle.SectTop != null && MyItemInfo.MyDocStyle.SectTop.Message != null) - { - float sectMsgY = 0; - if (PartsContainer == null || PartsContainer.Count == 0) - sectMsgY = CalculateYLocation(YTop, yTopMargin); - else - { - // B2016-134: Account for section top continue if item has container, i.e. move section top continue message above the container - sectMsgY = CalculateYLocation(YTopMost - (SixLinesPerInch * 3), yTopMargin); // 3 is # of lines: header, box, blank line moving up page - addextra = true; - } - VE_Font sctMsgFont = MyItemInfo.MyDocStyle.SectTop.Font; - string scttop = null; - if (!MyItemInfo.IsStepSection && MyItemInfo.MyDocStyle.SectTop.Message != null) - scttop = MyItemInfo.MyDocStyle.SectTop.Message.Replace("%s", (MyItemInfo.ActiveSection as SectionInfo).DisplayNumber); - else - scttop = (MyItemInfo as SectionInfo).DisplayNumber; - float scttopWidth = scttop.Length * 6; - float ctr = (float)MyItemInfo.MyDocStyle.SectTop.Margin; - float sctcntrX = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ctr - (scttopWidth / 2); - vlnText mySectMsg = new vlnText(cb, this, scttop, scttop, sctcntrX, sectMsgY, sctMsgFont); - PartsLeft.Add(mySectMsg); - } - return addextra; - } - // Added to try to resolve a problem when printing FNP-1-FRP-I.3 Attachment 3 Table 1. - // May be needed to evaluate this problem in the future. - //private void CompareSectionInfo(SectionInfo si, SectionInfo si1) - //{ - // if (si.ItemID != si1.ItemID) - // Console.WriteLine("Different"); - // if (si.ActiveFormat.FullName != si1.ActiveFormat.FullName) - // Console.WriteLine("Different"); - // if (si.ActiveParent != si1.ActiveParent) - // Console.WriteLine("Different"); - // if (si.ActiveSection.ItemID != si1.ActiveSection.ItemID) - // Console.WriteLine("Different"); - // if (si.MyDocStyle.Name != si1.MyDocStyle.Name) - // Console.WriteLine("Different"); - //} - private void AddFootNote(PdfContentByte cb) - { - // for calvert valve lists footnotes, if there is footnote data, save it for vlnSvgPageHelper - // which puts the footnotes out when page is printed. - List myNotes = MyPageHelper.NotesToFootNotesHLS[MyItemInfo.ItemID]; - foreach (int myNote in myNotes) - { - ItemInfo inote = StepInfo.Get(myNote); - - // first check if this exact text is already in the foot note list. If it is - // in there, don't add it. - bool inlist = false; - if (MyPageHelper.NotesToFootNotes != null) - { - foreach (vlnParagraph vp in MyPageHelper.NotesToFootNotes) - { - if (vp.MyItemInfo.MyContent.Text == inote.MyContent.Text) - { - inlist = true; - break; - } - } - } - if (!inlist) - { - vlnParagraph vpFNote = new vlnParagraph(null, cb, inote, (float)MyItemInfo.MyDocStyle.Layout.LeftMargin, 0, 0, 0, MyItemInfo.ActiveFormat, null, null, 0, false, MyPromsPrinter); - vpFNote.Width = (float)MyItemInfo.MyDocStyle.Layout.PageWidth - (float)MyItemInfo.MyDocStyle.Layout.LeftMargin; - vpFNote.Height = 0; - vpFNote.XOffset = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin; - if (MyPageHelper.NotesToFootNotes == null) MyPageHelper.NotesToFootNotes = new List(); - MyPageHelper.NotesToFootNotes.Add(vpFNote); - } - } - MyPageHelper.NotesToFootNotesHLS.Remove(MyItemInfo.ItemID); - } - private bool DoTopContinueMsg(PdfContentByte cb, ref float yPageStart, float yTopMargin, DocStyle docstyle, string subTab) - { - bool addExtraLine = false; - if ((bool)docstyle.Continue.Top.UseStepTabs) - { - // UseStepTabs is a format flag added for Comanche Peak to print out step tabs as - // a top comtinue message. This code will go up through parents putting out - // their tabs - at this y location, but at the tabs' x location - vlnParagraph myPar = this; - MyPageHelper.TopMessageRs = new List(); - while (!myPar.MyItemInfo.IsHigh) - { - myPar = myPar.MyParent; - foreach (vlnPrintObject vpo in myPar.PartsLeft) - { - if (vpo is vlnTab) - { - vlnTab vt = vpo as vlnTab; - string cltxt = vt.Text; - // Originally the Comache Peak customer did not want the '*'. As of 6/22/15, CP wants the asterisk in continue msg - ///cltxt = cltxt.Replace("*", " "); - // replace C# representation of unicode character "\u25CF" which is hex - // with the rtf representation @"\u9679?" - if (cltxt.Contains("\u25CF")) cltxt = cltxt.Replace("\u25CF", @"\u9679?"); // handle a bullet, if it isn't unicode yet - float msgTopMargin = yTopMargin; - // B2017-106: if caution/note move the message up a little so it doesn't touch the caution/note lines: - if (MyItemInfo.IsNote || MyItemInfo.IsCaution) msgTopMargin += 4; - // B2018-140: if table move the message up a little so it doesn't touch the table lines: - if (MyItemInfo.IsTable) msgTopMargin += 6; - MyPageHelper.TopMessageRs.Add(new vlnText(cb, this, cltxt, cltxt, vt.XOffset, msgTopMargin, vt.MyFont)); - } - else if (vpo is vlnText) // As of 6/22/15, CP wants the step designator in the continue message also. - { - vpo.YOffset = yTopMargin; - int nlcnt = 1; // number of lines to adjust the yoffset for the next step designator we are adding to TopMessageRs - string rtxt = ""; - int istr = 0; - int Rsidx = 0; - MyPageHelper.TopMessageRs.Add(vpo as vlnText); // this appends a previous step designator associated with this sub-step (there may be more than one and/or might have multiple lines) - // we are processing the step designator on the top continue message in reverse order - // we therefore need to adjust the y location of multiple step designors attached tothe top continue message - if (MyPageHelper.TopMessageRs.Count > 3) - { - Rsidx = MyPageHelper.TopMessageRs.Count - 1; - rtxt = MyPageHelper.TopMessageRs[Rsidx].Text; - // find the number of lines to shift existing TopMessageRs step designators down - istr = rtxt.IndexOf("\\line", 0); - while (istr != -1) - { - nlcnt++; - istr = rtxt.IndexOf("\\line", istr + 1); - } - // move the previous TopMessageRs step designators down - Rsidx -= 2; // index to the previous step desginator - while (Rsidx > 0) - { - MyPageHelper.TopMessageRs[Rsidx].YOffset -= (nlcnt * SixLinesPerInch); - Rsidx -= 2;// every other TopMessageRs is a step designator - } - } - // for Comanche Peak - if step breaks on a sub-step, and both the high level step and the sub-step have a step designator - // then since the high level step and its step designator are printed as part of the top continue message, - // move the step designator associated with the sub-step down so that it does not print on top of the - // ones in the top continue message. - if (this.PartsLeft.Count > 1) // was a step designator printed for the sub-step? - { - // count the number of lines in the step designator text in the top continue message - nlcnt = 0; // reset for the number of lines to push the sub-step's step designator down - Rsidx = MyPageHelper.TopMessageRs.Count - 1; // note that TopMessageRs[0] is a tab not a step designator - while (Rsidx > 0) - { - nlcnt++; - rtxt = MyPageHelper.TopMessageRs[Rsidx].Text; - istr = rtxt.IndexOf("\\line", 0); - while (istr != -1) - { - nlcnt++; - istr = rtxt.IndexOf("\\line", istr + 1); - } - Rsidx -= 2; // every other TopMessageRs is a step designator - } - if (nlcnt > 0) - { - for (int idx = 1; idx < this.PartsLeft.Count; idx++) - { - vlnPrintObject vpol = this.PartsLeft[idx]; - vpol.YOffset += (nlcnt * SixLinesPerInch); // move the existing step designator down - } - } - } - } - } - } - return false; - } - - string myMsg = docstyle.Continue.Top.Message; - MyPageHelper.TopMessageRs = new List(); - // bug fix B2106-099 - // when there are more than one Caution/Note off of a high level background step, - // the second, third, etc background Caution/Note pages begin printing two additional lines from the top of the page - // to fix, added a check to see the the item we are printing has the PageBrrakOnStep flag set, if it's set, - // then DON'T add two lines to the yPageStart (for the top conitnue message) - if (myMsg != null && myMsg != "" && !MyItemInfo.IsSection && !MyItemInfo.FormatStepData.PageBreakOnStep) // B2020-123 - { - // C2019-044 for BNPP put the top continue message on the same row as the Checkoff/Signoff header - // This is done by specifing a row positon in the top continue definition in the format. - // If the top continue messsage RowOverride is being used, don't move the yPageStart down (don't need to make room for it) - if (docstyle.Continue.Top.RowOverride == null) - yPageStart -= 2 * SixLinesPerInch;// Allow two lines for top continue message - if (myMsg.IndexOf(@"%sR") > -1) - { - ItemInfo myAer = MyItemInfo.IsHigh ? MyItemInfo : MyItemInfo.MyParent; - if (MyItemInfo.IsInRNO) - { - // If this is an RNO part, find the parent that is not an RNO (the reason for this is - // that RNO parts are structured as parent/child not sibling relationships, for - // example, RNO part 1.2 is the child of 1.1 not sibling). Also, if this is a caution - // or note of the RNO part, do the same because it should not use the RNO part's tab. - // However, the RNO Part will have the combined tab using its parent because this is - // needed if any of its children, for example substeps, need the combined tab. - if (((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.IsRNOPart) || MyItemInfo.IsRNOPart) - { - ItemInfo ip = MyItemInfo.MyParent; - while (ip.IsRNOPart) ip = ip.MyParent; - myMsg = myMsg.Replace(@"%sR", ip.CombinedTab); - } - // B2020-154: Incorrect top continue message tab in RNO column if for single level substep with a Caution/Note - else if ((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.MyParent.IsRNOPart) - { - if (DebugPagination.IsOpen) DebugPagination.WriteLine("***===>,'Yes','Case 1:Changed RNO Continue Message',{0},{1},,{3},'{4}'", MyItemInfo.ItemID, YSize, 0, 0, this); - ItemInfo ip = MyItemInfo.MyParent; - while (!ip.IsRNOPart) ip = ip.MyParent; - myMsg = myMsg.Replace(@"%sR", ip.CombinedTab); - } - // B2020-154: Incorrect top continue message tab in RNO column for substep with a Caution/Note within parent substeps - else if ((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.MyParent.IsInRNO) - { - if (DebugPagination.IsOpen) DebugPagination.WriteLine("***===>,'Yes','Case 2:Changed RNO Continue Message',{0},{1},,{3},'{4}'", MyItemInfo.ItemID, YSize, 0, 0, this); - myMsg = myMsg.Replace(@"%sR", MyItemInfo.MyParent.MyParent.CombinedTab); - } - else - myMsg = myMsg.Replace(@"%sR", MyItemInfo.MyParent.CombinedTab); - float xor = MyTopRNO.MyTab.XOffset; - MyPageHelper.TopMessageRs.Add(new vlnText(cb, this, myMsg, myMsg, xor, yTopMargin + 0.1F, docstyle.Continue.Top.Font)); - // get aer message, go up parent until find aer and use its combined tab: - myAer = MyItemInfo; - while (myAer.IsInRNO) myAer = myAer.MyParent; - } - else if (!MyItemInfo.IsHigh && (MyItemInfo.IsNote || MyItemInfo.IsCaution)) - { - ItemInfo ip1 = MyItemInfo.MyParent; - if (!ip1.IsHigh) myAer = ip1.MyParent; - } - myMsg = docstyle.Continue.Top.Message.Replace(@"%sR", myAer.CombinedTab); - } - if (myMsg.IndexOf(@"%s") > -1) - { - if (MyItemInfo.MyParent.IsSection && (docstyle.StructureStyle.Style & E_DocStructStyle.BottomSectionContinue) == E_DocStructStyle.BottomSectionContinue) - myMsg = myMsg.Replace(@"%s", MyItemInfo.MyParent.MyTab.CleanText.Trim()); - else - { - // F2020-023: tab includes parent tab and if caution/note don't use its parent, go up another level - string noBullet = MyItemInfo.IsCautionOrNotePart ? MyItemInfo.MyParent.MyParent.CombinedTab : MyItemInfo.MyParent.CombinedTab; - // F2026-002 Vogtle Units 3&4, don't include the RNO sub-step tab if the parent is an AER sub-step - if (docstyle.Continue.Top.DontIncludeRNOTabIfHasAERParent && MyItemInfo.MyParent.IsRNOPart && !MyItemInfo.MyParent.MyParent.IsRNOPart) - noBullet = MyItemInfo.MyParent.MyParent.CombinedTab; - // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. - // B2021-085 & 087: crash if noBullet was null. Also, if null, see if text in parent. if no text, replace the - // "%s." with noBullet (null) which won't put out just a '.' as step number. - if (docstyle.Continue.Top.RemoveBullet) - { - if (noBullet == null && MyItemInfo.IsCautionOrNotePart) noBullet = MyItemInfo.MyParent.CombinedTab; - if (noBullet != null) - { - int ind = noBullet.IndexOf(".o"); - if (ind < 0) ind = noBullet.IndexOf(".*"); - if (ind > -1) noBullet = noBullet.Substring(0, ind); - } - else - { - myMsg = myMsg.Replace(@"%s.", noBullet); - } - } - myMsg = myMsg.Replace(@"%s", noBullet); - } - } - if (myMsg.IndexOf(@"%3d") > -1) - myMsg = myMsg.Replace(@"%3d", MyItemInfo.MyHLS.Ordinal.ToString()); - if (myMsg.IndexOf(@"%2d") > -1) - myMsg = myMsg.Replace(@"%2d", MyItemInfo.MyHLS.MyTab.CleanTextNoSymbols.Trim(" .".ToCharArray()).PadLeft(2)); - if (myMsg.IndexOf(@"%d") > -1) - myMsg = myMsg.Replace(@"%d", MyItemInfo.MyHLS.MyTab.CleanTextNoSymbols.Trim(" .".ToCharArray())); - if (myMsg.IndexOf(@"%c") > -1) - myMsg = myMsg.Replace(@"%c", " "); - - // Top Continue message includes high level step tab and text - if ((docstyle.Continue.Top.HLS ?? 0) == 1) - { - myMsg = docstyle.Continue.Top.Message; // reset because we did replace strings in code above - ItemInfo parentStep = MyItemInfo.MyHLS; // get the high level step - myMsg = string.Format(myMsg, parentStep.CombinedTab, parentStep.DisplayTextKeepSpecialChars); - } - // B2023-115 Top continue message for Vogtle Alarms: 1st version done on 12/6/23. Changes to logic as per request - // from engineering done on 12/12/23. See comment below for logic for 12/12/23 (history of this file has previous - // logic) - if (((docstyle.Continue.Top.HLS ?? 0) == 4) || ((docstyle.Continue.Top.HLS ?? 0) == 7)) - { - // Vogtle Alarms: Their alarms are set up differently than standard procedures - the HLS in Vogtle - // alarms is a section in other procedures. The top continue message is shown when a break occurs: - // • A continued message will appear on the top of the page ONLY if the pagination occurs anywhere - // within the first level substep. If, for example, the page break occurs between substep 3 and substep - // 4 as in example 2, no continued message will appear on the top of the page. - // • If a continued message is needed, the continued message will include the first level substep number - // if it is a sequential substep, such as “5. (continued)”. If it is NOT a sequential substep, then only - // the word “(continued)” will appear. - // • If a page break occurs between high level steps, such as before “Causes:”, then no continued message is needed. - - // F2024-027 & F2024-028 - // Vogtle Units 3&4 needed similar top continue messages in the Local Alarms attachments as they have for the MCR Alarm point pages - // with the exception that when High Level Step (grouping text) is split and continued to the next page, the top continue message - // needs to be the HLS text with "(continued)" appended to it. - // Added a TOP.HLS value of 7 to allow for this minor difference and is set in the docstyle for that section - - bool doMessage = true; - if (MyItemInfo.IsHigh) doMessage = false; // at high, don't do message - if (MyItemInfo.MyParent.IsHigh) doMessage = false; // at first level, don't do message - // Caution/Note on first level, don't do message - if ((MyItemInfo.IsCaution || MyItemInfo.IsNote) && MyItemInfo.MyParent.MyParent.IsHigh) doMessage = false; - myMsg = docstyle.Continue.Top.Message; - if (doMessage) - { - // Get to highest level below HLS - ItemInfo cur = MyItemInfo; - while (!cur.MyParent.IsHigh) cur = cur.MyParent; - // if sequential, add on step number, otherwise just put out message: - myMsg = !cur.IsSequential ? myMsg : cur.CombinedTab + ". " + myMsg; - } - // F2024-027 & F2024-028 added else if to check of the case where we want to use the High Level Step text in the top continue message - else if (((docstyle.Continue.Top.HLS ?? 0) == 7) && MyItemInfo.MyParent != null && MyItemInfo.MyParent.IsHigh) - { - myMsg = MyItemInfo.MyParent.DisplayText + " " + myMsg; - } - else // if not doing message, clear it & set yPageStart back to what it was before handling message - { - myMsg = ""; - yPageStart += 2 * SixLinesPerInch; - } - } - // B2021-138: Top continue message for Barakah Single column New (2021) format was incorrect for some lower - // sub-steps. - if ((docstyle.Continue.Top.HLS ?? 0) == 6) - { - myMsg = docstyle.Continue.Top.Message; // reset because we did replace strings in code above - ItemInfo parentStep = MyItemInfo.MyHLS; - string ctab = parentStep.CombinedTab; - if (!MyItemInfo.MyParent.IsHigh) // If lower sub-step, get parent substep tab, skipping caution/note if in one of those - ctab = (MyItemInfo.IsInCautionOrNote) ? MyItemInfo.MyParent.MyParent.CombinedTab : MyItemInfo.MyParent.CombinedTab; - myMsg = string.Format(myMsg, ctab, parentStep.DisplayTextKeepSpecialChars); - } - // Calvert Alarms, step description have the alarm number as part of the top continue message - // Also, if the break is within the CONDITION/RESPONSE, there are continue messages in both columns at the top - // of the table, note that the continue messages WITHIN table are only printed when the - // steplevel is greater than 2 - this is from 16bit. - // NOTE THAT this code is not complete - the positioning & addition of step tab for within table are not working correctly - if ((docstyle.Continue.Top.HLS ?? 0) == 3) - { - MyPageHelper.TopMessageSub1s = new List(); - MyPageHelper.TopMessageSub2s = new List(); - - //string HLSTabTextForContMsg = MyHighLevelParagraph.MyItemInfo.MyTab.CleanText + " " + MyHighLevelParagraph.MyItemInfo.MyContent.Text; - //int len = (HLSTabTextForContMsg.Length - 10) * 6; - string tabText = @"\ul\b " + MyHighLevelParagraph.MyItemInfo.MyTab.CleanText.Trim() + @"\b0\ulnone"; - // B2017-185: added the replace of unicode dash to regular dash for the continue message so it matches the step text: - string stepText = @"\b " + MyHighLevelParagraph.MyItemInfo.MyContent.Text.Replace(@"\u8209?", "-") + @"\b0"; - //HLSTabTextForContMsg = @"\ul\b " + MyHighLevelParagraph.MyItemInfo.MyTab.CleanText.Trim() + @"\b0\ulnone \b " + MyHighLevelParagraph.MyItemInfo.MyContent.Text + @"\b0"; - vlnText vt1 = new vlnText(cb, this, tabText, tabText, MyHighLevelParagraph.MyTab.XOffset, yTopMargin + 0.1F, docstyle.Continue.Top.Font); - vt1.Width = MyHighLevelParagraph.MyTab.Width; - MyPageHelper.TopMessageRs.Add(vt1); - vlnText vt2 = new vlnText(cb, this, stepText, stepText, MyHighLevelParagraph.XOffset, yTopMargin + 0.1F, docstyle.Continue.Top.Font); - vt2.Width = MyHighLevelParagraph.Width; - MyPageHelper.TopMessageRs.Add(vt2); - - // the following code is used to print the top continue messages in the Calvert Alarm format - // CONDITION/RESPONSE table. Messages only get printed if the break is on a substep at steplevel > 2. - // see comments within code for what the tab contains, it varies depending on which side - // break occurred & how deep in the step the break occurred. - if (subTab != null && MyItemInfo.StepLevel > 2) { - bool incond = !MyItemInfo.IsInRNO; - float ybot = yTopMargin + (4 * SixLinesPerInch); - string concatrnoTab = ""; // constructed tab for Response side - string concataerTab = ""; // constructed tab for Condition side - float xoffTab = 0; // position for Response tab - float xoffMsg = 0; // position for Response message - vlnParagraph useAerParaForTab = null; // use this paragraph under Conditions for locating tab & message - if (incond) - { - // If break is in Condition side of table, use Condition tab of parent & no tab for Response side. - // Both sides have the message '(continued)'. - useAerParaForTab = MyParent; - concataerTab = MyParent.MyTab != null ? MyParent.MyTab.Text.TrimEnd() : ""; - xoffTab = 0; // no rno tab - xoffMsg = ToInt(MyItemInfo.ActiveFormat.MyStepSectionLayoutData.ColRTable, 1) + (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ((useAerParaForTab != null && useAerParaForTab.MyTab != null) ? useAerParaForTab.MyTab.Width : 7.2f); - } - else - { - // break occurred in Response side. Use the tabs up to highest RNO concatenated together. - vlnParagraph useRnoParaForTab = MyParent; - vlnParagraph useParaForTab = MyParent; - while (useParaForTab.MyItemInfo.IsInRNO) - { - concatrnoTab = (useParaForTab.MyTab != null ? useParaForTab.MyTab.Text.TrimEnd() : "") + concatrnoTab.Trim(); - if (concatrnoTab.Length > 0 && concatrnoTab[0] > '\xff') concatrnoTab = ""; - useRnoParaForTab = useParaForTab; - useParaForTab = useParaForTab.MyParent; - } - xoffTab = useRnoParaForTab.MyTab.XOffset; - xoffMsg = useRnoParaForTab.XOffset; - - // aer message when rno broke. Need to concatenate up the Condition side also until - // hitting 1st non-sequential, i.e. moves out of Condition/Response table. - useAerParaForTab = useParaForTab; // useParaForTab is 1st found non-Response step, i.e. moved into Condition side of table - while (useParaForTab.MyItemInfo.IsSequential) - { - concataerTab = (useParaForTab.MyTab != null ? useParaForTab.MyTab.Text.TrimEnd() : "") + concataerTab.Trim(); - useAerParaForTab = useParaForTab; - useParaForTab = useParaForTab.MyParent; - } - } - // For RNO tab, add a vlntext for tab and one for continue message: - float xoff1 = xoffMsg; - if (!incond) - { - vlnText vtc = new vlnText(cb, this, concatrnoTab, concatrnoTab, xoffTab, ybot, docstyle.Continue.Bottom.Font); - MyPageHelper.TopMessageSub1s.Add(vtc); - Chunk chk = (vtc.IParagraph.Chunks[0]) as Chunk; - if (chk != null) - { - float xoff2 = xoffTab + chk.GetWidthPoint() + 6; - // If the "(continue)" is going to overlap the tab, then move the "Continue)" so that it doesn't overlap. - if (xoff2 > xoff1) xoff1 = xoff2; - } - } - MyPageHelper.TopMessageSub1s.Add(new vlnText(cb, this, myMsg, myMsg, xoff1, ybot, docstyle.Continue.Bottom.Font)); - - // for aer tab, add a vlntext for tab and one for continue message: - MyPageHelper.TopMessageSub2s.Add(new vlnText(cb, this, concataerTab, concataerTab, useAerParaForTab.MyTab.XOffset, ybot, docstyle.Continue.Bottom.Font)); - MyPageHelper.TopMessageSub2s.Add(new vlnText(cb, this, myMsg, myMsg, useAerParaForTab.XOffset, ybot, docstyle.Continue.Bottom.Font)); - addExtraLine = true; - } - } - if (!PageBreakOnStep) - { - float colPos = docstyle.Layout.LeftMargin + docstyle.Continue.Top.Margin ?? 0; - if (!docstyle.Continue.Top.PlaceAtLeftMargin) //F2019-033 when true position with respect only to the left margin - colPos += XOffsetBox; //XOffsetbox get set when the tables, figures & equations were beyond the border and needed repositioned - // C2019-044 for BNPP, put the top continue message on the same row as the checkoff/signoff heading - // RowOverride specifies the position of the top continue message - // For BNPP, RowOverride is set to the same row as the checkoff header is set to in the pagelist - if (docstyle.Continue.Top.RowOverride != null) - { - float adjRowPosition = (float)docstyle.Layout.TopMargin - (float)docstyle.Continue.Top.RowOverride; - MyPageHelper.TopMessage = new vlnText(cb, this, myMsg, myMsg, colPos, yTopMargin + 0.1F + adjRowPosition, docstyle.Continue.Top.Font);// MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font); - } - else - MyPageHelper.TopMessage = new vlnText(cb, this, myMsg, myMsg, colPos, yTopMargin + 0.1F, docstyle.Continue.Top.Font);// MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font); - - } - else - MyPageHelper.TopMessage = null; - } - return addExtraLine; - } - - private void DoBottomContinueMsg(PdfContentByte cb, float yBottomMargin, float yLocation, DocStyle docstyle, bool doThreeContinues) - { - // Console.WriteLine("Page {0} - yLocation {1}", cb.PdfWriter.PageNumber, yLocation); - string myMsg = docstyle.Continue.Bottom.Message; - - // a format flag exists that states to only put a BOTTOM message if it is a certain type (RNO) - // check for this.... - bool RNOContinueOnly = MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly; - bool doBottom = !RNOContinueOnly || (MyItemInfo.IsInRNO && RNOContinueOnly); - if (doBottom && myMsg != null && myMsg != "") - { - myMsg = ReplaceStepBottomContinue(myMsg); - float msg_yLocation = 0; - if (myMsg.Contains("{par}")) - { - myMsg = myMsg.Replace("{par}", ""); - msg_yLocation = -SixLinesPerInch; - } - float yBtmMarginForMsg = yBottomMargin; - - // one of the format flags for FNP had an adjustment for printing the section title only - // on the first page of the section. Adjust the location of the bottom continue message - // if this adjustment was made (the current topmargin may not reflect the value within - // the document style) - if (MyPageHelper.PrintedSectionPage > 0) - { - if (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PrintSectOnFirst) == E_DocStructStyle.DSS_PrintSectOnFirst) // C2018-003 fixed use of getting the active section - { - float localYTopMargin = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize) - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin; // C2020-002 paper size is now set in the format files - yBtmMarginForMsg = Math.Max(0, localYTopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); - } - } - // include space for phone list when determining bottom continue message location - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.PrintPhoneList && MyPageHelper.PhoneListHeight != 0) - yBtmMarginForMsg += (MyPageHelper.PhoneListHeight - vlnPrintObject.SixLinesPerInch); - // B2019-079: Account for compression when locating the bottom continue message - if (MyPageHelper.YMultiplier != 1) - { - //float topOfPage = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize) - (float)MyItemInfo.MyDocStyle.Layout.TopMargin; // A4 paper logic - float topOfPage = 792 - (float)MyItemInfo.MyDocStyle.Layout.TopMargin; - yLocation = topOfPage - (topOfPage - yLocation) * MyPageHelper.YMultiplier; - } - switch (docstyle.Continue.Bottom.Location) - { - case E_ContBottomLoc.EndOfText: // place continue string at end of text - // msg_yLocation accounts for extra lines in message from docstyle; and BottomContent is the actual - // location of the last line of text on page. - //msg_yLocation = ((float)(MyPageHelper.BottomContent??0) - (SixLinesPerInch * MyPageHelper.YMultiplier)); // B2018-080 null reference check added - // B2019-079 changed yLocaton - msg_yLocation to '+'. The msg_ylocation has an adjustment for adding an extra line by moving down the page, this was moving - // the line up the page (double negative). - msg_yLocation = yLocation + msg_yLocation - (SixLinesPerInch * MyPageHelper.YMultiplier); //B2019-021 yLocation accounts for checkoffs - if (yBottomMargin + (docstyle.Layout.FooterLength ?? 0) > msg_yLocation) - { // Adjusted Continue Message Y Offset - //DebugPagination.WriteLine("====>> {0},'{1}'", msg_yLocation, MyItemInfo.ShortPath); - //msg_yLocation = (float) MyPageHelper.BottomContent - SixLinesPerInch; // Account for how low the lowest Item is on the page - float msg_yLocationOld = msg_yLocation = yBottomMargin + (docstyle.Layout.FooterLength ?? 0); - if (MyPageHelper.BottomContent != null) - msg_yLocation = Math.Min(yBottomMargin + (docstyle.Layout.FooterLength ?? 0), (float)MyPageHelper.BottomContent - SixLinesPerInch);// RHM20150525 - Table Scrunch - if (msg_yLocationOld != msg_yLocation) - _MyLog.WarnFormat("Continue Message Moved from {0} to {1} for {2}", msg_yLocationOld, msg_yLocation, this);// RHM20150525 - Table Scrunch - } - break; - case E_ContBottomLoc.BtwnTextAndBottom: // place continue string between end of text & bottom of page - msg_yLocation = msg_yLocation + yLocation - ((yLocation - yBottomMargin) / 2); // +SixLinesPerInch; // (need this for IP3) - msg_yLocation = Math.Max(msg_yLocation, yBottomMargin + SixLinesPerInch); - break; - case E_ContBottomLoc.BottomOfPage: // place continue message at bottom of page - //msg_yLocation = yBottomMargin + 2 * SixLinesPerInch + (float)docstyle.Layout.FooterLength; // 2 lines above bottom margin - msg_yLocation = msg_yLocation + yBtmMarginForMsg + (float)docstyle.Layout.FooterLength; - // if (MyPageHelper.YMultiplier != 1.0F) msg_yLocation = msg_yLocation / MyPageHelper.YMultiplier; - break; - case E_ContBottomLoc.BelowBottom1: - msg_yLocation = msg_yLocation + yBtmMarginForMsg; - break; - case E_ContBottomLoc.BottomWithFooter: // put bottom message AND if in CONDITION/RESPONSE table, in both columns. - msg_yLocation = msg_yLocation + yBtmMarginForMsg; - break; - case E_ContBottomLoc.EndOfText2: // Like EndOfText but limited within yBottomMargin - msg_yLocation = Math.Max(msg_yLocation + yLocation - SixLinesPerInch, yBottomMargin + SixLinesPerInch); - break; - case E_ContBottomLoc.BtwnTextAndBottom2: - // Like BtwnTextAndBottom but accounts for line spacing of step & is 1 line up on page (for BGE - Procedure Steps - 2 column) - float adj = (!MyItemInfo.IsSection && MyItemInfo.FormatStepData.StepLayoutData.EveryNLines == 1) ? SixLinesPerInch : 0; - msg_yLocation = msg_yLocation + yLocation - ((yLocation - yBottomMargin) / 2) + adj;// +SixLinesPerInch; - if (msg_yLocation < yBottomMargin) msg_yLocation = yBottomMargin; - break; - default: - _MyLog.WarnFormat("**** BOTTOM CONTINUE MESSAGE NOT CODED FOR LOCATION {0}*****", docstyle.Continue.Bottom.Location); - break; - } - if (!PageBreakOnStep) - { - float xoffB = 0; - // Added for Calvert Alarms: if 'doThreeContinues', continue message at bottom of page - // and a continue message at the bottom of each column. - if (doThreeContinues) - { - float ybot = yLocation; - xoffB = (float)docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; - MyPageHelper.BottomMessageA = new vlnText(cb, this, myMsg, myMsg, xoffB, ybot, docstyle.Continue.Bottom.Font); - xoffB = docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.MarginR ?? 0; - MyPageHelper.BottomMessageR = new vlnText(cb, this, myMsg, myMsg, xoffB, ybot, docstyle.Continue.Bottom.Font); - MyPageHelper.AlarmYoffEnd -= SixLinesPerInch; - float tmp = (((float)docstyle.Layout.PageWidth - (float)docstyle.Layout.LeftMargin) / 2) - (myMsg.Length / 2 * 5); - xoffB = (float)docstyle.Layout.LeftMargin + tmp; - } - else if (docstyle.Continue.Bottom.Location == E_ContBottomLoc.BottomWithFooter) - { - float tmp = (((float)docstyle.Layout.PageWidth - (float)docstyle.Layout.LeftMargin) / 2) - (myMsg.Length / 2 * 5); - xoffB = (float)docstyle.Layout.LeftMargin + tmp; - } - else if (RNOContinueOnly) - { - // The following line was added for McGuire APs/AP/1/5500/12, Step 13 - //if (msg_yLocation < yBottomMargin + SixLinesPerInch) msg_yLocation = yBottomMargin + SixLinesPerInch; - float colR = float.Parse(MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColRTable.Split(",".ToCharArray())[MyItemInfo.ColumnMode]); - xoffB = colR + docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; - } - else if (MyItemInfo.IsInRNO && (docstyle.Continue.Bottom.MarginR ?? 0) > 0) - { - xoffB = (float)docstyle.Layout.LeftMargin + (float)docstyle.Continue.Bottom.MarginR; - MyPageHelper.BottomMessageR = new vlnText(cb, this, myMsg, myMsg, xoffB, msg_yLocation, docstyle.Continue.Bottom.Font); - xoffB = (float)docstyle.Layout.LeftMargin + (float)docstyle.Continue.Bottom.Margin; - - } - // FloatingContinueMessage format flag: - // if breaking at the AER put continue message in left column, - // if breaking RNO put continue message in Right column. - else if (MyItemInfo.IsInRNO && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.FloatingContinueMessage) - { - float colR = float.Parse(MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColRTable.Split(",".ToCharArray())[MyItemInfo.ColumnMode]); - xoffB = colR + docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; - } - else - xoffB = docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; - //MyPageHelper.BottomMessage = new vlnText(cb, this, myMsg, myMsg, docstyle.Layout.LeftMargin + XOffsetBox + docstyle.Continue.Bottom.Margin ?? 0, msg_yLocation, docstyle.Continue.Bottom.Font);// MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font); - MyPageHelper.BottomMessage.Clear(); // B2017-207 should be only one continue message - was putting an extra continue message in middle of page for V.S.Summer (ex. AOP set, 900.4 Attachment 12) - MyPageHelper.BottomMessage.Add(new vlnText(cb, this, myMsg, myMsg, xoffB, msg_yLocation, docstyle.Continue.Bottom.Font)); - } - } - if (PageBreakOnStep) MyPageHelper.BottomMessage.Clear(); - } - - private void RefreshDocStyle() - { - MyItemInfo.ActiveSection = null; - MyItemInfo.MyDocStyle = null; - MyPageHelper.MySection = MyItemInfo as SectionInfo; - MyPageHelper.ResetSvg(); - MyPageHelper.PrintedSectionPage = 0; - } - - private string ReplaceStepBottomContinue(string myMsg) - { - string tb = null; - if (MyItemInfo.IsSection) - tb = MyItemInfo.MyTab.CleanText.Trim(); - else - tb = MyItemInfo.MyHLS.MyTab.CleanTextNoSymbols; - // if the tab ends with .0, remove it if it was added because of the virtualdotinhls flag. - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.VirtualDotInHLSTab && tb.Contains(".0")) tb = tb.Replace(".0", ""); - if (myMsg.IndexOf(@"%d") > -1) - myMsg = myMsg.Replace(@"%d", tb.Trim()); - if (myMsg.IndexOf(@"%0d") > -1) - myMsg = myMsg.Replace(@"%0d", tb.Trim(" .".ToCharArray())); - if (myMsg.IndexOf(@"%2d") > -1) - myMsg = myMsg.Replace(@"%2d", tb.Trim(" .".ToCharArray()).PadLeft(2)); - if (myMsg.IndexOf(@"%3d") > -1) - myMsg = myMsg.Replace(@"%3d", MyItemInfo.MyHLS.Ordinal.ToString()); - // F2020-023: tab includes parent tab and if caution/note don't use its parent, go up another level - if (myMsg.IndexOf(@"%s") > -1) // %s was added for F2020-023 - { - string tmp = tb.Trim(); - if (!MyItemInfo.MyParent.IsHigh) - { - tmp = MyItemInfo.IsCautionOrNotePart ? MyItemInfo.MyParent.MyParent.CombinedTab : MyItemInfo.MyParent.CombinedTab; - // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. - // B2021-085 & 087: crash if noBullet was null. Also, if null, see if text in parent. if no text, replace the - // "%s." with noBullet (null) which won't put out just a '.' as step number. - if (MyItemInfo.MyDocStyle.Continue.Bottom.RemoveBullet) - { - if (tmp == null && MyItemInfo.IsCautionOrNotePart) tmp = MyItemInfo.MyParent.CombinedTab; - if (tmp != null) - { - int ind = tmp.IndexOf(".o"); - if (ind < 0) ind = tmp.IndexOf(".*"); - if (ind > -1) tmp = tmp.Substring(0, ind); - } - else - { - myMsg = myMsg.Replace(@"%s.", tmp); - } - } - } - myMsg = myMsg.Replace(@"%s", tmp); - } - return myMsg; - } - private vlnParagraph TopMostChild - { - get - { - if (ChildrenAbove.Count > 0) return ChildrenAbove[0].TopMostChild; - return this; - } - } - private bool EmptyTopMostPart - { - get - { - if (TopMostChild.PartsAbove.Count == 0) return false; - if (TopMostChild.PartsContainer != null && TopMostChild.PartsContainer.Count > 0) return false; // B2016-198: not 'EmptyTopMostPart' if there is a box. - foreach (vlnPrintObject po in TopMostChild.PartsAbove) - { - vlnHeader hd = po as vlnHeader; - if (hd == null) return false; - if (hd.Text != "") return false; - } - return true; - } - } - // B2019-115 Locate Bottom Continue Message below AER Table if necesssary - private float _TableBottom = -1; - public float TableBottom - { - get { return _TableBottom; } - set { _TableBottom = value; } - } - private float OutputOtherPageSteps(PdfContentByte cb, float YTopMost, float yPageStart, float yTopMargin, float yBottomMargin) - { - // B2019-115 Locate Bottom Continue Message below AER Table if necessary - Initialize TableBottom to -1 - TableBottom = -1; - float retval = YTopMost; - // Find any items remaining in MyPageHelper.MyParagraphs that should be printed on this page. - vlnParagraphs process = new vlnParagraphs(null); - int processed = 0; - foreach (vlnParagraph vPara in MyPageHelper.MyParagraphs.Values) - { - if (!vPara.Processed) - { - if (vPara.MyItemInfo.IsTable && (vPara.YOffset <= YTopMost) && vPara.MyItemInfo.ActiveSection.ColumnMode > 0 && vPara.Height + yBottomMargin < yPageStart - vPara.YOffset) //B2019-120 Byron ELEC-1 step 3 second table was not printing on following page - { - if (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID) - { - // B2019-115 Locate Bottom Continue Message below AER Table if necessary - _MyLog.WarnFormat("\r\n=-=-=> Table Print on First Page {0} {1} ColumnMode = {2}", vPara.MyItemInfo.ItemID, vPara.MyItemInfo.ShortPath, vPara.MyItemInfo.ActiveSection.ColumnMode); - process.Add(vPara); - // Console.WriteLine("Table YOffset {0} height {1} Bottom = {2} yPageStart = {3} Bottom {4}", vPara.YOffset, vPara.Height, vPara.YOffset + vPara.Height - yPageStart, yPageStart, this.YBottom); - } - } - else if (((vPara.YOffset + vPara.Height) < YTopMost)) - { - // B2019-028: Added check for active section in next line so that following section text doesn't overlap or start too far down on page for case where there is a subsection - // with subsections of type Step/Word/Step - //if (vPara.MyItemInfo.ActiveSection.ItemID == this.MyItemInfo.ActiveSection.ItemID && (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID)) // 20150701 Complicated RNO change - if (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID) - { - // B2019-077: 2.0 SCOPE empty section not printing for WES (revert to previous code line versus above) - process.Add(vPara); - } - else // 20150701 Complicated RNO change - _MyLog.WarnFormat("Less Than: Step Could Have Fit {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); - } - else if (((vPara.YOffset + vPara.Height) == YTopMost)) - { - - // B2019-028: see above comment (same check was added) - //if (vPara.MyItemInfo.ActiveSection.ItemID == this.MyItemInfo.ActiveSection.ItemID && (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID)) // RHM20150507 Table Scrunch - if (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID) // B2019-077: see above - { - process.Add(vPara); - _MyLog.WarnFormat("New AerRno PageBreak Logic: Step Could Have Fit {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); - } - else // RHM20150507 Table Scrunch - _MyLog.WarnFormat("Equal: Step Could Have Fit {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); - } - else if (((vPara.YOffset) < YTopMost)) - { - retval = Math.Min(retval, vPara.YTopMost); - } - } - else - processed++; - } - //Console.WriteLine("~~~ {0} has {1} Steps {2} Processed {3} to Process", MyItemInfo.ShortPath, MyPageHelper.MyParagraphs.Count - // , processed,process.Count); - foreach (vlnParagraph vPara in process) - { - vPara.ParagraphToPdf(cb, yPageStart, yTopMargin, yBottomMargin); - // B2019-115 Locate Bottom Continue Message below AER Table if necessary - if(vPara.MyItemInfo.IsTable) - { - if (TableBottom == -1) - TableBottom = (yPageStart-vPara.YOffset)-vPara.Height- SixLinesPerInch; - else - TableBottom = Math.Min(TableBottom, (yPageStart - vPara.YOffset) - vPara.Height - SixLinesPerInch); - } - } - return retval; - } - private float _YVeryTop = -1; - public float YVeryTop - { - get - { - if (_YVeryTop == -1) - { - _YVeryTop = YTop; - _YVeryTop = VeryTop(PartsAbove, _YVeryTop); - _YVeryTop = VeryTop(PartsContainer, _YVeryTop); - } - return _YVeryTop; - } - } - - private float VeryTop(vlnPrintObjects parts, float yVeryTop) - { - if (parts != null) - foreach (vlnPrintObject part in parts) - if (part.YOffset < yVeryTop) - yVeryTop = part.YOffset; - return yVeryTop; - } - /// - /// This gets the height of the step with it's Caution's, Notes and potentially any First Substeps - /// - /// - // F2024-006: Vogtle Alarms pagination - added 'includeFirstSub' to get that size of the first substep with the parent step - // to help determine pagination - private float GetFirstPieceSize(bool includeFirstSub = false) - { - vlnParagraph paraLast = GetFirstPieceLastPart(includeFirstSub); - float retval = (paraLast.YBottom) - YTopMost; - //Console.WriteLine(MyItemInfo.DBSequence); - return retval; - } - public override float YBottom - { - get - { - float bottom = YOffset + Height; - if (PartsBelow != null) - { - foreach (vlnPrintObject part in PartsBelow) - { - float partBottom = part.YBottom; - bottom = Math.Max(partBottom, bottom); - } - } - return bottom; - } - } - public float YVeryBottom - { - get - { - float bottom = YOffset + Height; - if (ChildrenBelow != null) - foreach (vlnParagraph child in ChildrenBelow) - bottom = Math.Max(child.YVeryBottom, bottom); - if (ChildrenLeft != null) - foreach (vlnParagraph child in ChildrenLeft) - bottom = Math.Max(child.YVeryBottom, bottom); - if (ChildrenRight != null) - foreach (vlnParagraph child in ChildrenRight) - bottom = Math.Max(child.YVeryBottom, bottom); - if (PartsBelow != null) - foreach (vlnPrintObject part in PartsBelow) - bottom = Math.Max(part.YBottom, bottom); - return bottom; - } - } - public float YBottomText - { - get - { - return YOffset + Height; - } - } - private float _YBottomForBox = 0; - public float YBottomForBox - { - get { return _YBottomForBox; } - set { _YBottomForBox = value; } - } - // F2024-006: Vogtle Alarms pagination - added 'includeFirstSub' to get that size of the first substep with the parent step - // to help determine pagination - even when PaginateOnFirstSubstep is turned on - private vlnParagraph GetFirstPieceLastPart(bool includeFirstSub = false) - { - vlnParagraph para = this; - if ((!MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PaginateOnFirstSubstep || includeFirstSub) && ChildrenBelow != null && ChildrenBelow.Count > 0) - { - // If the substep has a separator (OR, AND) then return the last substep rather than the first. - string mySep = ChildrenBelow[0].MyItemInfo.FormatStepData.Sep ?? "{Null}"; - if (mySep != "{Null}" && mySep != "") - para = ChildrenBelow[ChildrenBelow.Count - 1].GetFirstPieceLastPart(); - else - { - // MNS Pagination - Mike Weiner Case 1a to keep step together with any non-sequential substeps (ANDs, EQ List) - bool keepEqListTogether = ChildrenBelow[0].MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PutOnPageByItself; - if (keepEqListTogether && !ChildrenBelow[0].MyItemInfo.IsSequential && !this.MyItemInfo.IsHigh) // Extend to the last Item. - para = ChildrenBelow[ChildrenBelow.Count - 1].GetFirstPieceLastPart(); - else - para = ChildrenBelow[0].GetFirstPieceLastPart(includeFirstSub); - } - } - if (ChildrenRight != null && ChildrenRight.Count > 0) - { - foreach (vlnParagraph paraRight in ChildrenRight) - { - vlnParagraph paraRightLast = paraRight.GetFirstPieceLastPart(includeFirstSub); - if (paraRightLast.YBottom > para.YBottom) - para = paraRightLast; - } - } - return para; - } - /// - /// Find items from previous page (yLocation less than yTop) and remove them from the list. - /// yTop is the new starting location on the next page for this step. - /// - /// - /// - private void RemoveProcessedParagraphs(StepLevelList myList, float yTop) - { - // the two CleanUpLists are used to remove items from - // the original list because list items cannot be removed in a - // 'foreach'. - List CleanupListStepLevel = new List(); - foreach (int stepLevel in myList.Keys) - { - List CleanupListYLocation = new List(); - SortedList AdjustYLocation = new SortedList(); - foreach (float yLocation in myList[stepLevel].Keys) - { - if (-yLocation <= yTop) - CleanupListYLocation.Add(yLocation); - else - AdjustYLocation.Add(-yLocation, yLocation); // order in ascending order - } - foreach (float yLocation in CleanupListYLocation) - myList[stepLevel].Remove(yLocation); - foreach (float yLocation in AdjustYLocation.Keys) - { - vlnParagraph para = myList[stepLevel][-yLocation]; - myList[stepLevel].Remove(-yLocation); - // shift yLocation by yTop to work with items whose locations - // are defined from the top of the new page rather than - // from the beginning of the step. - // Note that yLocation is negative to have items in descending - // order so that adding yTop decrements their values. - if (!myList[stepLevel].ContainsKey(yTop - yLocation)) - myList[stepLevel].Add(yTop - yLocation, para); - } - if (myList[stepLevel].Count == 0) - CleanupListStepLevel.Add(stepLevel); - } - foreach (int stepLevel in CleanupListStepLevel) - myList.Remove(stepLevel); - } - /// - /// Builds a list of paragraphs by StepLevel and yLocation in descending order. - /// - /// - /// - private void BuildLocationList(float yTopMost, ParagraphLocations myLocations) - { - foreach (vlnParagraph child in ChildrenAbove) - child.BuildLocationList(yTopMost, myLocations); - foreach (vlnParagraph child in ChildrenLeft) - child.BuildLocationList(yTopMost, myLocations); - - // Add a list entry consisting of StepLevel, yoffset from the beginning of this step, paragraph itself - myLocations.Add(this, yTopMost); - - foreach (vlnParagraph child in ChildrenRight) - child.BuildLocationList(yTopMost, myLocations); - foreach (vlnParagraph child in ChildrenBelow) - child.BuildLocationList(yTopMost, myLocations); - } - private int COL_WID_ADJ = 6; // adjusts for incorrect use of WidSTable when breaking a line (it breaks 6 chars too short) - private bool IsTitleType(ItemInfo itm) - { - if (itm.FormatStepData != null && (itm.FormatStepData.Index == 42 || itm.FormatStepData.Index == 43)) return true; - return false; - } - private static VlnFlexGrid _MyFlexGrid = new VlnFlexGrid(1, 1); - public static VlnFlexGrid MyFlexGrid - { - get { return _MyFlexGrid; } - } - private pkParagraph _MyPlaceKeeper = null; - public pkParagraph MyPlaceKeeper - { - get { return _MyPlaceKeeper; } - set { _MyPlaceKeeper = value; } - } - private pkParagraph _MyContAct = null; - public pkParagraph MyContAct - { - get { return _MyContAct; } - set { _MyContAct = value; } - } - // F2022-024 Time Critical Action - private pkParagraph _MyTimeCriticalAction = null; - public pkParagraph MyTimeCriticalAction - { - get { return _MyTimeCriticalAction; } - set { _MyTimeCriticalAction = value; } - } - public static bool InList(int id, params int[] ids) - { - foreach (int listid in ids) - if (id == listid) return true; - return false; - } - private bool _PrefixSpecialCharacter = false; - public bool PrefixSpecialCharacter - { - get { return _PrefixSpecialCharacter; } - set { _PrefixSpecialCharacter = value; } - } - private string _Prefix; - public string Prefix - { - get { return _Prefix; } - set { _Prefix = value; } - } - private string _Suffix; - public string Suffix - { - get { return _Suffix; } - set { _Suffix = value; } - } - private float RoughSizeOfPage - { - get - { - return (float)(MyItemInfo.MyDocStyle.Layout.PageLength /*- MyItemInfo.MyDocStyle.Layout.TopMargin*/ - MyItemInfo.MyDocStyle.Layout.FooterLength); - } - } - private PromsPrinter _MyPromsPrinter; - public PromsPrinter MyPromsPrinter - { - get { return _MyPromsPrinter; } - set { _MyPromsPrinter = value; } - } - public static float _yPageStartForSupInfo = 0; - public vlnParagraph(vlnParagraph parent, PdfContentByte cb, ItemInfo itemInfo, float xoff, float yoff, int rnoLevel, int maxRNO, FormatInfo formatInfo, string prefix, string suffix, float yoffRightParent, bool loadChildren, PromsPrinter pp) - { - MyPromsPrinter = pp ?? parent.MyPromsPrinter; - int profileDepth = ProfileTimer.Push(">>>> vlnParagraph"); - Prefix = prefix; - Suffix = suffix; - MyItemInfo = itemInfo; - MyContentByte = cb; - if (itemInfo.IsFootnote && loadChildren) - { - // notestofootnoteshls is a list, a hls can have more than one note - if (MyPageHelper.NotesToFootNotesHLS.ContainsKey(itemInfo.MyHLS.ItemID)) - MyPageHelper.NotesToFootNotesHLS[itemInfo.MyHLS.ItemID].Add(itemInfo.ItemID); - else - { - List notesList = new List(); - notesList.Add(itemInfo.ItemID); - MyPageHelper.NotesToFootNotesHLS.Add(itemInfo.MyHLS.ItemID, notesList); - } - Processed = true; // don't want to print during normal ToPdf/ParagraphToPdf cycle - print in vlnsvgpagehelper - ProfileTimer.Pop(profileDepth); - return; - } - // do some 'setup' for Calvert Alarms: - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - // The CONDITION/RESPONSE portion of the alarm uses a macro to print the 'table' heading, - // i.e. the lines/boxes and text for CONDITION and RESPONSE. This does not have a tab, - // tabs are where the macros are usually stored, so flag this for future reference. - // The 2nd if is executed when the step is at the same y offset as the parent, i.e. DEVICE & SETPOINT text. - if (itemInfo.TemplateIndex > 0 && itemInfo.ActiveFormat.PlantFormat.FormatData.Templates[itemInfo.TemplateIndex].hmacro > 0) - HasCalvertMacro = true; - if (KeepOnParentLine(itemInfo)) yoff = parent.YOffset; - } - float yOffOrig = yoff; - // Save step text information to be used to create a PlaceKeeper (Calver Cliffs) - BuildPlacekeeper(parent, itemInfo); - - // Save step text information to be used to create a Continuous Action Summary - if (MyPromsPrinter.ShouldPrint_CAS_CTAS) BuildContinuousActionSummary(parent, itemInfo); - - // F2022-024 Time Critical Step - // Save step text information to be used to create a Time Critical Action Summary - if (MyPromsPrinter.ShouldPrint_CAS_CTAS) BuildTimeCriticalActionSummary(parent, itemInfo); - - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.BoxLeftAdj != null) - _MyBoxLeftAdj = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.BoxLeftAdj); - ShowSectionTitles = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ShowSectionTitles || itemInfo.MyDocStyle.ShowSectionTitles; - if (itemInfo.IsSection && itemInfo.ActiveSection.DisplayText.ToUpper().Contains("") && !itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.PrintNoTitle) ShowSectionTitles = false; - HasIndent = itemInfo.IsStep && itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.DontResetIndentOnNewline; - - int MetaLevel = 0; // if meta section, stores what level this section is. - float savCheckListBottomMost = 0; - //int[] problemIDs = { 889 }; - //List lProblemIDs = new List(problemIDs); - //if (lProblemIDs.Contains(itemInfo.ItemID)) - // Console.WriteLine("Found Item {0}", itemInfo.ItemID);formatInfochecko - MyParent = parent; - // The following code determines the last paragraph for an RNO - // MyTopRNO finds the Top paragraph for an RNO - if (itemInfo.IsInRNO) - { - if (rnoLevel <= maxRNO && itemInfo.IsRNOPart) // Not top level RNO - MyTopRNO = this; - else - MyTopRNO = MyParent.MyTopRNO; - if (MyTopRNO != null) MyTopRNO.LastRNO = this; - } - if (!MyPageHelper.MyParagraphs.ContainsKey(itemInfo.ItemID) && !itemInfo.IsFootnote) - { - MyPageHelper.MyParagraphs.Add(itemInfo.ItemID, this); - } - // if this a continuous subsection, refresh the style. - // This was commented out to fix a Westinghouse print issue 3-21-2014, orignally put in for Farley - //if (itemInfo.IsStepSection && !(itemInfo as SectionInfo).IsSeparatePagination() && itemInfo.MyParent.IsSection) - // RefreshDocStyle(); - - XOffset = xoff; - if (!MyItemInfo.IsStep && !MyItemInfo.IsStepSection && MyItemInfo.MyContent.MyEntry != null) - { - IsWordDocPara = true; - // special case - this is a 'Word Doc' paragraph. The Processed flag is used to know - // that steps need put out on a page for the pagination logic, and since there are no steps - // we don't want to have to worry about putting this out for pagination logic. - Processed = true; - ProfileTimer.Pop(profileDepth); - return; - } - YTopMost = YOffset = yoff; - vlnTab mytab = null; - bool doSectTab = false; - // if this substep has a caution or note as its parent, then there may have been a special indent done on the - // substep... check the CautionOrNoteSubstepIndent value, this is the additional indent amount in number - // of characters. - if (itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote) - { - // if this is a Note or Caution off of a Note or Caution (Catawba EG/1A/CSAM/SACGR1 step 1) - // then indent it the length of its tab - if (itemInfo.IsCaution || itemInfo.IsNote) - XOffset += (!itemInfo.IsBackgroundStep()) ? (itemInfo.FormatStepData.TabData.IdentPrint.Length - 1) * 6 : 0; // B2018-139 don't adjust XOffset when processing a Caution, or Note background text is is off of Caution or Note WCN BG SAG-10 step 4 - - else - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) - XOffset = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset); - else - XOffset += 72 * (itemInfo.FormatStepData.CautionOrNoteSubstepIndent == null ? 0 : (float)itemInfo.FormatStepData.CautionOrNoteSubstepIndent / (float)itemInfo.FormatStepData.Font.CPI); - } - - if (itemInfo.IsStep && itemInfo.MyHLS != null && itemInfo.MyHLS.FormatStepData.UseSmartTemplate && - itemInfo.FormatStepData.StepLayoutData.AlignWithParentTab - || (itemInfo.Steps != null && itemInfo.Steps.Count > 0 && itemInfo.Steps[0].FormatStepData.StepLayoutData.AlignWithParentTab)) - itemInfo.MyTab = null; - - float xMetaAdj = 0; - - if (itemInfo.IsFootnote) itemInfo.MyTab = null; - - if (itemInfo.IsSupInfoPart) XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - - //if (itemInfo.MyTab != null && itemInfo.MyTab.Text != null && itemInfo.MyTab.Text != "") - // bug fix - if the section does not have a section number, then we need to build an empty tab for the itemInfo - // so that we place the section title in the correct location. so we need to go into this IF code block - // even if itemInfo has a MyTab that is an empty string when itemInfo is a section - 2/11/2015 - if (itemInfo.MyTab != null && itemInfo.MyTab.Text != null && (itemInfo.MyTab.Text != "" || itemInfo.IsSection)) - { - float localXOffset = XOffset; - bool doprint = true; - if (itemInfo.IsSection) - { - MyItemInfo.ActiveSection = null; - MyItemInfo.MyDocStyle = null; - DocStyle ds = MyItemInfo.MyDocStyle; - - if (!ds.ComponentList && ShowSectionTitles - && !MyItemInfo.MyDocStyle.CancelSectTitle - && !MyItemInfo.MyDocStyle.SpecialStepsFoldout) // Don't ouput the Step Section title - { - SectionConfig sch = MyItemInfo.MyConfig as SectionConfig; - if (sch != null && sch.Section_PrintHdr != "Y") - { - doprint = false; - YTopMost = 0; - } - } - else - doprint = false; - } - // if printing the supplemental info facing page, don't put out the section title. ToPdf will put out 'Supplemental Information' title. - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && MyPageHelper.CreatingSupInfoPage && itemInfo.IsSection) doprint = false; - if (doprint && itemInfo.IsSection && !itemInfo.MyDocStyle.CancelSectTitle && (itemInfo.MyConfig as SectionConfig).Section_IsFoldout != "Y") //C2019-042 Section_IsFoldout checks Section Number, Section Title, and use of check box - { - doSectTab = true; - if (itemInfo.IsStepSection && formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Just.Contains("PSLeft")) - { - float offset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - if (formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos != null) - { - ItemInfo iilvl = itemInfo; - while (!iilvl.IsProcedure) - { - // see if this metasection, walking up the tree, has its header printed, - // if so, indent for it. - SectionConfig sch1 = iilvl.MyConfig as SectionConfig; - if (sch1.Section_PrintHdr == "Y" || MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) - MetaLevel++; - iilvl = iilvl.MyParent; - } - - if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - { - if (MetaLevel == 1) - offset += (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - else - { - SectionConfig sc = itemInfo.MyParent.MyConfig as SectionConfig; - if (MyParent != null) - { - // if the parent is not printed, then adjust the xoffset based on - // the level of the metasection. Note that the 'if (MetaLevel==20) MetaLevel = 1' - // line of code was added so that the xoffsets between 16 & 32 bit are closer. - // This code was added to fix problems in BGE OI34, Appendix sections/subsection xoffsets. - if (sc != null && sc.Section_PrintHdr == "N") - { - if (MetaLevel == 2) MetaLevel = 1; - xMetaAdj = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[0].ColSByLevel; - for (int i = 0; i < MetaLevel; i++) - { - xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[i].SecNumPositionAdj; - } - offset += xMetaAdj; - } - else - { - offset = (sc != null && sc.SubSection_AutoIndent == "Y") ? MyParent.XOffset - : (MyParent.MyTab != null) ? MyParent.MyTab.XOffset : XOffset; - } - } - } - } - else - { - - MetaLevel = MetaLevel <= 2 ? 1 : MetaLevel - 1; - if (MetaLevel == 1) - offset += (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - else - { - xMetaAdj = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[0].ColSByLevel; - for (int i = 0; i < MetaLevel; i++) - { - xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[i].SecNumPositionAdj; - - } - offset += xMetaAdj; - itemInfo.MyTab.Text = itemInfo.MyTab.Text.TrimEnd(" ".ToCharArray()); - itemInfo.MyTab.CleanText = itemInfo.MyTab.CleanText.TrimEnd(" ".ToCharArray()); - if (((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_SameXOffSubsections) == E_DocStructStyle.DSS_SameXOffSubsections)) - offset += (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - } - } - } - localXOffset = offset; - } - } - if (!itemInfo.IsSection || doSectTab) - { - if (itemInfo.IsSupInfoPart) // get combined tab if on a supinfo facing page: - mytab = GetSupInfoTab(cb, itemInfo, yoff, mytab, doSectTab, localXOffset); - else if (itemInfo.MyTab.AltPrintTab != null) - mytab = new vlnTab(cb, this, itemInfo.MyTab.AltPrintTab, itemInfo.MyTab.AltPrintTab, localXOffset, yoff, itemInfo.MyTab.MyFont, doSectTab, StepRTB.MySymbolFontName, itemInfo.MyTab.RemovedStyleUnderline); - else { - string clntxt = itemInfo.MyTab.CleanText; - if (!string.IsNullOrEmpty(itemInfo.FormatStepData?.TabData?.MacroEditTag) && itemInfo.FormatStepData.TabData.MacroEditTag == "_" && clntxt.StartsWith("_")) - clntxt = clntxt.Substring(1); - mytab = new vlnTab(cb, this, itemInfo.MyTab.Text, clntxt, localXOffset, yoff, itemInfo.MyTab.MyFont, doSectTab, StepRTB.MySymbolFontName, itemInfo.MyTab.RemovedStyleUnderline); - } - PartsLeft.Add(mytab); - if (mytab.MyMacro != null) PartsLeft.Add(mytab.MyMacro); - } - } - else if (itemInfo.IsSupInfoPart) // if it was an empty tab - it may have been a caution/note - { - mytab = GetSupInfoTab(cb, itemInfo, yoff, mytab, doSectTab, XOffset); - PartsLeft.Add(mytab); - } - // if this is the High Level RNO step (MyTopRNO) and we are numbering the RNO, adjust the xoffset to start the tab - // at the x location rather than starting the text at the x location: - AdjustWidth(itemInfo, maxRNO, formatInfo, mytab); - bool adjustAgain = ((itemInfo.MyTab != null && itemInfo.MyTab.Position == 0) || (itemInfo.MyPrevious != null && itemInfo.MyPrevious.FormatStepData != null && itemInfo.MyPrevious.FormatStepData.TabData.IsTransition)) ? true : false; - if (!itemInfo.IsSection && itemInfo.FormatStepData.NumberHighLevel && itemInfo.IsRNOPart && (MyTopRNO == null || itemInfo.ItemID == MyTopRNO.MyItemInfo.ItemID)) - { - // adjust the x-offset of the RNO to include the tab. - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthSameAsHighParent)// && !itemInfo.MyParent.IsHigh) - { - vlnParagraph hls = GetHighLevelParagraph(); - float RnoOffset1 = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); - float offset = hls.Width + RnoOffset1 + hls.XOffset; - vlnTab tb = hls.MyTab; - //offset += tb.Width; - if (MyTopRNO == null) - Width -= (float)itemInfo.ActiveFormat.MyStepSectionLayoutData.SingleColumnRNOIndent; - offset -= Width; - float inc = offset - XOffset; - if (mytab != null) - mytab.XOffset += inc;// +(itemInfo.MyParent.IsHigh ? 6.8f : 0); - XOffset += inc; - adjustAgain = false; - } - else if (itemInfo.FormatStepData.AdjHighLevelTab != null && itemInfo.ColumnMode > 0) - // For Farley (only plant format to use AdjHighLevelTab), determine the xoffset based on - // where the right edge of the text is. Their RNO's are numbered with parent numbering - // so the calculations for determining the xoffset backs up from the right edge. - { - float rightTextEdge = this.MyHighLevelParagraph.XOffset + this.MyHighLevelParagraph.Width; - int colRx = int.Parse(formatInfo.MyStepSectionLayoutData.ColRTable.Split(",".ToCharArray())[itemInfo.ColumnMode]); - rightTextEdge += (colRx + (itemInfo.FormatStepData.AdjHighLevelTab ?? 0)); - float diff = rightTextEdge - (XOffset + Width); - if (mytab != null) mytab.XOffset += diff; - XOffset += diff; - adjustAgain = false; - } - else if (mytab != null) - { - float adjusttab = (itemInfo.MyParent.IsHigh) ? itemInfo.FormatStepData.AdjHighLevelTab ?? 0 : 0; - mytab.XOffset += (mytab.Width + adjusttab); - XOffset = mytab.XOffset + mytab.Width; - if (adjusttab != 0) Width += (mytab.Width); - } - } - if (adjustAgain) - { - AdjustXOffsetForTab(itemInfo, maxRNO, formatInfo, mytab, xMetaAdj); - // Used in Ginna's Attachment format. - // if the Note/Caution is off of a sub-step, then adjust the width so that the Caution/Note text box does not extend past the HLS text box - if (itemInfo.IsCautionOrNotePart && maxRNO == 0 && (itemInfo.ActiveSection != null && itemInfo.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.LimitCautionNoteWidthToHLS)) // C2018-003 fixed use of getting the active section - { - float wMax = MyHighLevelParagraph.Width + MyHighLevelParagraph.XOffset - XOffset; - if (wMax < Width && (Width + XOffset > MyItemInfo.MyDocStyle.Layout.PageWidth)) Width = wMax; - } - } - - if (itemInfo.IsSection && MyParent == null && itemInfo.MyDocStyle.SupplementalInformation && MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge) - { - _SupInfoSection = new vlnParagraph(this, cb, itemInfo, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRightParent, false, pp); - MyPromsPrinter.SupInfoPdfPageCount = -1; - } - // For Calvert Alarms: if within the CONDITION/RESPONSE table, indent by 1 character. - // Sequential substeps are ok because of the tab string, but items without a tab & other step - // types were writing over the CONDITION/RESPONSE vertical table line. This code uses - // 7.2 for the character size to match 16bit output. - if (itemInfo.IsStep && !itemInfo.IsSequential && !itemInfo.IsCaution && !itemInfo.IsNote && MyParent.HasCalvertMacro) - { - XOffset += 7.2f; - if (mytab != null) mytab.XOffset += 7.2f; - } - if ((itemInfo.IsCaution || (itemInfo.IsNote && !itemInfo.IsFootnote)) && (itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) - { - if (itemInfo.IsInRNO) - { - XOffset = MyTopRNO.MyTab != null ? MyTopRNO.MyTab.XOffset : MyTopRNO.XOffset; - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - 10; - } - else - { - XOffset = MyHighLevelParagraph.MyTab.XOffset; - Width = MyHighLevelParagraph.MyTab.Width + MyHighLevelParagraph.Width - 6; // make width 1/2 char smaller so it doesn't touch line - } - } - if (UseTemplateWidthOrXOff(itemInfo)) - { - float txoff = GetWidthOrStartFromTemplate(itemInfo, itemInfo.ActiveFormat, false); - if (txoff > 0) XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + txoff; // GetWidthOrStartFromTemplate(itemInfo, itemInfo.ActiveFormat, false); - } - if (itemInfo.MyHeader != null && itemInfo.MyHeader.Text != null && !doSectTab) - yoff += SetHeader(this, cb, itemInfo, formatInfo); - else if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.SeparateBox && itemInfo.FirstSibling.MyHeader != null && itemInfo.FirstSibling.MyHeader.Text != null) - yoff += SetHeader(this, cb, itemInfo.FirstSibling, formatInfo); - float yoffLeft = yoff; - if (ChildrenAbove != null) - ChildrenAbove.StepDesignator = null; //reset StepDesignator - if (DoSubs && itemInfo.Cautions != null && (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || itemInfo.Cautions[0].FormatStepData.Type != "Caution1") && !(itemInfo.IsCaution || itemInfo.IsNote)) - { - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format) - { - // For deviations, the Cautions are always in the same place. - // Fix for Catawba E-1 deviation for step 10. Has note/caution off of a paragraph instead of HLS - float xoffDev = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - if (loadChildren) yoffLeft = ChildrenLeft.Add(cb, itemInfo.Cautions, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); - } - else - { - if (yoffRightParent > yoff && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) != E_DocStructStyle.DoubleBoxHLS)) yoff = yoffRightParent; - if (loadChildren) yoff = ChildrenAbove.Add(cb, itemInfo.Cautions, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); - } - } - if (DoSubs && itemInfo.Notes != null && !(itemInfo.IsCaution || itemInfo.IsNote)) - { - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format) - { - // For deviations, the Cautions are always in the same place. - // Fix for Catawba E-1 deviation for step 10. Has note/caution off of a paragraph instead of HLS - float xoffDev = (float)itemInfo.MyDocStyle.Layout.LeftMargin + 6 + (float)(itemInfo.ActiveFormat.MyStepSectionLayoutData.WidT); - if (loadChildren) yoffLeft = Math.Max(yoffLeft, ChildrenLeft.Add(cb, itemInfo.Notes, xoffDev, yoff, yoff, rnoLevel, maxRNO, formatInfo)); - } - else - { - // Notes/Cautions span the page. If the right (RNO) column is below current yoff, use the - // yoff from this. Without this, an overlap of text between the note and the bottom of the - // RNO was occurring for FNP - Unit 2/AOP, AOP-4.0. - if (yoffRightParent > yoff && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) != E_DocStructStyle.DoubleBoxHLS)) yoff = yoffRightParent; - if (loadChildren) - { - float yoffadj = 0; - if (itemInfo.IsTable && MyFlexGrid.BorderStyle == C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None && !MyFlexGrid.TopRowHasBorder()) - yoffadj = SixLinesPerInch; // adjust the yoffset if the note is off of a borderless table - yoff = ChildrenAbove.Add(cb, itemInfo.Notes, xoff, yoff + yoffadj, yoff + yoffadj, rnoLevel, maxRNO, formatInfo) - yoffadj; - } - } - } - if (itemInfo is StepInfo && ((itemInfo as StepInfo).MyConfig as StepConfig).Step_PreferredPagebreak) HasPrefPageBreak = true; - // The following adds supplemental information items to the SupInfoSection list off of the section level paragraph for printing - // of the sup info pdf. The SupInfoSection list is just a flat list of all supplemental information within the section. - if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && loadChildren && itemInfo.SupInfos != null) - { - SupInfoSection.ChildrenBelow.Add(cb, itemInfo.SupInfos, XOffset, 0, 0, rnoLevel, maxRNO, formatInfo); - } - - // Without the following, BGE had gaps in y-direction if the AER/RNO both had cautions/notes. - // The only time this needs done is if caution/notes are printed in separate columns in dual - // column mode (used the DoubleBoxHLS BGE flag for this - if another plant needs this, make it - // a more generic flag). - if (itemInfo.IsRNOPart && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) && - rnoLevel == maxRNO && ChildrenAbove.Count > 0 && MyParent.ChildrenAbove.Count > 0) - { - float yDeltaRno = yoff - yOffOrig; - float yDeltaAer = SixLinesPerInch + yOffOrig - MyParent.ChildrenAbove[0].YTopMost; - if (yDeltaRno > yDeltaAer) - { - foreach (vlnParagraph chlda in MyParent.ChildrenAbove) - { - chlda.AdjustYOffset(yDeltaAer - yDeltaRno); - } - foreach (vlnParagraph chld in ChildrenAbove) - chld.AdjustYOffset(yDeltaAer); - yoff -= yDeltaAer; - } - else - { - foreach (vlnParagraph chld in ChildrenAbove) - chld.AdjustYOffset(yDeltaRno); - yoff -= yDeltaRno; - } - } - // Comanche Peak uses CAUTION2 type to enter a Step Designator, which is placed to the left of the step number. - // The Step Designator information is saved during the processing of the Cautions (ChildrenAbove) - // defined in the vlnParagraphs class (of which ChildrenAbove is defined) - if (ChildrenAbove.StepDesignator != null) - { - string pref = ChildrenAbove.StepDesignator; - float colOvrd = (float)(ChildrenAbove.StepDesignatorColumn ?? 0); - float xPref = (colOvrd > 0) ? colOvrd : mytab.XOffset - (pref.Length * (72 / (float)_MyItemInfo.FormatStepData.Font.CPI)); - PartsLeft.Add(new vlnText(cb, this, pref, pref, xPref, yoff, ChildrenAbove.StepDesignatorFont)); - ChildrenAbove.StepDesignator = null; - ChildrenAbove.StepDesignatorColumn = null; - } - DoAnnotationPrintableText(cb, itemInfo, yoff); // Look in annotation type to see if annotation has text that should be printed (like a step designator) - - // if this is a hls with a box, adjust the starting y location for the hls. this is done here - // in case this hls had a boxed caution and/or note before it. Also, this code is here rather - // than in the vlnparagraphs.add code because the yoff in that code will position the box, but - // this code positions the hls (in y direction), without this, the hls starts on the box line. - int bxIndx = itemInfo.IsSection ? 0 : itemInfo.FormatStepData.StepLayoutData.STBoxindex ?? 0; - if (itemInfo.IsHigh && bxIndx > 0) - { - int boxLnAdjust = itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox ? 1 : 2; - yoff += (boxLnAdjust * SixLinesPerInch); // this yoff is where the BOX starts (boxLnAdjust was added for WEP2) - } - - // If the format has that extra space should be put out before the step, then - // handle this by using the 'PartsAbove' structure. By using the parts above, the extra - // space above will be done regardless of where page breaks fall. - float addExtraSpace = 0; - if (MyItemInfo.FormatStepData != null && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing) - addExtraSpace = MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0; - //if (MyItemInfo.MyParent != null && MyItemInfo.MyParent.FormatStepData != null && - // MyItemInfo.MyParent.FormatStepData.Type != "TitleWithTextRight") - // addExtraSpace = (MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0; - if (MyItemInfo.MyParent != null && MyItemInfo.MyParent.FormatStepData != null) - addExtraSpace = (MyItemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight" || MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0; - // If a high level step, the 16bit code uses the value of the extra space - // from the high level step format regardless of what type of high level step it is: - // Added check for UseSTExtraRealValue, if set, we want to use what is set for the specific step type - // Added check for CustomSpacing (was also in 16-bit logic) - if (!MyItemInfo.ActiveFormat.MyStepSectionLayoutData.UseSTExtraRealValue && - !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing && - MyItemInfo.IsHigh) - addExtraSpace = MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[2].StepLayoutData.STExtraSpace ?? 0; - // If CustomSpacing flag is true - // then use the STExtraSpace from the step type called "Default" (index number 25) - //if (YOffset != 0 && MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.CustomSpacing) - if (YOffset != 0 && MyItemInfo.IsSection && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing) - addExtraSpace = (float)MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[25].StepLayoutData.STExtraSpace; - if (YOffset != 0 && MyItemInfo.FormatStepData != null && - MyItemInfo.MyPrevious == null && MyItemInfo.FormatStepData.ThreeBlanksAbove && (!MyItemInfo.IsNote || MyItemInfo.MyParent.Cautions == null)) - addExtraSpace = 24; // already has one blank line above, added two more - //if (YOffset != 0 && MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace > 0) - // addExtraSpace = (float)MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace; - // if this plant has the AlwaysUseExtraLines and there are notes/cautions above the hls, don't add in the - // extra space: - if (itemInfo.IsHigh && (itemInfo.Cautions != null || itemInfo.Notes != null)) - { - if ((itemInfo.Cautions != null && itemInfo.Cautions[0].FormatStepData.AlwaysUseExtraLines) || (itemInfo.Notes != null && itemInfo.Notes[0].FormatStepData.AlwaysUseExtraLines)) - addExtraSpace = 0; - // F2021-038: SHE/SHEA format - Less space after boxes - if (itemInfo.Cautions != null && itemInfo.Cautions[itemInfo.Cautions.Count - 1].FormatStepData.NoYBxAdjust) - addExtraSpace = 0; - if (itemInfo.Notes != null && itemInfo.Notes[itemInfo.Notes.Count - 1].FormatStepData.NoYBxAdjust) - addExtraSpace = 0; - } - // F2021-038: SHE/SHEA format - Less space after boxes. The following is for when a HLS has an RNO that has Cautions/Notes - if (itemInfo.IsHigh && itemInfo.RNOs != null) - { - if (itemInfo.RNOs[0].Notes != null && itemInfo.RNOs[0].Notes[0].FormatStepData.NoYBxAdjust) - addExtraSpace = 0; - if (itemInfo.RNOs[0].Cautions != null && itemInfo.RNOs[0].Cautions[0].FormatStepData.NoYBxAdjust) - addExtraSpace = 0; - } - if (addExtraSpace > 0 && MyItemInfo.FormatStepData != null) - { - // We need to strip out the underline style from the font before putting out - // the extra line. - VE_Font vf = MyItemInfo.FormatStepData.Font; - E_Style sty = (E_Style)vf.Style; - if ((sty & E_Style.Underline) != 0) - sty ^= E_Style.Underline; - vf = new VE_Font(vf.Family, (int)vf.Size, sty, (float)vf.CPI); - this.PartsAbove.Add(new vlnText(cb, this, " ", " ", 72, yoff, vf)); - } - - yoff += addExtraSpace; - - YTop = yoff; - YOffset = yoff; - if (mytab != null && mytab.SeparateBullet) - { - string identB = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.IdentB; - vlnText myBullet = new vlnText(cb, this, identB, identB, XOffset - 12, YOffset, MyItemInfo.FormatStepData.TabData.Bullet.Font); - myBullet.Rtf = myBullet.Rtf.Replace("\u25CF", @"\f1\u9679?\f0 "); - PartsLeft.Add(myBullet); - } - if (itemInfo.MyTab != null && itemInfo.MyTab.AsteriskOffset != 0) - { - - // the '-24' in x-direction & '+4' in y-direction was used for the SHE format to get the continuous - // HLS's asterisk to match 16bit. The font size was set at 16 to make it match also: - VE_Font astFont = new VE_Font(MyItemInfo.FormatStepData.TabData.Font.Family, 16, E_Style.Bold, 10); - vlnText myAsterisk = new vlnText(cb, this, "*", "*", mytab.XOffset - 24, YOffset + 4, astFont); - PartsLeft.Add(myAsterisk); - } - if (itemInfo.IsRNOPart && rnoLevel > maxRNO) - { - // the DoubleSpace & SpaceDouble flags seem redundant. The 2nd line was added for foldout - // line spacing for IP2 foldouts (one example can be found in E-1) - if (!itemInfo.FormatStepData.SpaceDouble && itemInfo.MyParent.IsHigh) - { - // but it we are in single column mode, don't remove the blank line. (Wolf Creek Admin Instructions - wcn1) - if (itemInfo.ActiveSection != null && (itemInfo.ActiveSection as SectionInfo).SectionConfig.Section_ColumnMode != SectionConfig.SectionColumnMode.One) // C2018-003 fixed use of getting the active section - yoff = YOffset = yoff - SixLinesPerInch; - } - else if (itemInfo.FormatStepData.NoSpaceMultipleRNOs) yoff = YOffset = yoff - SixLinesPerInch; - if (itemInfo.FormatStepData.DoubleSpace && itemInfo.FormatStepData.SpaceDouble) yoff = YOffset = yoff + SixLinesPerInch; - } - AddMacros(itemInfo, mytab); - if (mytab != null) - { - mytab.YOffset = yoff; - if (mytab.MyMacro != null) mytab.MyMacro.YOffset = yoff; - } - // For background formats, HLS's or Caution or any Notes have tab on line and then text - // on line below (with space in between) - if (itemInfo.IsBackgroundStep() && itemInfo.MyTab != null && itemInfo.MyTab.AltPrintTab != null && itemInfo.MyTab.AltPrintTab.Trim() != "") - yoff = YOffset = yoff + (2 * SixLinesPerInch); - CheckOff co = itemInfo.GetCheckOffStep(); - float yForCheckoff = yoff; //0; - default checkoff row is same as FIRST line of text - // if dropCheckoff is true, then the checkoff is place on the same of row as the LAST line of text - bool dropCheckoff = itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.DropCheckOff - || (co != null && co.DropCheckOff); - if (itemInfo.MyContent.MyGrid != null) - { - vlnCells.DefaultFont = itemInfo.FormatStepData.Font.WindowsFont;// Set the default text font based upon the format - int profileDepth1 = ProfileTimer.Push(">>>> Before vlnParagraph.Grid"); - //Use Static MyFlexGrid - BWD INST2 - FlexGrid Errors - MyFlexGrid.LoadGrid(itemInfo); - MyGrid = new vlnTable(MyFlexGrid, cb); - Height = MyGrid.Height; - Width = MyGrid.Width; - // Adjust the XOffset before determining if the table will overlap the RNO column RHM 20150529 - CalculateXOffsetGridOrFigure(itemInfo, maxRNO, formatInfo); - - yoff = AdjustLocIfLongerRNO(itemInfo, yoff, yoffRightParent); - // if the table does not have a border, only move down one line: - float yoffForBorder = 2 * SixLinesPerInch; - if (MyFlexGrid.BorderStyle == C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None && !MyFlexGrid.TopRowHasBorder()) - yoffForBorder -= SixLinesPerInch; - //yForCheckoff = yoff + Height - SixLinesPerInch; - if (dropCheckoff) - yForCheckoff += Height - SixLinesPerInch; // place checkoff on last row of text - yoff += (Height + yoffForBorder); //(2 * SixLinesPerInch)); - yoff = (float)Math.Ceiling(yoff); - ProfileTimer.Pop(profileDepth1); - } - else if (itemInfo.IsRtfRaw) - { - CalculateXOffsetGridOrFigure(itemInfo, maxRNO, formatInfo); - YOffset = yoff; - yoff += Height * .6f; // .6 is used as a scale factor in RtfRawAt (rtf2pdf). Use it here too for moving down page after equation. - yoff = (float)Math.Ceiling(yoff); - yoff += AdjustForBlankLines(); - } - else if (itemInfo.IsFigure) // if a figure we've got to determine the size: - { - int profileDepth2 = ProfileTimer.Push(">>>> Before vlnParagraph.Figure"); - string erMsg = null; - if (itemInfo.MyContent.Text != null) // ro image - { - if (itemInfo.MyContent.Text != "") // also check for text, there is an RO image then: - { - ProcedureInfo proc = itemInfo.MyProcedure; - DocVersionInfo dvi = proc.MyDocVersion; - ROFstInfo rofst = dvi.DocVersionAssociations[0].MyROFst; - //rofst.docVer = dvi; - ROFSTLookup lookup = rofst.GetROFSTLookup(dvi); - string linkInfoText = itemInfo.MyContent.Text.Replace(@"\v ", ""); - Match m = Regex.Match(linkInfoText, @"(.*)[#]Link:([A-Za-z]*):(.*)"); - string val = null; - if (m.Length > 0) // if m.lengh is zero, then no match was found - no RO was entered in the figure substep - { - if (m.Groups.Count < 4) - { - //erMsg = "RO was not found during data migration."; - // added newlines in the RO number (shown in figure substep type with figure RO) - // if we are here, then there is no RO link information, use this number to find the RO image to print - val = string.Format("{0}\n{1}\n{2}\n{3}", - linkInfoText.Substring(0, linkInfoText.Length - 16), - linkInfoText.Substring(linkInfoText.Length - 16, 8), - linkInfoText.Substring(linkInfoText.Length - 8, 4), - linkInfoText.Substring(linkInfoText.Length - 4, 4)); - val = val.Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); // replace dash and backslash symbols with dash and backslash characters - } - else - { - string[] subs = m.Groups[3].Value.Split(" ".ToCharArray()); - // B2022-088: Find Doc Ro button not working in Word Sections - val = lookup.GetRoChild(subs[1]).value; - if (val == null || val == "?") val = lookup.GetRoChild(subs[1].Substring(0, 12)).value; - if (val == "?") - { - erMsg = string.Format("Referenced Object does not exist."); - _MyLog.WarnFormat("\r\nMissing Referenced Object {0} in {1}", subs[1], itemInfo.ShortPath); - yoff += 2 * SixLinesPerInch; - } - } - } - GC.Collect(); // memory garbage collection (Regex memory bug) - if (val != null && val != "?") - { - string[] vals = val.Split("\n".ToCharArray()); - Width = Int32.Parse(vals[3], System.Globalization.NumberStyles.AllowHexSpecifier) * MyItemInfo.FormatStepData.Font.CharsToTwips; - int lines = Int32.Parse(vals[2], System.Globalization.NumberStyles.AllowHexSpecifier); - // Check that the Height of figure isn't too big to fit on the page, if it is - // set the Height to the printable part of page - Height of the HLS and an extra line - // for between HLS & figure. - float h1 = lines * SixLinesPerInch; - float h2 = RoughSizeOfPage - MyParent.Height - SixLinesPerInch; - Height = Math.Min(h1, h2); - if (h1 > h2) - { - Width *= (h2 / h1); - } - StepInfo si = (StepInfo)MyItemInfo; - StepConfig sc = new StepConfig(si.MyContent.Config); - if (sc != null && sc.Step_ImageWidth != 0) - { - Width = sc.Step_ImageWidth; - Height = sc.Step_ImageHeight; - } - yoff = AdjustLocIfLongerRNO(itemInfo, yoff, yoffRightParent); - if (dropCheckoff) - yForCheckoff += Height - SixLinesPerInch; // place checkoff on last row of text - bool noborder = MyItemInfo.FormatStepData.Type.ToUpper().Contains("BORDERLESS"); - yoff += (Height + ((noborder ? 1 : 2) * SixLinesPerInch)); // RHM 20120925 - Eliminate extra space after Figure } - try - { - ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); - if (roImage != null) - ImageText = val; - else - { - roImage = rofst.GetROImageByFilename(vals[0], MyItemInfo);// need code to go and get an ROImaage if it exists - if (roImage == null) - erMsg = string.Format("Image {0} does not exist.", vals[0]); - else - ImageText = val; - } - } - catch (Exception ex) - { - erMsg = string.Format("Image {0} does not exist, error = {1}.", vals[0], ex.Message); - } - } - if (erMsg != null) Rtf = GetRtf(erMsg, itemInfo.ActiveFormat.PlantFormat.FormatData.Font); - } - CalculateXOffsetGridOrFigure(itemInfo, maxRNO, formatInfo); - } - else - { - // figure - ImageText = "figure"; - } - if (ImageText == null && erMsg == null) - { - ImageText = "figure"; - ImageConfig ic = new ImageConfig(MyItemInfo.MyContent.MyImage); - // B2016-277: add a try catch in case of there being 'bad' data in the text field for an image/figure - try - { - byte[] idata = (ic != null && ic.Image_DataSize > 0) ? ROImageInfo.Decompress(MyItemInfo.MyContent.MyImage.Data, ic.Image_DataSize) : MyItemInfo.MyContent.MyImage.Data; - MemoryStream ms = new MemoryStream(idata); - System.Drawing.Image img = System.Drawing.Image.FromStream(ms); - Width = img.Width; - Height = img.Height; - if (ic != null && ic.Image_Height != 0) - { - Width = ic.Image_Width; - Height = ic.Image_Height; - - // B2022-041: extra whitespace after resized image. Make same adjustment here that gets made in ParagrphToPdf - // B2023-040: WCN pagination changed for And steps with large image after - add format flag for - // Barakah - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.AdjustLargeImage) - { - float mult = 1.0F; - if (Width > (vlnParagraph.wMax - 12)) mult = (vlnParagraph.wMax - 24) / Width; - if (Height > (vlnParagraph.hMax - 36)) mult = Math.Min(mult, (vlnParagraph.hMax - 36) / Height); - if (mult < 1.0F) - { - Width = Width * mult; - Height = Height * mult; - } - } - } - yoff = AdjustLocIfLongerRNO(itemInfo, yoff, yoffRightParent); - bool noborder = MyItemInfo.FormatStepData.Type.ToUpper().Contains("BORDERLESS"); - yoff += (Height + SixLinesPerInch); // B2019-059 only one extra line after a figure (does not matter if it has a border or not) - CalculateXOffsetGridOrFigure(itemInfo, maxRNO, formatInfo); - } - catch (Exception ex) - { - _MyLog.WarnFormat("Bad figure content data: item = {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); - } - } - ProfileTimer.Pop(profileDepth2); - } - else - { - // For Calvert Alarms, the 'CONDITION/RESPONSE' portion uses a macro to print - // the CONDITION and RESPONSE text with the lines around it. Add the macro here because - // there is no tab for the step & that's where the macro is usually stored: - if (HasCalvertMacro) PartsLeft.Add(new vlnMacro(xoff - 12f, yoff, "H4")); - - //if (itemInfo.IsSection) - // Rtf = GetRtf(itemInfo, prefix, " (Continued)"); - //else - // BuildRtf(); // not necessary, RTF is lazyloaded - if (itemInfo.IsStep && itemInfo.MyHLS != null && itemInfo.MyHLS.FormatStepData.UseSmartTemplate) - { - if (itemInfo.FormatStepData.StepLayoutData.AlignWithParentTab - || (itemInfo.Steps != null && itemInfo.Steps.Count > 0 && itemInfo.Steps[0].FormatStepData.StepLayoutData.AlignWithParentTab)) - { - int stplevl = TheStepLevel(itemInfo); - if (stplevl >= 0 && MyItemInfo.MyHLS.FormatStepData.VertPos[stplevl] > 0) - { - if (MyItemInfo.FormatStepData.StepPrintData.Justify == "Center") - { - string[] vertPos = MyItemInfo.MyHLS.FormatStepData.VertPos.Split(",".ToCharArray()); - float hloc = (float.Parse(vertPos[stplevl]) + ((float.Parse(vertPos[stplevl + 1]) - float.Parse(vertPos[stplevl])) / 2)); - Chunk chk = (Chunk)IParagraph.Chunks[0]; - hloc = hloc - (chk.GetWidthPoint() / 2); - XOffset = hloc + (float)itemInfo.MyDocStyle.Layout.LeftMargin; - } - else - XOffset = float.Parse(MyItemInfo.MyHLS.FormatStepData.VertPos.Split(",".ToCharArray())[stplevl]) + (float)itemInfo.MyDocStyle.Layout.LeftMargin; - } - } - } - if (itemInfo.IsTablePart) // Not for grid, this is for old-style tables. - { - Width = GetTableWidth(cb, IParagraph, MyItemInfo.MyDocStyle.Layout.PageWidth); - CalculateXOffsetGridOrFigure(itemInfo, maxRNO, formatInfo); - } - else - if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.StepPrintData != null && (itemInfo.IsHigh || (!itemInfo.IsHigh && itemInfo.MyContent.Type != itemInfo.MyParent.MyContent.Type))) XOffset += (float)(itemInfo.FormatStepData.StepPrintData.PosAdjust ?? 0); - - // point beach wpb subformats 20 & 22 were printing some text past right margin. Limit the width to the right margin, i.e. pagewid - if (itemInfo.ActiveFormat.MyStepSectionPrintData.LimitWidToPageWid) - { - float lim = (MyTab == null ? (XOffset - (float)itemInfo.MyDocStyle.Layout.LeftMargin) : MyTab.XOffset + MyTab.Width) + Width; - float docStyleLim = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin; - - if (lim > docStyleLim) - { - WidthNoLimit = Width; // Use this width to calculate childrens' width, without this, code was making children to narrow! - Width = docStyleLim - (MyTab == null ? (XOffset - (float)itemInfo.MyDocStyle.Layout.LeftMargin) : MyTab.XOffset + MyTab.Width); - } - } - if (itemInfo.IsSection && ShowSectionTitles - && !MyItemInfo.MyDocStyle.CancelSectTitle) - { - if (MyItemInfo.MyDocStyle.Layout.SectionMacro != null) - { - string macro = GetMacroName(MyItemInfo.MyDocStyle.Layout.SectionMacro); - PartsAbove.Add(new vlnMacro(xoff, yoff, macro)); - yoff += SixLinesPerInch; - YOffset = yoff; - } - } - - // if this step has a prefix but it's not checklist... do a partsleft for prefix - if (_MyItemInfo.IsStep && !_MyItemInfo.FormatStepData.UseSmartTemplate) - { - if (_MyItemInfo.FormatStepData.Prefix != null && _MyItemInfo.FormatStepData.Prefix != "") - { - string pref = _MyItemInfo.FormatStepData.Prefix.Replace("{Backspace}", ""); - float xPref = XOffset - (pref.Length * (72 / (float)_MyItemInfo.FormatStepData.Font.CPI)); - E_Style es = (E_Style)_MyItemInfo.FormatStepData.Font.Style & E_Style.Bold; - VE_Font tmpFont = new VE_Font(_MyItemInfo.FormatStepData.Font.Family, (int)_MyItemInfo.FormatStepData.Font.Size, es, (float)_MyItemInfo.FormatStepData.Font.CPI); - PartsLeft.Add(new vlnText(cb, this, pref, pref, xPref, yoff, tmpFont)); - } - } - // If checklists, the substeps are printed in a row, need to keep track of the 'longest' in - // y direction (bottommost) across the row. - if (itemInfo.IsStep && itemInfo.MyHLS != null && (itemInfo.MyHLS.FormatStepData.UseSmartTemplate || (itemInfo.MyHLS.FormatStepData.UseOldTemplate && itemInfo.MyDocStyle.ComponentList)) && (TheStepLevel(itemInfo) >= 0)) - savCheckListBottomMost = yoff + Height + (itemInfo.MyHLS.FormatStepData.UseSmartTemplate ? SixLinesPerInch : 0); - - // The following was added for BGE valve lists, this format (BGEVLV) used caution1 as - // a subheader within the valve list. To print correctly, a line needs to be added to - // where the bottom of this (subheader) is located and XOffset is set to the leftmargin. - if (itemInfo.IsStep && itemInfo.MyHLS != null && !itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.IsCaution1 && itemInfo.MyHLS.FormatStepData.UseOldTemplate && itemInfo.MyDocStyle.ComponentList) - { - savCheckListBottomMost += SixLinesPerInch; - yoff += Height; - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - } - - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.IsCaution1) savCheckListBottomMost = yoff + Height; - // Get Y offset for regular steps, or if section title is output or if not within row (not last column of - // text) for wcn checklist, i.e. - if ((!itemInfo.IsStepSection && itemInfo.MyHLS != null && !itemInfo.MyHLS.FormatStepData.UseSmartTemplate) // regular step - || (ShowSectionTitles - && !MyItemInfo.MyDocStyle.CancelSectTitle - && !MyItemInfo.MyDocStyle.SpecialStepsFoldout) - // In Checklist: I don't have children or if I have children the first child doesn't alignwithparent. - || (!itemInfo.IsStepSection && itemInfo.MyHLS != null && itemInfo.MyHLS.FormatStepData.UseSmartTemplate - && ((itemInfo.Steps == null || itemInfo.Steps.Count == 0) - || !itemInfo.Steps[0].FormatStepData.StepLayoutData.AlignWithParentTab)) - || ((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.IsSection)) // B2016-222 check if is a caution or note and parent is a section - { - bool doprint = !(MyPageHelper.DidHLSText && MyItemInfo.ItemID == MyPageHelper.HasHLSTextId); - if (MyItemInfo.IsSection) - { - SectionConfig sch = MyItemInfo.MyConfig as SectionConfig; - if (sch != null && sch.Section_PrintHdr != "Y") doprint = false; - } - //C2025-021 Add logic to PROMS to support a special High Level Step type that is not printed. - if (doprint && !UseTemplateKeepOnCurLine(itemInfo) && !itemInfo.IsType("InvisibleHigh")) - { - float tyoff = yoff; - if (itemInfo.Steps != null) - { - if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.Type == "TitleWithTextRight") - if (loadChildren) tyoff = ChildrenRight.Add(cb, itemInfo.Steps, XOffset + 72, yoff, yoff, rnoLevel, maxRNO, formatInfo); - } - yoff += Height; - yoff = Math.Max(yoff, tyoff); - yoff += AdjustForBlankLines(); - if (dropCheckoff) - yForCheckoff += Height - SixLinesPerInch; // place checkoff on last row of text - } - } - } - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - // For Calvert Alarms, the row has formatting that makes this template item have a header & box - // (CONDITION/RESPONSE), header with box around it is defined in genmac whereas the lines around - // substeps are drawn in pagehelper. Adjust some yoffsets around this box. - // Need to: - // 1) move the text down a bit for top line (1.5f * SixLinesPerInch) - // 2) move the substep down 2 lines (2 * SixLinesPerInch) for bottom of box - // and space before substep - // 3) if the previous item had this condition, add space for the - // line below. - if (HasCalvertMacro) - { - YOffset += (1.5f * vlnPrintObject.SixLinesPerInch); - yoff += (2 * vlnPrintObject.SixLinesPerInch); - } - if (itemInfo.MyPrevious != null && itemInfo.MyPrevious.TemplateIndex > 0) - { - if (itemInfo.MyPrevious.ActiveFormat.PlantFormat.FormatData.Templates[itemInfo.MyPrevious.TemplateIndex].hmacro > 0) - { - YOffset += (3 * vlnPrintObject.SixLinesPerInch); - yoff += (3 * vlnPrintObject.SixLinesPerInch); - } - } - } - if (co != null && !MyItemInfo.IsInSupInfo) // C2018-002: don't print checkboxes on supplemental infromation pages. - { - // if this item's content is empty, and the flag is set to 'notonempty', don't print out the - // checkoff - this was added for shearon harris: - if (!(co.NotOnEmpty && itemInfo.MyContent.Text.Replace(@"\u160?", " ").TrimEnd() == "")) - { - float xloc_co = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - // if the format has 'SkipSpaces', look at the tab, and back up the macros to the number of - // spaces in the tab. - if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.SkipSpaces) - { - if (mytab != null) - xloc_co = mytab.XOffset; - else - xloc_co = XOffset; //there's no tab - put checkoff at step's xoff. Macro should back up from step's x. - } - else - { - if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.XLocation != 0) - xloc_co += (float)formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.XLocation; - else if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.RelXLocation != 0) - { - float relX = (float)formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.RelXLocation; - xloc_co = XOffset + (relX > 0 ? Width : 0) + relX; - } - } - - // CheckOffXtraLines was introduced for the additional lines needed for the longer signoffs - // for VCBA (&WST1), for F2016-061. - float checkOffNumberOfLines = (co.CheckOffNumberOfLines ?? 0); - if (checkOffNumberOfLines > 0) - { - yForCheckoff += (2 * SixLinesPerInch); - PartsRight.Add(new vlnMacro(xloc_co, yForCheckoff/* + xtraCheckOffLines */, co.Macro)); - yoff += ((checkOffNumberOfLines *= SixLinesPerInch) + (2 * SixLinesPerInch)); - } - else - { - // if xtraCheckOffLines is a negative number, start the checkoff on the same line - // as text and adjust the y-offset after the checkoff by the amount of the absolute - // value of xtraCheckOffLines. - // if xtraCheckOffLines is a positive number, start the checkoff xtraCheckOffLines - 1 - // down from the text and adjust the y-offset after the checkoff by the amount - // of xtraCheckOffLines. - float xtraCheckOffLines = (co.CheckOffXtraLines ?? 0); - if (xtraCheckOffLines < 0) - { - xtraCheckOffLines = -xtraCheckOffLines; - xtraCheckOffLines *= SixLinesPerInch; - PartsRight.Add(new vlnMacro(xloc_co, yForCheckoff/* + xtraCheckOffLines */, co.Macro)); - yoff += xtraCheckOffLines; - } - else - { - xtraCheckOffLines *= SixLinesPerInch; - xtraCheckOffLines -= ((xtraCheckOffLines > 0) ? SixLinesPerInch : 0); - PartsRight.Add(new vlnMacro(xloc_co, yForCheckoff + xtraCheckOffLines, co.Macro)); - yoff += (xtraCheckOffLines != 0) ? xtraCheckOffLines + SixLinesPerInch : 0; - } - } - } - } - // for WCNTRN, do the responsibility: - if (formatInfo.PlantFormat.FormatData.PrintData.WCNTraining) DoResponsibility(cb, YOffset); - float yOffRight = yoff; - float RnoOffset = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); - if (DoSubs && rnoLevel < maxRNO && itemInfo.RNOs != null) - { - if (loadChildren) yOffRight = ChildrenRight.Add(cb, itemInfo.RNOs, XOffset + RnoOffset, YTop, YTop, rnoLevel + 1, maxRNO, formatInfo); - if (ChildrenRight[0].ChildrenAbove.Count > 0) - { - float adj = ChildrenRight[0].YOffset - YOffset; - YOffset = ChildrenRight[0].YOffset; - yoff += adj; - if (MyTab != null) MyTab.YOffset = ChildrenRight[0].YOffset; - if (PartsRight.Count > 0) PartsRight[0].YOffset = ChildrenRight[0].YOffset; - //B2020-160 use YTopMost instead of Yoffset if there are children above. - // Get the minimun value between the AER and RNO YtopMost. - // example. Calvert AOP-7E/XIII/Step A5.h Unit 2 Approved set - //B2021-027 use YOffset if there isn't any children above (AER). - // example: Catawba Unit 1 AP’s; AP/1/A/5500/050; Enclosure 8 step 1 - if (ChildrenAbove.Count == 0) - YTopMost = ChildrenRight[0].ChildrenAbove[0].YOffset; //B2021-027 - else - YTopMost = Math.Min(ChildrenAbove[0].YTopMost, ChildrenRight[0].ChildrenAbove[0].YTopMost); //B2020-160 - } - } - // if this hls had a box drawn, add a line for substeps. - if (itemInfo.IsHigh && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) yoff += vlnPrintObject.SixLinesPerInch; - - // Need code to determine if the table will overlap the Right Column if it does then - // use YOffRight rather than yoff - if (DoSubs && itemInfo.Tables != null) - { - bool aerTableOrFigure = itemInfo.Tables[0].FormatStepData.Type.Contains("AER"); - // get the first table & see if it is borderless. If borderless, 16bit code removed a - // line (yoffset) before printing it: - float yoffadj = 0; - if (itemInfo.Tables[0].IsTable) - { - MyFlexGrid.LoadGrid(itemInfo.Tables[0]); - // B2018-077 added check for caution and note parts in which case we want the blank line - fix for Calvert OI-27B 6.11.B and 6.12.B - if (MyFlexGrid.BorderStyle == C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None && !MyFlexGrid.TopRowHasBorder() && !MyItemInfo.IsCautionOrNotePart) - yoffadj = -SixLinesPerInch; - } - // B2023-008: when an equation is off a paragraph sub-step in single column mode, extra lines were added so - // when in single column mode & the substep has an equation (rtfraw), then don't reset yoffright to yverybottom - bool rtfRawInSingleCol = (itemInfo.ColumnMode == ((int)VEPROMS.CSLA.Library.SectionConfig.SectionColumnMode.One-1)) && (itemInfo.Tables != null && itemInfo.Tables.Count > 0 && itemInfo.Tables[0].IsRtfRaw); - if (yOffRight < yoffRightParent) yOffRight = yoffRightParent; - // find the very bottom Yoffset (don't do this is in single column mode for cautions/notes: B2016-261) - vlnParagraph parentPar = parent; - if (!rtfRawInSingleCol && (!((MyItemInfo.IsCaution || MyItemInfo.IsNote) && itemInfo.RNOLevel == 0))) - { - while (parentPar != null && parentPar.MyItemInfo.IsStep) - { - float vb = parentPar.YVeryBottom; - if (yOffRight < vb) yOffRight = vb; - parentPar = parentPar.MyParent; - } - } - bool rightLonger = yOffRight > yoff; - if (!aerTableOrFigure && itemInfo.RNOLevel == 0) // Centered Table - { - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.Tables, XOffset, rightLonger ? yOffRight : yoff + yoffadj, yOffRight + yoffadj, rnoLevel, maxRNO, formatInfo); - } - else // AER or RNO Table - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.Tables, XOffset, yoff + yoffadj, yOffRight + yoffadj, rnoLevel, maxRNO, formatInfo); - } - yOffRight = Math.Max(yOffRight, yoffLeft); - // Look for the meta section case where the 'Editable' flag is set to 'N', which means that - // these steps should not be printed: - bool printsteps = true; - if (itemInfo.Steps != null && itemInfo.IsSection && itemInfo.Sections != null && itemInfo.Sections.Count > 0) - { - SectionConfig sc = itemInfo.MyConfig as SectionConfig; - if (sc != null && sc.SubSection_Edit != "Y") printsteps = false; - } - bool rnoBefore = false; - bool rnoAfter = false; - if (rnoLevel >= maxRNO && itemInfo.RNOs != null && - !itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.WolfCreekBackgroundFormat && - !itemInfo.RNOs[0].FormatStepData.InPageList) - { - if ((itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString ?? "") != "" || - (itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString ?? "") != "") - rnoBefore = true; - else - rnoAfter = true; - } - if (rnoBefore) - { - if ((itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString ?? "") != "") - { - string tmpSepStr = itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString; - float tmpSepLen = itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString.Length; - float xsep = MyHighLevelParagraph.PartsLeft.Count > 0 ? MyHighLevelParagraph.PartsLeft[0].XOffset : MyHighLevelParagraph.XOffset; - vlnRNOSeparator mySep = new vlnRNOSeparator(this, cb, tmpSepStr, xsep, yoff, itemInfo.ActiveFormat, false); - PartsBelow.Add(mySep); - yoff += mySep.Height;// +SixLinesPerInch; - } - if (loadChildren) yoff = ChildrenBelow.Add(cb, itemInfo.RNOs, MyTab.XOffset, yoff, yoff, rnoLevel + 1, maxRNO, formatInfo); - if ((itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString ?? "") != "") - { - string tmpSepStr = itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString; - float tmpSepLen = itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString.Length; - float xsep = MyHighLevelParagraph.PartsLeft.Count > 0 ? MyHighLevelParagraph.PartsLeft[0].XOffset : MyHighLevelParagraph.XOffset; - vlnRNOSeparator mySep = new vlnRNOSeparator(this, cb, tmpSepStr, xsep, yoff, itemInfo.ActiveFormat, false); - PartsBelow.Add(mySep); - yoff += mySep.Height;// +SixLinesPerInch; - } - } - // For Calvert Alarms, 'Caution1' was used to implement the Annunciator Window, i.e. is printed - // below the HLS and close to the right margin. - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.Cautions != null && itemInfo.Cautions[0].FormatStepData.Type == "Caution1") - { - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.Cautions, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); - savCheckListBottomMost = yoff; - } - if (DoSubs && itemInfo.Steps != null && printsteps) - { - if (itemInfo.FormatStepData == null || itemInfo.FormatStepData.Type != "TitleWithTextRight") - if (rnoBefore) - { - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.Steps, MyTab.XOffset, yoff, yOffRight, rnoLevel, maxRNO, formatInfo); - } - else - if (loadChildren) yoff = ChildrenBelow.Add(cb, itemInfo.Steps, XOffset, yoff, yOffRight, rnoLevel, maxRNO, formatInfo); - } - if (itemInfo.Sections != null) - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.Sections, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo, pp); - if (itemInfo.Procedures != null) - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.Procedures, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); - // Don't add the RNO to print if doing backgrounds. That piece of data is part of the pagelist item. - if (rnoAfter) - if (loadChildren) - yoff = ChildrenBelow.Add(cb, itemInfo.RNOs, XOffset, yoff, yoff, rnoLevel + 1, maxRNO, formatInfo); - YBottomPagination = yoff;// B2019-111 Exclude Right for Pagination - yoff = Math.Max(yoff, yOffRight); - // TODO - use RNOSepAfterAER flag too: - string tmpRnoSepStr = formatInfo.MyStepSectionPrintData.RNOSepString; - float tmpRnoSepLen = formatInfo.MyStepSectionPrintData.RNOSepLineLength ?? 0; - if (rnoLevel < maxRNO && itemInfo.RNOs != null && (tmpRnoSepStr != null || tmpRnoSepLen != 0)) - { - vlnParagraph rno = ChildrenRight[0]; - vlnParagraph bottomChild = BottomChild; - float xsep = MyHighLevelParagraph.XOffset + RnoOffset; - - // ip3 has an rno separator and also has asterisk boxes around continous HLS. If - // the hls has RNOs off of it, then the rno separator line is outside of the box. If - // there are RNOs, but not off of HLS, then rno separator line is within the box (this is - // how 16bit proms did this). The following use of yadjSep and YBottomForBox handle that - float yadjSep = (MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex != null && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex >= 0 && - MyItemInfo.MyHLS.RNOs != null && MyItemInfo.MyHLS.RNOs.Count > 0) ? 2 * SixLinesPerInch : 0; - vlnRNOSeparator myRnoSep = new vlnRNOSeparator(this, cb, tmpRnoSepStr, xsep, yoff + yadjSep, formatInfo, bottomChild == null ? true : bottomChild.MyItemInfo.HasChangeBar); - // TODO: May need to handle more than one RNO column for RNO Separator - if ((rno.LastRNO.MyItemInfo.HasChangeBar == false && bottomChild != null && bottomChild.MyItemInfo.HasChangeBar) - || (bottomChild != null && bottomChild.YBottom > rno.LastRNO.YBottomMost)) - bottomChild.PartsBelow.Add(myRnoSep); - else - rno.LastRNO.PartsBelow.Add(myRnoSep); - MyHighLevelParagraph.YBottomForBox = 0; - if (yadjSep > 0) - { - MyHighLevelParagraph.YBottomForBox = yoff; // if hlrno, box before sep - YBottomMostAdjust = SixLinesPerInch; // added for IP3 pagination, the RNO separator is outside asterisk box - } - yoff += (myRnoSep.Height + SixLinesPerInch); - } - // if in WCNTRN (Wolf Creek Training), need to consider the ysize of the Responsibility text when setting - // YBottomMost, i.e. if the Responsibilty has more height (y-direction) compared to the actual step text, - // need to move down on page the height of the responsibility. - if (formatInfo.PlantFormat.FormatData.PrintData.WCNTraining && MyItemInfo.IsHigh) - { - if (PartsLeft.Count > 0 && PartsLeft[0] is vlnText) - { - foreach (vlnText vt in PartsLeft) - yoff = Math.Max(yoff, vt.YOffset + vt.Height); - } - } - YBottomMost = yoff; - - if ((MyItemInfo.IsHigh || MyItemInfo.IsCaution1) && MyItemInfo.MyDocStyle.LandscapePageList && MyItemInfo.MyDocStyle.ComponentList) - { - // put out line after step (for BGEVLV format) - float macroY = YBottomMost - (0.25f * SixLinesPerInch); - PartsLeft.Add(new vlnMacro((float)MyItemInfo.MyDocStyle.Layout.LeftMargin, macroY, "B9")); - } - - // For Checklist, the substeps are in rows of data. The YBottomMost is the bottom most for - // the row. - if (savCheckListBottomMost != 0) YBottomMost = Math.Max(savCheckListBottomMost, YBottomMost); - if (XOffsetCenter != null) XOffset = (float)XOffsetCenter; - ProfileTimer.Pop(profileDepth); - } - - private vlnTab GetSupInfoTab(PdfContentByte cb, ItemInfo itemInfo, float yoff, vlnTab mytab, bool doSectTab, float localXOffset) - { - string strmytab = null; - if (itemInfo.MyParent.IsHigh) - strmytab = itemInfo.MyTab.CleanText; - else if (itemInfo.MyParent.IsCaution) - strmytab = "Caution"; - else if (itemInfo.MyParent.IsNote) - strmytab = "Note"; - else - { - // B2018-022: use flag to determine whether to pre-pend the parent's tab as part of the supplemental info tab - // (if the procedure tab is long, such as in Farley, the tab overwrites text in the supplemental info pages) - strmytab = itemInfo.ActiveSection.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoIncludeParTab - ? ItemInfo.GetCombinedTab(itemInfo.MyParent, itemInfo.MyParent.MyParent.CombinedTab) - : itemInfo.MyTab.CleanText; - } - strmytab = strmytab.Trim(); - mytab = new vlnTab(cb, this, strmytab, strmytab, localXOffset, yoff, itemInfo.MyTab.MyFont, doSectTab, StepRTB.MySymbolFontName, itemInfo.MyTab.RemovedStyleUnderline); - return mytab; - } - private static VE_Font _AnnotationFont; - public static VE_Font AnnotationFont - { - get { return vlnParagraph._AnnotationFont; } - set { vlnParagraph._AnnotationFont = value; } - } - - // Check to see if the procedure has any printable text in the annotations - private bool? _CanDoPrintableText = null; - public bool CanDoPrintableText - { - get - { - if (_CanDoPrintableText == null) - { - _CanDoPrintableText = false; - AnnotationTypeInfoList atil = AnnotationTypeInfoList.Get(); - foreach (AnnotationTypeInfo ati in atil) - { - AnnotationTypeConfig atc = new AnnotationTypeConfig(ati.Config); - if (atc.PrintableText_XLocation != 0) - { - _CanDoPrintableText = true; - break; - } - } - } - return (bool)_CanDoPrintableText; - } - } - private void DoAnnotationPrintableText(PdfContentByte cb, ItemInfo itemInfo, float yoff) - { - // check to see if this procedure has any printable annotations. - // if it does not, then there is no need to spin through checking for the given itemInfo - if (!CanDoPrintableText) return; - - // if this step has an Annotation and it has config data to define location, parse out '[xx]' and print it at the location - // this was added for VC Summer (unit 2 & 3) but is available for any data that has defined the location in the config (from the folder properties - // at the top node - annotationtype tab. - if (itemInfo.ItemAnnotationCount > 0) - { - foreach (AnnotationInfo ai in itemInfo.ItemAnnotations) - { - // get the annotation type from the annotation, and see if it has a print location: - AnnotationTypeInfo at = ai.MyAnnotationType; - AnnotationTypeConfig atc = new AnnotationTypeConfig(at.Config); - if (atc.PrintableText_XLocation != 0) - { - int st = ai.SearchText.IndexOf("["); - int end = ai.SearchText.IndexOf("]"); - if (st != -1 && end != -1 && end > st) - { - string pref = ai.SearchText.Substring(st + 1, end - st - 1); // annotation - parse out [xx] - pref = Regex.Replace(pref, "{Up}", @"\u8593?", RegexOptions.IgnoreCase); - pref = Regex.Replace(pref, "{Down}", @"\u8595?", RegexOptions.IgnoreCase); - float xPref = atc.PrintableText_XLocation; - if (AnnotationFont == null) - AnnotationFont = new VE_Font(_MyItemInfo.FormatStepData.Font.Family, 6, (E_Style)_MyItemInfo.FormatStepData.Font.Style, 20F); - PartsLeft.Add(new vlnText(cb, this, pref, pref, xPref, yoff, AnnotationFont)); - break; - } - } - } - } - } - - private float AdjustLocIfLongerRNO(ItemInfo itemInfo, float yoff, float yoffRightParent) - { - if (!itemInfo.IsInRNO && yoffRightParent > yoff && itemInfo.FormatStepData.Type.Contains("AER")) - { - // is the width of this table going to cause the table to overlap the RNO - vlnParagraph parRno = FindParentRNO(); - float xMinRno = FindMinXOffsetRno(parRno); - if (XOffset + Width > xMinRno - 12) // 12 = 2 characters, so that tables don't almost touch & look like an overlap - { - if ((float)MyItemInfo.MyDocStyle.Layout.LeftMargin + Width > xMinRno) - { - yoff = yoffRightParent; - YOffset = yoff; - } - else - XOffset = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin; - } - } - return yoff; - } - private float FindMinXOffsetRno(vlnParagraph parRno) - { - // Find the minimum xoffset in the rno column that overlaps in the y direction with - // the table that is currently being processed. This is necessary in order to fix the - // case where the AER table overlaps an RNO table (or tab/text) - float xcur = 0; - // YOffset/Height is for the current table, check it against the rno's yoffset & height - // if aer & rno are within y range of each other - if (YOffset <= (parRno.YOffset + parRno.Height) && (YOffset + Height) >= parRno.YOffset) - { - xcur = parRno.XOffset; - if (parRno.MyTab != null) xcur = parRno.MyTab.XOffset; - } - // recursively look at steps in the rno column to get the smallest xoffset which will - // then be used to compare to table's xoffset/width to see if there is an overlap - if (parRno.ChildrenBelow != null) - { - foreach (vlnParagraph vp in parRno.ChildrenBelow) - { - // yoffset is past where the table is, so don't consider it: - if (vp.YOffset > (YOffset + Height)) return xcur; - - float xchild = FindMinXOffsetRno(vp); - if (xchild > 0 && (xcur == 0 || xchild < xcur)) - xcur = xchild; - } - } - return xcur; - } - private void DoResponsibility(PdfContentByte cb, float yoff) // WCNTRN's text in 1st column (saved in config for HLS) - { - StepConfig sc2 = MyItemInfo.MyConfig as StepConfig; - if (sc2 != null) - { - string resp = sc2.Step_Responsibility; - - if (resp != null && resp != "") // lines are separated by "\r\n" - { - resp = DelimitResponse((int)MyItemInfo.MyDocStyle.SectTop.MaxLen, resp); - if (!resp.EndsWith("\r\n")) resp = resp + "\r\n"; // parsing needs this. - int indx = resp.IndexOf("\r\n"); - int stindx = 0; - float y = yoff; - while (indx > -1) - { - string subresp = resp.Substring(stindx, indx - stindx); - float respWidth = subresp.Length * 6; - float ctr = (float)MyItemInfo.MyDocStyle.SectTop.Margin; - float respcntrX = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ctr - (respWidth / 2); - vlnText myResp = new vlnText(cb, this, subresp, subresp, respcntrX, y, MyItemInfo.FormatStepData.Font); - PartsLeft.Add(myResp); - y += SixLinesPerInch; - stindx = indx + 2; - indx = stindx < resp.Length ? resp.IndexOf("\r\n", stindx) : -1; - } - } - } - } - private string DelimitResponse(int maxLen, string responsStr) - { - // This code handles whether user enters \r\n to separate lines or not. The - // max width that a line can be in the Responsibility column is a format flag (passed in) - List results = new List(); - int width = 0; // keep track of current width of current 'line' while looking for space to break - int start = 0; // start of line (index into string 'text') - int lastspace = 0; // location of lastspace (index into string) - for (int indx = 0; indx < responsStr.Length; indx++) - { - if ((indx + 1) < responsStr.Length && responsStr.Substring(indx, 2) == "\r\n") - { - results.Add(responsStr.Substring(start, indx - start).Trim(" ".ToCharArray()) + "\r\n"); - start = indx + 2; - width = 0; - } - else - { - if (responsStr[indx] == ' ') lastspace = indx; - width++; - if (width > maxLen) - { - // what should be done if lastspace == 0 - // cannot find space char to split on, so break the word - bool spFound = true; - if (lastspace == 0) - { - lastspace = indx; - spFound = false; - } - results.Add(responsStr.Substring(start, lastspace - start).Trim(" ".ToCharArray()) + "\r\n"); - start = lastspace + (spFound ? 1 : 0); // increment start based on whether a space is found, i.e. if no space keep at 'indx' - // width either is equal to width of text after the last space, or is zero if at the maxlen of width: - width = (indx - lastspace - 1) > 0 ? indx - lastspace - 1 : 0; - lastspace = 0; - } - } - } - if (width > 0 || start < responsStr.Length) results.Add(responsStr.Substring(start).Trim(" ".ToCharArray())); - string retval = null; - foreach (string st in results) retval = retval + st; - return retval; - } - public override string Rtf - { - get - { - if (_Rtf == null) BuildRtf(); - return _Rtf; - } - set { _Rtf = value; } - } - private void BuildRtf() - { - int profileDepth = ProfileTimer.Push(">>>> BuildRtf"); - if (_Rtf == null) - { - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && MyItemInfo.IsCaution1 && - MyItemInfo.MyContent.Text.StartsWith(@"\u") && !MyItemInfo.MyContent.Text.StartsWith(@"\u160?")) - { - Rtf = GetRtf(MyItemInfo, " " + (Prefix ?? ""), Suffix); - PrefixSpecialCharacter = true; - } - else - { - Rtf = GetRtf(MyItemInfo, Prefix, Suffix); - } - // Need the following with some modifications for WCNCKL format: - if (Rtf.Contains("{Backspace}")) - { - XOffset -= 25; - Width += 24; - Rtf = Rtf.Replace("{Backspace}", ""); - } - } - Rtf = FixRTFToPrint(MyItemInfo, Rtf); - ProfileTimer.Pop(profileDepth); - } - // C2018-024 I in Arial font changed to I in TimesNewRoman - private static System.Drawing.Font _TNR; - // F2018-013 Changed to static and public so that it can be used with step identifiers for bullets - public static string FixRTFToPrint(ItemInfo myItemInfo, string rtf) - { - // Only do this if the text contains symbols. - if ((rtf.Contains("VESymbFix") || rtf.Contains(Volian.Base.Library.vlnFont.ProportionalSymbolFont))) // C2017-036 get best available proportional font for symbols - { - // bug fix: B2017-117 was getting an out of window handles error when doing a print all for Bryon - // add the using statment to free up window handle that is created doing a New RichTextBox() - using (System.Windows.Forms.RichTextBox rtb = new System.Windows.Forms.RichTextBox()) - { - rtb.Rtf = rtf.Replace(@"\\", ""); // rename backslash character to avoid RTF confusion - //string showRTF = rtf; - bool changed = false; - // C2018-024 I in Arial font changed to I in TimesNewRoman - if (myItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ChangeFontUpperCaseIinArial) - { - bool lastWasNumber = false; - for (int i = 0; i < rtb.TextLength - 1; i++) - { - rtb.Select(i, 2); - if (rtb.SelectionLength == 2) - { - if ((rtb.SelectedText == ".I") && rtb.SelectionFont.FontFamily.Name == "Arial") - { - if (_TNR == null) - _TNR = new System.Drawing.Font("Times New Roman", rtb.SelectionFont.Size, rtb.SelectionFont.Style); - if (lastWasNumber) - { - rtb.SelectionFont = _TNR; - changed = true; - lastWasNumber = false; - } - } - else - lastWasNumber = Regex.IsMatch(rtb.SelectedText, @"[0-9]\."); - } - } - } - // C2017-008 - WCN wants the box symbol to look like their checkoff/signoff box - // Check for a list of replacement character for symbols in the format file - // ReplaceSymbolChars lets you do one or more of the following with a symbol character: - // - change the point size - // - change the style - // - change the font family - // - change the symbol character - // - // below is taken from the BaseAll format file - is currently commentout and there for reference - // Wolf Creek (WCN) currently uses this to increase the size of the box symbol - // - // - // - // - // get the list of symbol replacements - FormatData fmtdata = (myItemInfo.ActiveFormat != null) ? myItemInfo.ActiveFormat.PlantFormat.FormatData : FormatInfo.PROMSBaseFormat.FormatData; - ReplaceSymbolCharList SymReplaceList = (fmtdata != null && fmtdata.SectData.ReplaceSymbolCharList != null) ? fmtdata.SectData.ReplaceSymbolCharList : null; - // Look at one character at a time - for (int i = 0; i < rtb.TextLength; i++) - { - rtb.Select(i, 1); - if ((rtb.SelectedRtf.Contains("VESymbFix") || rtb.SelectedRtf.Contains(Volian.Base.Library.vlnFont.ProportionalSymbolFont)) && rtb.SelectedText.Length > 0) // C2017-036 get best available proportional font for symbols - { - for (int j = 0; j < SymReplaceList.MaxIndex; j++) - { - ReplaceChar rc = SymReplaceList[j]; - if (rc.Unicode != null && (rc.Family != null || rc.Size != null || rc.Style != null)) - { - char rc_uchar = Convert.ToChar(Convert.ToInt32(rc.Unicode)); - if (rc_uchar == rtb.SelectedText[0]) - { - //use bolding underline italics from local font - System.Drawing.Font fnt = rtb.SelectionFont; - // follow through in fixing an Out of Window Handles bug, use new function to see if - // we can retrieve the font from a dictionary instead a doing a New and using another - // window handle B2017-117 - //System.Drawing.Font fntw = new System.Drawing.Font((rc.Family != null) ? rc.Family : fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); - System.Drawing.Font fntw = VE_Font.GetWinSysFont((rc.Family != null) ? rc.Family : fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); - rtb.SelectionFont = fntw; - if (rc.Replace != null) - { - char rc_RplChar = Convert.ToChar(Convert.ToInt32(rc.Replace)); - rtb.SelectedText = rc_RplChar.ToString(); - } - changed = true; - break; // break out of foreach loop since we changed the character - } - } - } - } - } - if (changed) - { - if (rtb.Rtf.EndsWith(" \\par\r\n}\r\n") && rtf.EndsWith(" }")) //B2018-060 rtb.RTF added extra new line characters and commands to the end. so remove it. - rtf = rtb.Rtf.Replace(" \\par\r\n}\r\n", " }"); - else - rtf = rtb.Rtf; - return rtf.Replace("", @"\\"); // put back the backslash character - } - } - } - return rtf; - } - - // for Calvert (BGE) alarms, some step text is kept on the same line as its parent. This - // is flagged by the -1 row in the template definition. - private bool KeepOnParentLine(ItemInfo itemInfo) - { - int tindx = itemInfo.TemplateIndex; - if (tindx < 0) return false; - if (itemInfo.ActiveFormat.PlantFormat.FormatData.Templates[tindx].row == -1) return true; - return false; - } - - private void AdjustYOffset(float yDelta) - { - YOffset -= yDelta; - foreach (vlnPrintObject vpo in PartsAbove) - vpo.YOffset -= yDelta; - foreach (vlnParagraph vp in ChildrenBelow) - vp.AdjustYOffset(yDelta); - } - - private void BuildPlacekeeper(vlnParagraph parent, ItemInfo itemInfo) - { - if (itemInfo is SectionInfo && (itemInfo as SectionInfo).SectionConfig.Section_Placekeeper.ToUpper() != "N") // if is a section type and the section is marked to create placekeeper - { - MyPlaceKeeper = new pkParagraph(this); - if (parent != null && parent.MyItemInfo.IsSection) - parent.MyPlaceKeeper = MyPlaceKeeper; - } - else if (parent != null && parent.MyPlaceKeeper != null && itemInfo is StepInfo)//InList(parent.MyItemInfo.ItemID, 513, 514, 519, 520, 525)) - { - StepConfig sc = itemInfo.MyConfig as StepConfig; - if (sc != null && sc.Step_Placekeeper.ToUpper() != "N") - { - if (itemInfo.IsCautionPart || itemInfo.IsNotePart) - MyPlaceKeeper = parent.MyPlaceKeeper.AddCautionsAndNotes(this); - else - MyPlaceKeeper = parent.MyPlaceKeeper.AddChild(this); - } - } - } - - private void BuildContinuousActionSummary(vlnParagraph parent, ItemInfo itemInfo) - { - if (itemInfo is SectionInfo) - { - MyContAct = new pkParagraph(this); - if (parent != null && parent.MyItemInfo.IsSection) - parent.MyContAct = MyContAct; - } - else if (itemInfo is StepInfo) - { - StepConfig sc = itemInfo.MyConfig as StepConfig; - if ((sc != null && sc.Step_CAS == "True") || ((sc == null || sc.Step_CAS == null) && itemInfo.IncludeOnContActSum)) - { - // save this step info for use on the Continuous Action Summary - vlnParagraph tparent = parent; - while (tparent != null && tparent.MyContAct == null) - tparent = tparent.MyParent; - if (parent.MyContAct != null) - { - if (itemInfo.IsCautionPart || itemInfo.IsNotePart) - MyContAct = parent.MyContAct.AddCautionsAndNotes(this); - else - MyContAct = parent.MyContAct.AddChild(this); - } - else - MyContAct = tparent.MyContAct.AddChild(this); - } - } - } - private void BuildTimeCriticalActionSummary(vlnParagraph parent, ItemInfo itemInfo) - { - if (itemInfo is SectionInfo) - { - MyTimeCriticalAction = new pkParagraph(this); - if (parent != null && parent.MyItemInfo.IsSection) - parent.MyTimeCriticalAction = MyTimeCriticalAction; - } - else if (itemInfo is StepInfo) - { - StepConfig sc = itemInfo.MyConfig as StepConfig; - if ((sc != null && sc.Step_TCAS == "True") || ((sc == null || sc.Step_TCAS == null) && itemInfo.IncludeOnTimeCriticalActionSum)) - { - // save this step info for use on the Continuous Action Summary - vlnParagraph tparent = parent; - while (tparent != null && tparent.MyTimeCriticalAction == null) - tparent = tparent.MyParent; - if (parent.MyTimeCriticalAction != null) - { - if (itemInfo.IsCautionPart || itemInfo.IsNotePart) - MyTimeCriticalAction = parent.MyTimeCriticalAction.AddCautionsAndNotes(this); - else - MyTimeCriticalAction = parent.MyTimeCriticalAction.AddChild(this); - } - else - MyTimeCriticalAction = tparent.MyTimeCriticalAction.AddChild(this); - } - } - } - - private vlnParagraph FindParentRNO() - { - if (ChildrenRight != null && ChildrenRight.Count > 0) return ChildrenRight[0]; - return MyParent.FindParentRNO(); - } - - private string GetMacroName(string str) - { - int mindx = str.IndexOf(@"{!"); - string macro = str.Substring(mindx + 2, str.Length - 3); - return macro; - } - - private int TheStepLevel(ItemInfo itemInfo) - { - if (itemInfo.IsHigh) return -1; - int lev = 0; - ItemInfo ii = itemInfo; - while (!ii.MyParent.IsHigh) - { - lev++; - ii = ii.MyParent; - } - return lev; - } - - private string SectionHasCheckOffHeader(ItemInfo itemInfo, ref VE_Font font) - { - // If the passed in itemInfo is not a section, get it's parent section. This may be a subsection, so - // it will be found here, versus using 'MyActiveSection'. - while (!itemInfo.IsSection) - { - itemInfo = itemInfo.MyParent; - } - // See if this section has a checkoffheading index - this value, if set is stored in the config field. - // -1 flags no entries in the format's CheckOffHeaderList & 0 flags the first - // entry which is always '{NO HEADING}'. So only continue if it's greater than 0. - //SectionInfo si = SectionInfo.Get(itemInfo.ItemID); // sometimes the itemInfo isn't a section info - SectionInfo si = itemInfo.GetSectionInfo(); // sometimes the itemInfo isn't a section info - int sindx = si.CheckOffHeadingIndex(); - - // If there is a checkoff header for this section, see if this section has subsections. - // If this has a header but no subsections, put out the header. - // Else if this section has a header AND subsections, don't put it out... - // the subsection's checkoff header will be processed (or lack there of). - bool doCheckoffHeader = sindx > 0 && (itemInfo.Sections == null || itemInfo.Sections.Count == 0); - - // if doing it, then grab the string from the format.... CHECK if this works for subsection, it is - // getting ActiveSection which may return the top section, not subsections. - if (doCheckoffHeader && itemInfo.SectionCheckOffHeader != "") - { - font = itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList[sindx].Font; - return itemInfo.SectionCheckOffHeader; - } - return null; - } - - private void DoCheckOffHeader(PdfContentByte cb, ItemInfo itemInfo, float yLocation, float yTopMargin, float yPageStart) - { - // CheckOffHeaders are handled in two different ways: - // 1) Where the pagelist item puts them - this is at the 'top' of the page, when the current section on the - // page has a checkoff header defined. Support for this is here AND in the VlnSvgPageHelper pagelist code. - // 2) If a continuous section, and it doesn't start at 'top' of the page, then the checkoff header is - // printed on the same line as the continuous section. Support for this is here, the check off header is added - // to the 'PartRight' off of the section's VlnParagraph. - - // First see if there is any checkoff data in the format file and that there - // is a pagelist item for the checkoff header. - int maxindx = itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffList.MaxIndexNoInherit; - if (maxindx <= 0) return; - if (MyPageHelper.PageListCheckOffHeader == null) return; - - VE_Font font = null; - ItemInfo mySectionInfo = itemInfo.ActiveSection; // C2018-003 fixed use of getting the active section - ItemInfo mySubSectionInfo = itemInfo; - - // If the passed in itemInfo is not a section, get it's parent section. This may be a subsection, so - // it will be found here, versus using 'MyActiveSection' which is the topmost section. The passed in - // item may be a regular step, i.e. if a page break had occurred. - if (!itemInfo.IsSection) - { - while (!mySubSectionInfo.IsSection) - { - mySubSectionInfo = mySubSectionInfo.MyParent; - } - } - else - mySubSectionInfo = (mySectionInfo == null || mySectionInfo.Sections == null) ? null : mySectionInfo.Sections[0]; - - if (mySectionInfo == mySubSectionInfo) mySubSectionInfo = null; - - // The following duplicates the 16bit logic. The 16bit logic only put out a header if: - // there is no subsection and section has a header (from config); - // OR there is a subsection and the first subsection has a header. - // For locating the header in 16bit logic: - // If no subsections, output with section - // If subsections and continuous section, put out on same line as subsection. (done here) - // If subsections and starts at top of page, (on top of page, use pagelist code in VlnSvgPageHelper) - - // Get SectionInfos to access specific section config items... - //SectionInfo si = SectionInfo.Get(mySectionInfo.ItemID); - SectionInfo si = (mySectionInfo != null)? mySectionInfo.GetSectionInfo() : null; - int sindx = si.CheckOffHeadingIndex(); - //SectionInfo subi = mySubSectionInfo == null ? null : SectionInfo.Get(mySubSectionInfo.ItemID); - SectionInfo subi = (mySubSectionInfo == null)? null : mySubSectionInfo.GetSectionInfo(); - int subindx = (subi == null)? -1 : subi.CheckOffHeadingIndex(); - - // if there is no subsections & the main section doesn't use a header OR - // if there is a subsection, & it does not use a header... Return. - if ((subi == null && sindx < 1) || (subi != null && subindx < 1)) return; - - // figure out location now: - // if step, it uses pagelist logic to locate it (this is a page break condition). - // if continuous, put out with subsection if there is one, otherwise section. - // otherwise, use pagelist logic. - bool usePageListCOHdr = false; - - // B2022-129: Barakah - Adjust the INITIAL header location, i.e. make it a pagelist item - if (itemInfo.IsStep || itemInfo.MyDocStyle.AdjSectTitleLoc) - { - usePageListCOHdr = true; - } - // This checks to see if the section is starting at the top of the page. - // If it is, then we want to use PageList to print the checkoff/sighoff header - // else the checkoff/signoff header will be printed across from the section title where ever it is on the page (i.e. section pagination set to continuous) - else if (subi == null) //no subsection - { - // B2021-106 added check if the section has a note or caution - if ((yPageStart - YOffset) == yTopMargin || mySectionInfo.HasCautionOrNote) usePageListCOHdr = true; - } - else // there is a sub-section - { - // B2021-106 added check if the section has a note or caution - if (mySectionInfo == itemInfo && ((yPageStart - YOffset) == yTopMargin) || mySectionInfo.HasCautionOrNote) usePageListCOHdr = true; - if (!usePageListCOHdr && mySubSectionInfo != itemInfo) return; - } - - // grab the string from the format, depending on whether it should get it from the section or subsection. - string cohead = (mySubSectionInfo != null) ? mySubSectionInfo.SectionCheckOffHeader : (mySectionInfo != null)? mySectionInfo.SectionCheckOffHeader : null; - if (cohead == "" || cohead == null) return; - - // PageListCheckOffHeader is an svgtext - but really we only need the x/y location for this (pagelist support) - // The actual text is from the checkoff header selection in the section config. - if (cohead != MyPageHelper.PageListLastCheckOffHeader) - { - font = mySectionInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList[sindx].Font; - float chkOffY = CalculateYLocation(YTop, yTopMargin); - if (MyPageHelper.YMultiplier != 1) - { - chkOffY = -1 + yTopMargin - (yTopMargin - yLocation) * MyPageHelper.YMultiplier; - if (Rtf != null) - IParagraph.Leading = _SevenLinesPerInch; - } - if (!usePageListCOHdr) - { - vlnText myCOHead = new vlnText(cb, this, cohead, cohead, MyPageHelper.PageListCheckOffHeader.X.Value + (float)MyItemInfo.MyDocStyle.Layout.LeftMargin, chkOffY, font); - PartsRight.Add(myCOHead); - } - else - MyPageHelper.PageListTopCheckOffHeader = cohead; - MyPageHelper.PageListLastCheckOffHeader = cohead; - } - } - internal vlnParagraph BottomChild - { - get - { - float bottomChildYBottomText = YBottomText; - vlnParagraph bottomChild = this; - foreach (vlnParagraph child in ChildrenRight) - { - vlnParagraph grandChild = child.BottomChild; - if (grandChild != null && grandChild.YBottomText > bottomChildYBottomText) bottomChild = grandChild; - if (grandChild != null && grandChild.YBottomText == bottomChildYBottomText && grandChild.MyItemInfo.HasChangeBar) bottomChild = grandChild; - bottomChildYBottomText = bottomChild.YBottomText; - } - foreach (vlnParagraph child in ChildrenBelow) - { - vlnParagraph grandChild = child.BottomChild; - if (grandChild != null && grandChild.YBottomText > bottomChildYBottomText) bottomChild = grandChild; - if (grandChild != null && grandChild.YBottomText == bottomChildYBottomText && grandChild.MyItemInfo.HasChangeBar) bottomChild = grandChild; - bottomChildYBottomText = bottomChild.YBottomText; - } - return bottomChild; - } - } - private void CalculateXOffsetGridOrFigure(ItemInfo itemInfo, int maxRNO, FormatInfo formatInfo) - { - float scale = itemInfo.IsRtfRaw ? 0.6f : 1.0f; - bool aerTableOrFigure = itemInfo.FormatStepData.Type.Contains("AER"); - vlnParagraph hls1 = MyParent; - if (!formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && !itemInfo.IsInSupInfo) - while (hls1.MyParent != null && !hls1.MyItemInfo.IsHigh) hls1 = hls1.MyParent; - else if (itemInfo.IsInSupInfo) - while (hls1.MyParent != null && !hls1.MyItemInfo.IsSupInfoPart) hls1 = hls1.MyParent; - float colR = float.Parse(formatInfo.MyStepSectionLayoutData.ColRTable.Split(",".ToCharArray())[itemInfo.ColumnMode]); - float xLowerLimit = (aerTableOrFigure && hls1.PartsLeft != null && hls1.PartsLeft.Count > 0) ? hls1.PartsLeft[0].XOffset : hls1.XOffset; - float xUpperLimit = 0; - float pageWidth = ((float)itemInfo.ActiveSection.MyDocStyle.Layout.PageWidth); // C2018-003 fixed use of getting the active section - float leftMargin = ((float)itemInfo.ActiveSection.MyDocStyle.Layout.LeftMargin); // C2018-003 fixed use of getting the active section - if (itemInfo.IsInRNO) - // if in rno column, the upper limit is width of the page (right margin). Subtract off size of a character - xUpperLimit = pageWidth - (72 / (float)MyItemInfo.FormatStepData.Font.CPI); - else - // in the following calculation, the hls width (hls1.Width) == rno column width, so xUpperLimit is - // the around the right margin, i.e. 'hls xoffset' + 'location of rno (colR) * columnmode' + 'width of rno' - xUpperLimit = hls1.XOffset + hls1.Width + hls1.CheckOffWidth + colR * itemInfo.ColumnMode; - - // If a table is within the alarm section and its parent is a template item is single column - // adjust the xoffset so that the table is centered around center of page - bool ctrCalvertAlarmTbl = false; - if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - ctrCalvertAlarmTbl = MyItemInfo.IsWithInSingleColumnTemplate(); - // B2019-049 added check for table being in a Caution or Note - if so, use the single column setting for the format variable TableCenterPos - float TableCenterPos = float.Parse(formatInfo.MyStepSectionLayoutData.TableCenterPos.Split(",".ToCharArray())[(itemInfo.IsInCautionOrNote)?0:itemInfo.ColumnMode]); - if (ctrCalvertAlarmTbl || formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TieTabToLevel) - XOffset = leftMargin + (pageWidth - leftMargin - (scale * Width)) / 2; - else - { - if (!aerTableOrFigure && itemInfo.RNOLevel == 0 && TableCenterPos != 0) // Only adjust TableCenterPos for Non-RNO Cenetered Tables - { - XOffset = TableCenterPos; - XOffset = XOffset - (this.Width / 2) + (float)itemInfo.MyDocStyle.Layout.LeftMargin; - } - else if (itemInfo.RNOLevel != 0) // RNO - XOffset = MyParent.XOffset + (MyParent.Width / 2) - ((scale * Width) / 2); - else if (aerTableOrFigure) - { - // if in the BGE alarm format and the hls is a Window (upper right corner when it prints), use the parent of the table - // to print in aer column (B2014-105) - if (MyItemInfo.IsInCalvertConditionResponse) - XOffset = hls1.XOffset + hls1.Width / 2 - Width / 2; - else - XOffset = MyHighLevelParagraph.XOffset + MyHighLevelParagraph.Width / 2 - Width / 2; - } - else // Centered Table or Figure - { - // Determine center of hls - XOffset = hls1.XOffset + hls1.Width / 2; - // Determine left edge of the table by subtracting 1/2 of its width. - XOffset -= Width / 2; - // Add in 1/2 of the width of all RNO columns - XOffset += (colR * itemInfo.ColumnMode) / 2; - - if (!aerTableOrFigure && !MyItemInfo.IsRtfRaw) - { - // 05/14/12 - 16bit code adjusts the center depending upon the CPI of the table font. - // Start with XOffset of table, then calculate the XOffset adjusted for the table font, - // based on the default CPI of 12. Adjust the XOffset by the difference of these - // two numbers. - XOffset -= (XOffset - (XOffset * (float)MyItemInfo.FormatStepData.Font.CPI / 12)); - } - XOffset -= 12; // This makes the 16bit & 32bit align very closely. - // if outside of the page margins then center within the page margins - float xOffset2 = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - float xWidth2 = (float)itemInfo.MyDocStyle.Layout.PageWidth; - if (XOffset + Width > xOffset2 + xWidth2) - XOffset = xOffset2 / 2 + xWidth2 / 2 - Width / 2; - - } - // 05/14/12 - The PosAdjust is a format flag from 16bit. For WCN2, it appears that this amount equals - // the amount of difference from a 10 CPI to a 12 CPI font. See comment above. - float posAdjust = (float)(itemInfo.FormatStepData.StepPrintData.PosAdjust ?? 0); - if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.StepPrintData != null && - posAdjust > 0) - { - if (Width < hls1.Width - posAdjust) - XOffset += posAdjust; - else if (Width < hls1.Width) - XOffset = hls1.XOffset + hls1.Width - Width; // align with the right edge of hls text - } - } - if (itemInfo.MyDocStyle.Layout.CenterToStepThenPage) - { - if (Width > hls1.Width) - { - float XOffsetPage = leftMargin + ((pageWidth - leftMargin) - Width) / 2; - float fraction = (Width - hls1.Width) / ((pageWidth - leftMargin) - hls1.Width); - float XOffsetNew = (1 - fraction) * XOffset + fraction * XOffsetPage; - _MyLog.WarnFormat("***XOffsetAdjust-CenterToStepThenPage*** ItemID, XOffset, XOffsetPage, XOffsetNew ={0},{1},{2},{3}", itemInfo.ItemID, XOffset, XOffsetPage, XOffsetNew); - XOffset = XOffsetNew; - } - } - else - { - // if the XOffset < High Level Step Text's XOffset , then align with the High Level Step Text' - // B2020-161 - needed to substract the checkoff width when deterniming the XOffset - // fixes centered tables in Calvert Unit 2 STP O-90-2 step 6.3.A - if (XOffset < xLowerLimit && Width < (xUpperLimit - xLowerLimit - hls1.CheckOffWidth)) - XOffset = xLowerLimit; - - // if the right margin exceeds the right edge of the rightmost RNO, then adjust right edge to match. - // In lines below, the 12 was used for Wolf Creek 2 column format, the pagewidth goes beyond the right border line so that - // the tables, figures & equations were beyond the border. -12 takes it enough so that if boxed, it won't print out of border - // We know this is not ideal. - if (MyItemInfo.IsRtfRaw && (XOffset + (scale * Width) > xUpperLimit - 12)) - XOffset = xUpperLimit - (scale * Width) - 12; - if (!MyItemInfo.IsRtfRaw && XOffset + Width > xUpperLimit) - XOffset = xUpperLimit - Width; - // because of the above, if it pushes beyond the left margin, use the left margin. - if (XOffset < (float)itemInfo.MyDocStyle.Layout.LeftMargin) - XOffset = XOffsetBox = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - } - } - private float AdjustForBlankLines() - { - if (MyParent != null && MyParent.MyItemInfo.FormatStepData != null && MyParent.MyItemInfo.FormatStepData.Type == "TitleWithTextRight") return 0; - // F2022-121 added SpecialStepsFoldoutKeepWhiteSpace flag to allow for all of the other special foldout formatting, but - // not compress the page - if (MyItemInfo.MyDocStyle.SpecialStepsFoldout && !MyItemInfo.MyDocStyle.SpecialStepsFoldoutKeepWhiteSpace) return 0; - if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.Prefix != null && MyItemInfo.FormatStepData.Suffix != null && MyItemInfo.FormatStepData.UseSmartTemplate) return 0; - int everyNLines = MyItemInfo.FormatStepData == null ? 1 : MyItemInfo.FormatStepData.StepLayoutData.EveryNLines ?? 1; - if (everyNLines == -99) return 0; - if (everyNLines == -1) return -SixLinesPerInch; - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || - (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert && MyItemInfo.IsStep && MyItemInfo.FormatStepData.StepLayoutData.STBoxindex != null)) - { - if ((MyItemInfo.IsCaution || MyItemInfo.IsNote || MyItemInfo.MyParent.IsCaution || MyItemInfo.MyParent.IsNote) && !MyItemInfo.FormatStepData.SpaceIn - && (MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) - && (MyItemInfo.NextItem == null || MyItemInfo.MyContent.Type != MyItemInfo.NextItem.MyContent.Type)) - { - // C2014-009: Don't add another blank line - print the calvert Condition/Response RNO Caution/Notes without it. - if (!(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && MyItemInfo.IsInRNO)) - return 0; - } - //B2020-117 for multiple Calvert Condition/Response Cautions,Note, and Warnings, do add an extra blank line - // between them - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && - MyItemInfo.IsInRNO && (MyItemInfo.IsCaution || MyItemInfo.IsNote) && - MyItemInfo != MyItemInfo.LastSibling) - return 0; - if (everyNLines == 99 && MyItemInfo.NextItem == null) - { - if (MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0 && MyItemInfo.Steps[0].MyContent.Type == MyItemInfo.MyContent.Type) return 0; - if (MyItemInfo.MyParent.NextItem != null && MyItemInfo.MyParent.NextItem.MyContent.Type == MyItemInfo.MyContent.Type) return 0; - } - } - // B2015-005: if there isn't a blank line after this step && it has children, see if there shouldn't be - // a blank line, i.e. if the first substep child's type is the same as this. - if (!MyItemInfo.IsHigh && everyNLines == 99 && MyItemInfo.NextItem == null && MyItemInfo.HasChildren) - { - ItemInfo chld = MyItemInfo.FirstChild(E_FromType.Step); - if (chld != null && chld.MyContent.Type == MyItemInfo.MyContent.Type) return 0; - } - // F2021-033: No blank line between hls and its first substep: - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoBlankHlsAndFirstSub && MyItemInfo.IsHigh) - { - // F2021-060 Do not remove blank line between step and Caution, Note or Warning below it (Caution, Note, Warning are off 1st sub step) - if (MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0 && !MyItemInfo.Steps[0].HasCautionOrNote) return 0; - } - // F2021-025: Barakah single column no blank line between last Note/Caution/Warning text and bottom line of box - // C2021-049: Barakah no blank line between last Note/Caution/Warning text, include sub-step text by using 'IsInCautionOrNote' - // B2022-017: Barakah within note/caution, if note has substeps, there should be a blank line between note & 1st substep - // B2022-027: Barakah blank line not printing after list within another list. Rewrote code for all of these issues so that - // code looks up parents to see if they have next before returning a 0 (no blank line) - // B2022-042: double Caution followed by Critical Step missing bullet - // F2022-010: substeps in multiple notes, cautions, warning print differently - if (MyItemInfo.IsInCautionOrNote) - { - float adjLastBlankLineInNoteCautionWarning = 0; - // Get the box information for the Note, Caution, or Warning - ItemInfo tifo = (MyItemInfo.IsCaution || MyItemInfo.IsNote) ? MyItemInfo : MyItemInfo.ParentNoteOrCaution; - int typ = ((int)tifo.MyContent.Type) % 10000; - int? bxIndx = tifo.ActiveFormat.PlantFormat.FormatData.StepDataList[typ].StepLayoutData.STBoxindex; - if (bxIndx != null) - { - Box bx = tifo.ActiveFormat.PlantFormat.FormatData.BoxList[(int)bxIndx]; - // F2024-078 save the adjustment of the last blank line - this value will be added to the SixLinesPerInch value (a blank line) - adjLastBlankLineInNoteCautionWarning = (float)(bx.AdjLastBlnkLn ?? 0); - } - //} - // if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoBlankLastNoteCautionWarn && (MyItemInfo.IsInCautionOrNote)) - // F2024-078 added check for adjustment of the last blank line in the Note/Caution box - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoBlankLastNoteCautionWarn || adjLastBlankLineInNoteCautionWarning != 0) - { - if ((MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) && (MyItemInfo.NextItem == null)) // there are no sub-steps, see if any parents have next - { - ItemInfo par = MyItemInfo.MyParent; - while (par.IsInCautionOrNote) // while in the caution or note, see if there is anything below this item - { - // if there is no next item, or content types are different, go up to see if the parent has any next item. If note - // keep going up tree, otherwise there is a next so don't return 0, i.e. continue on with code to determine - // whether there is a blank line - if ((par.NextItem == null) || (par.MyContent.Type != par.NextItem.MyContent.Type)) par = par.MyParent; - else break; - } - if (!par.IsInCautionOrNote || (par != null && par.MyContent.Type != par.NextItem.MyContent.Type)) - { - if (adjLastBlankLineInNoteCautionWarning != 0) - return SixLinesPerInch + adjLastBlankLineInNoteCautionWarning; // F2024-078 adjust the size of the last blank line of Note/Caution box - else - return 0; // no blank line after last text line of Note/Caution/Warning - } - } - if ((MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) && MyItemInfo.NextItem != null && MyItemInfo.MyContent.Type != MyItemInfo.NextItem.MyContent.Type) - { - if (adjLastBlankLineInNoteCautionWarning != 0) - return SixLinesPerInch + adjLastBlankLineInNoteCautionWarning; - else - return 0; // no blank line after last text line of Note/Caution/Warning - } - } - } - if (MyItemInfo.Ordinal % everyNLines == 0 || MyItemInfo.NextItem == null) return SixLinesPerInch; - // B2022-003: BNPP Alarms (BNPPalr) - incorrect line spacing for substeps off substeps. Added a format flag so as not to affect other plants. - if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.StepPrintData != null && MyItemInfo.FormatStepData.StepPrintData.BlankAfterSubWithSub && MyItemInfo.NextItem != null && MyItemInfo.HasChildren && MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0) return SixLinesPerInch; - - // If the next table child is a figure, equation or a visio drawing add a blank line - if (MyItemInfo.Tables != null && MyItemInfo.Tables.Count > 0 && MyItemInfo.Tables[0].MyContent.MyGrid == null) return SixLinesPerInch; - // Pagination issue to be used with yEndsWithBlankLine in Pagination code, but not checked in yet. - //if (MyItemInfo.Ordinal % everyNLines == 0 || MyItemInfo.NextItem == null) return SixLinesPerInch; - return 0; - } - private void AddMacros(ItemInfo itemInfo, vlnTab mytab) - { - float y = YOffset; - float x = mytab == null ? XOffset : mytab.XOffset + mytab.TabOffset; - List myMacros = itemInfo.MyMacros; - if (myMacros != null) - { - int colMode = (MyItemInfo.ActiveSection != null)? MyItemInfo.ActiveSection.ColumnMode : 0; // C2018-003 fixed use of getting the active section - foreach (Macro myMacro in myMacros) - { - // if the format has the 'LocWithXOff' locate the macro along with the tab's offset. - // however, if the tab is more than 2 characters long, adjust so that it aligns with the - // last two characters, not the first 2. - string tabText = mytab == null ? null : mytab.Text.Trim(" .".ToCharArray()); - int tablen = (tabText == null) ? 0 : (tabText.Length <= 2) ? 0 : tabText.Length - 2; - if (myMacro.LocWithXOff ?? false) x = mytab == null ? XOffset : ((float)mytab.XOffset + (tablen * (float)mytab.MyFont.CharsToTwips)); - if (colMode == 0 && myMacro.SingleColMacroDef != null && myMacro.SingleColMacroDef.Length > 0) - { - float macroXOffset = myMacro.MacroXOffSet ?? 0; - float widthAdj = myMacro.SingleColWidthAdjust ?? 0; // set as negative number in format - float rightTextEdge = (itemInfo.IsHigh) ? XOffset + Width + mytab.XOffset : this.MyHighLevelParagraph.XOffset + this.MyHighLevelParagraph.Width; - x = (macroXOffset > 0) ? macroXOffset : rightTextEdge; - if (rightTextEdge > x) - Width += widthAdj; - PartsRight.Add(new vlnMacro(x, y, myMacro.SingleColMacroDef)); - } - else - PartsLeft.Add(new vlnMacro(x, y, myMacro.MacroDef)); - } - } - } - // HLP Change bar flags in format file: - // Locations: With Text, Outside Box, AER on Left RNO on Right, To The Left of Text - // Text: Date & Change ID, Revision Number, Change ID, None, Custom (use input data) - // Flag AERChgBarMsgRNOChgBarNoMsg and AERMsgRNONoMsg are NOT Used in 16-bit. - private string cbMess = null; - private vlnChangeBar DoChangeBar(PdfContentByte cb, ItemInfo itemInfo, VlnSvgPageHelper myPageHelper, float xoff, float yoff, int maxRNO, FormatInfo formatInfo) //, vlnChangeBar myCB) - { - // find column for the change bar based on format flags - this is code from 16-bit - // if AbsoluteFixedChangeColumn - // if FixedAERChangeColumn - // if col>ColsS+ColR+COL_WID+ADJ - // FixedChangeColumn - // else - // AERLeftChangeBarLocation() - // else - // FixedChangeColumn - // else - // ChangeBarLocation() - ChangeBarData cbd = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData; - float cols = formatInfo.MyStepSectionLayoutData.ColS ?? 0; - float colr = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); - // FixedChangeColumn + - Column location for change bars - // 0 - Separate AER and RNO change bars to the right of the text - // -10 to -1 - Change bars on left (specify # of columns from the text) - // <-10 - AER change bars on the left and RNO change bars on the right. - // FixedAERChangeColumn overrides the -5 default setting in chgbar.c, value is converted to a negative by the code - - float col = (cbd.AbsoluteFixedChangeColumn) ? - ((cbd.FixedAERChangeColumn ?? 0) > 0) ? - (xoff > (cols + colr + COL_WID_ADJ)) ? - cbd.FixedChangeColumn ?? 0 : AERLeftChangeBarLocation(formatInfo) : - cbd.FixedChangeColumn ?? 0 : ChangeBarLocation(xoff, this, formatInfo, maxRNO); - string chgIdTxt = null; - if (itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds) - { - StepConfig sc = itemInfo.MyConfig as StepConfig; - chgIdTxt = sc == null ? null : sc.Step_ChangeID; - } - if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.ChgID) - cbMess = chgIdTxt != null ? chgIdTxt : itemInfo.MyContent.UserID; - else if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.DateChgID) - { - string fmtDate = itemInfo.MyContent.DTS.ToShortDateString(); - if (fmtDate.Length != 10) // need to add zeros - { - if (fmtDate.IndexOf("/") == 1) - fmtDate = "0" + fmtDate; - if (fmtDate.IndexOf("/", 3) == 1) - fmtDate = fmtDate.Substring(0, 3) + "0" + fmtDate.Substring(3, fmtDate.Length - 3); - } - cbMess = (chgIdTxt != null ? chgIdTxt : itemInfo.MyContent.UserID) + @"\n" + fmtDate; - } - else if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.RevNum) - { - - string lRev = myPageHelper.Rev; - // Now check the format flags to determine if/how the Rev string should be parsed. - if ((itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate && lRev.Contains("/")) - || (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.RevDateWithForwardSlash && lRev.Contains("\\"))) - { - int indx = lRev.IndexOf(itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate ? '/' : '\\'); - cbMess = lRev.Substring(0, indx > -1 ? indx : lRev.Length); - } - else - cbMess = lRev; - } - else if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.UserDef) - cbMess = myPageHelper.ChangeBarDefinition.MyChangeBarMessage; - - int msgAlign = Element.ALIGN_LEFT; - if (myPageHelper.ChangeBarDefinition.MyChangeBarLoc == PrintChangeBarLoc.LeftOfText || - (myPageHelper.ChangeBarDefinition.MyChangeBarLoc == PrintChangeBarLoc.AERleftRNOright && - !itemInfo.IsInRNO)) msgAlign = Element.ALIGN_RIGHT; - float coltotwips = col * itemInfo.FormatStepData.Font.CharsToTwips; - if (cbd.AbsoluteFixedChangeColumn) coltotwips = col * itemInfo.ActiveFormat.PlantFormat.FormatData.Font.CharsToTwips; - // B2023-052: Beaver Valley - Inconsistent change bar location - used AbsoluteFixedChangeColumn flag, but the LeftMargin - // was still added in, thus sections had different locations for change bar if sections had different left margin. Use - // adjustment, 'AbsChgBarAdj' - coltotwips += itemInfo.MyDocStyle.Layout.AbsChgBarAdj ?? 0; - if (itemInfo.IsFigure) coltotwips = col * itemInfo.ActiveFormat.PlantFormat.FormatData.Font.CharsToTwips; - return new vlnChangeBar(cb, this, (float)itemInfo.MyDocStyle.Layout.LeftMargin + coltotwips, yoff, msgAlign, - myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.RevNum, - itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds); - } - - // changed this function to return a float instead of an int to correct a rounding error which cause change bars - // to inconsistantly position next to changed text. Bug B2015-033 - private float ChangeBarLocation(float c, vlnParagraph paragraph, FormatInfo formatInfo, int maxRNO) - { - int fixedChgCol = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData.FixedChangeColumn ?? 0; - float cols = formatInfo.MyStepSectionLayoutData.ColS ?? 0; - int colr = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); - float tmpc = c; - Box bxCautNote = null; // used for notes and cautions in the Prairie Island Alarms format - if (MyItemInfo.IsCaution || MyItemInfo.IsNote) - { - // Temporary fix for change bars on Notes and Cautions where the FixedChgCol < -10 - tmpc = (float)formatInfo.MyStepSectionLayoutData.ColT + (float)formatInfo.MyStepSectionLayoutData.WidT; // end position of Caution / Note - int typ = (int)(MyItemInfo.MyContent.Type % 10000); - int? bxIndx = formatInfo.PlantFormat.FormatData.StepDataList[typ].StepLayoutData.STBoxindex; - if (bxIndx != null) - { - bxCautNote = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; - if (bxCautNote != null) - tmpc = (float)bxCautNote.Start + (float)bxCautNote.End; // end position of a boxed Caution / Note - } - } - // if this is a caution or note, put the change bar to the right of the text: - //if ((paragraph.MyItemInfo.IsCaution || paragraph.MyItemInfo.IsNote) && fixedChgCol < -10) return -fixedChgCol; - if ((fixedChgCol == 0))// && paragraph.MyItemInfo.IsCaution || paragraph.MyItemInfo.IsNote) - //if ((fixedChgCol==0) || paragraph.MyItemInfo.IsCaution || paragraph.MyItemInfo.IsNote) - { - float rightEdge = (paragraph.XOffset + paragraph.Width + 5); - rightEdge -= (float)paragraph.MyItemInfo.MyDocStyle.Layout.LeftMargin; - if (bxCautNote != null) - rightEdge = (float)bxCautNote.End + 10; // used for notes and cautions in the Prairie Island Alarms format - rightEdge = rightEdge / paragraph.MyItemInfo.FormatStepData.Font.CharsToTwips; - return MyItemInfo.IsFigure ? rightEdge + 1 : rightEdge; // B2017-111: Add a little more space between figure & change bar - } - if (fixedChgCol < -10 || fixedChgCol >= 0) - return ((fixedChgCol > 0) ? fixedChgCol : - (fixedChgCol == 0) ? (int)c + 1 : - (tmpc > (cols + colr + COL_WID_ADJ)) ? -fixedChgCol : - //(c > (cols + colr + COL_WID_ADJ) || (MyItemInfo.IsCaution || MyItemInfo.IsNote)) ? -fixedChgCol : - AERLeftChangeBarLocation(formatInfo)); - else - return (fixedChgCol + (((c < cols + Width + colr) || TableTest() - || MyItemInfo.IsCaution || MyItemInfo.IsNote) ? 0 : cols + colr)); // || (GetColumnMode() == 0)) ? 0 : cols + colr)); - /* Change bars to left of text -- ColS+WidS+ColR is the end of RNO col*/ - } - /* - ** Centered tables whose width exceeds the end of the RNO column should - ** still have their change bars printed on the left. This procedure checks - ** to make sure the step is a table and that it is not an RNO. - */ - private bool TableTest() - { - return false; - //return ((s->Type == TABLE || s->Type == BORDERLESSTABLE) && - //!(strchr((char *)&s->dbseq[2],RNO_MARKER))); - } - private float GetBottomYoff(float bottomY) - { - foreach (vlnParagraph child in ChildrenBelow) - { - if (child.YOffset > bottomY) bottomY = child.YOffset; - bottomY = child.GetBottomYoff(bottomY); - } - return bottomY; - } - private int AERLeftChangeBarLocation(FormatInfo formatInfo) - { - // use -5 default unless it is format specified - int fixedAERChgCol = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData.FixedAERChangeColumn ?? 0; - return (fixedAERChgCol != 0) ? - (fixedAERChgCol > 100) ? - (fixedAERChgCol % 100) : -fixedAERChgCol : -5; - } - private StringBuilder _RtfSB = null; - public string GetRtf(ItemInfo itemInfo, string prefix, string suffix) - { - int profileDepth = ProfileTimer.Push(">>>> GetRtf"); - _RtfSB = new StringBuilder(); - DisplayText vlntxt = new DisplayText(itemInfo, E_EditPrintMode.Print, E_ViewMode.View, true, E_FieldToEdit.StepText, false, prefix, suffix, MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndSpaces != null); - - //C2025-021 Add logic to PROMS to support a special High Level Step type that is not printed. - if (itemInfo.IsType("InvisibleHigh")) - { - System.Drawing.Font myHighFont = vlntxt.TextFont.WindowsFont; - _RtfSB.Append(AddFontTable(myHighFont)); - _RtfSB.Append("}"); - string rtfHigh = _RtfSB.ToString(); - ProfileTimer.Pop(profileDepth); - return rtfHigh; - } - - // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. - if (DisplayText.RemoveTrailingBlankID > 0 && !MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndSpaces.Contains(itemInfo.ItemID)) MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndSpaces.Add(DisplayText.RemoveTrailingBlankID); - System.Drawing.Font myFont = vlntxt.TextFont.WindowsFont; - if (!itemInfo.IsTable && StepRTB.MyFontFamily != null) - // follow through in fixing an Out of Window Handles bug, use new function to see if - // we can retrieve the font from a dictionary instead a doing a New and using another - // window handle B2017-117 - //myFont = new System.Drawing.Font(StepRTB.MyFontFamily, myFont.Size, myFont.Style); - myFont = VE_Font.GetWinSysFont(StepRTB.MyFontFamily, myFont.Size, myFont.Style); - - string stText = null; // if Calvert (BGE) Alarms, the text is included in the macro, so save text as a blank: - if (HasCalvertMacro) - { - stText = " "; - // turn underline off - // follow through in fixing an Out of Window Handles bug, use new function to see if - // we can retrieve the font from a dictionary instead a doing a New and using another - // window handle B2017-117 - //myFont = new System.Drawing.Font(myFont.FontFamily, myFont.Size, System.Drawing.FontStyle.Regular); //myFont.Style. | FontStyle.Underline); - myFont = VE_Font.GetWinSysFont(myFont.FontFamily, myFont.Size, System.Drawing.FontStyle.Regular); //myFont.Style. | FontStyle.Underline); - } - else - stText = vlntxt.StartText; - - if (itemInfo.IsHigh && itemInfo.MyDocStyle.UndSpecialStepsFoldout) - { - // follow through in fixing an Out of Window Handles bug, use new function to see if - // we can retrieve the font from a dictionary instead a doing a New and using another - // window handle B2017-117 - //myFont = new System.Drawing.Font(myFont.FontFamily, myFont.Size, myFont.Style | System.Drawing.FontStyle.Underline); - myFont = VE_Font.GetWinSysFont(myFont.FontFamily, myFont.Size, myFont.Style | System.Drawing.FontStyle.Underline); - stText = stText.Replace(@"\ulnone ", ""); - stText = stText.Replace(@"\ulnone", ""); - } - if (stText.Contains("{IND}")) stText = stText.Replace("{IND}", "\x5"); - if (itemInfo.IsSection && itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.SectionNumber.Level0Big && itemInfo.MyParent.IsProcedure) - // follow through in fixing an Out of Window Handles bug, use new function to see if - // we can retrieve the font from a dictionary instead a doing a New and using another - // window handle B2017-117 - //myFont = new System.Drawing.Font(myFont.FontFamily, 14, myFont.Style | System.Drawing.FontStyle.Bold); - myFont = VE_Font.GetWinSysFont(myFont.FontFamily, 14, myFont.Style | System.Drawing.FontStyle.Bold); - _RtfSB.Append(AddFontTable(myFont)); - _RtfSB.Append(stText); - if (_MyItemInfo.IsStep && !itemInfo.FormatStepData.UseSmartTemplate && _MyItemInfo.FormatStepData.Suffix != null && _MyItemInfo.FormatStepData.Suffix != "") - _RtfSB.Append(_MyItemInfo.FormatStepData.Suffix.Replace("{ulnone}", @"\ulnone ")); - _RtfSB.Append("}"); - string rtf = _RtfSB.ToString(); - UnderlineTerminateList utl = MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.UnderlineTerminateList; - if (utl != null && myFont.Underline) - { - foreach (UnderlineTerminate ut in utl) - { - MatchCollection mc = Regex.Matches(rtf, "(? 0) - { - Match m = mc[mc.Count - 1]; - rtf = rtf.Substring(0, m.Index) + @"\ulnone " + rtf.Substring(m.Index); - } - } - } - ProfileTimer.Pop(profileDepth); - return rtf; - } - private float _XOffsetBox = 0; - public float XOffsetBox - { - get { return _XOffsetBox; } - set { _XOffsetBox = value; } - } - private float _MyBoxLeftAdj = 0; - private float SetHeader(vlnParagraph para, PdfContentByte cb, ItemInfo itemInfo, FormatInfo formatInfo) - { - float xoff = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - // The '6' below is really converting from characters to Twips. But instead of considering the CPI, 16bit assumed - // it was 12 to center the header. That's where the 6 comes from. - float hdrWidth = (itemInfo.MyHeader.CleanText == null) ? 0 : itemInfo.MyHeader.CleanText.Length * 6; - int typ = ((int)itemInfo.MyContent.Type) % 10000; - int? bxIndx = formatInfo.PlantFormat.FormatData.StepDataList[typ].StepLayoutData.STBoxindex; - float adjmentAfterBoxedNoteCautionTab = 0; // F2024-078 used to save the adjustment of the space after the Note/Caution tab - - if (itemInfo.MyHeader.Justify == System.Drawing.ContentAlignment.MiddleCenter) - { - if (bxIndx != null) - { - Box bx = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; - if (bx.TabPos > 0) - xoff += (float)bx.TabPos; // xoff starts as left margin - else - xoff += (float)((bx.TxtStart + _MyBoxLeftAdj + XOffsetBox + (bx.TxtWidth / 2)) - (hdrWidth / 2)); // xoff starts as left margin - adjmentAfterBoxedNoteCautionTab = (float) (bx.AdjSpAftTab ?? 0); // F2024-078 save the adjustment of the space (line) after the Note/Caution tab - } - else if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.IsInRNO && (itemInfo.IsCaution || itemInfo.IsNote)) // C2014-009 - xoff = XOffset + (para.Width / 2) - (hdrWidth / 2); - else if (formatInfo.MyStepSectionLayoutData.Separator.Location > 0) - xoff = XOffset + AdjustToCharPosition((float)((para.Width - hdrWidth) / formatInfo.MyStepSectionLayoutData.Separator.Location), itemInfo.MyHeader.MyFont.CPI); - else if (itemInfo.IsInRNO && itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].NumberWithLevel) - xoff = XOffset + (para.Width / 2) - (hdrWidth / 2); - else if (itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].NumberWithLevel) - xoff = XOffset + (para.Width / 2) - (hdrWidth / 2); - else - xoff = XOffset + (para.Width / 2) + (hdrWidth / 2); // XOffset has left margin included - } - else - xoff = XOffset; // XOffset has left margin included - // KEEP: This may be needed in the future to fix location of 'OR's when Separator location="0" - // the following code would place the 'OR' at the location of the tab rather than text. This - // is how 16bit was. However, a number of plants had been sent out with the xoffset at the xlocation - // of text (does not match 16bit) when this was found for BGE OI3/OI-1B/6.1.B.4. Previous releases - // went to CAT, MCG, FPL, NSP. - //{ - // if (this.MyTab != null) - // xoff = this.MyTab.XOffset; - // else - // xoff = XOffset; - //} - // B2018-096 AEP 082.002CD Note Box overlapping Step Box - vlnHeader myHeader = new vlnHeader(this, cb, itemInfo.MyHeader.Text, itemInfo.MyHeader.CleanText.TrimStart(" ".ToCharArray()), xoff + AdjustHeader + _MyBoxLeftAdj, YOffset, itemInfo.MyHeader.MyFont); - PartsAbove.Add(myHeader); - //return myHeader.Height + (!MyItemInfo.MyDocStyle.SpecialStepsFoldout || (MyItemInfo.MyDocStyle.ExtraLineHeader && (MyItemInfo.IsCaution || MyItemInfo.IsNote)) ? SixLinesPerInch : 0); - // Only use SpaceIn property for Cautions or Notes - bool bSpaceIn = (MyItemInfo.IsCaution || MyItemInfo.IsNote) ? MyItemInfo.FormatStepData.SpaceIn : true; - // F2022-121 added SpecialStepsFoldoutKeepWhiteSpace flag to allow for all of the other special foldout formatting, but - // not compress the page - this need to handle explicit OR and AND sub-steps to ensure there are blank lines before and after - // the separator text. - return myHeader.Height + (!MyItemInfo.MyDocStyle.SpecialStepsFoldout || (MyItemInfo.MyDocStyle.SpecialStepsFoldout && MyItemInfo.MyDocStyle.SpecialStepsFoldoutKeepWhiteSpace) || (MyItemInfo.MyDocStyle.ExtraLineHeader && (MyItemInfo.IsCaution || MyItemInfo.IsNote)) ? bSpaceIn ? SixLinesPerInch : 0 : 0) + adjmentAfterBoxedNoteCautionTab; // F2024-078 add adjustment to the space after the Note/Caution tab - } - private float AdjustToCharPosition(float position, float? CPI) - { - int iPosition = (int)position; - int charsToTwips = (int)(72 / (CPI ?? 12)); - iPosition = (iPosition / charsToTwips) * charsToTwips; - position = (position / 7.2F) * 7.2F; - return (float)iPosition; - } - private bool _SectionPageBreak = false; - public bool SectionPageBreak - { - get { return _SectionPageBreak; } - set { _SectionPageBreak = value; } - } - private bool _Processed = false; - public bool Processed - { - get { return _Processed; } - set { _Processed = value; } - } - private vlnParagraph _LastRNO; - public vlnParagraph LastRNO - { - get { return _LastRNO; } - set { _LastRNO = value; } - } - private vlnParagraph _MyTopRNO; - public vlnParagraph MyTopRNO - { - get { return _MyTopRNO; } - set { _MyTopRNO = value; } - } - private static string _PathPrefix = ""; - public static string PathPrefix - { - get { return vlnParagraph._PathPrefix; } - set { vlnParagraph._PathPrefix = value; } - } - protected float _YBottomMost; // Bottom of the paragraph including the children - public float YBottomMost - { - get { return _YBottomMost; } - set - { - _YBottomMost = value; - } - } - private float _YBottomPagination; // B2019-111 Keep table with Parent - protected float YBottomPagination - { - get { return _YBottomPagination; } - set { _YBottomPagination = value; } - } - protected float _YBottomMostAdjust = 0; // the RNO separator is outside asterisk box, account for additional Y space - public float YBottomMostAdjust - { - get { return _YBottomMostAdjust; } - set { _YBottomMostAdjust = value; } - } - protected float _YTopMost; // Top of the paragraph including the children - public float YTopMost - { - get { return _YTopMost; } - set { _YTopMost = value; } - } - protected float _YTop; // Top of the paragraph including parts - public float YTop - { - get { return _YTop; } - set - { - vlnParagraph vp = this as vlnParagraph; - _YTop = value; - - } - } - public float SmartTemplateAdjust - { - // If we're in a smart template (WCNCKL checklists) then account for the bottom line in the - // table. - get { return (MyItemInfo.IsHigh && MyItemInfo.FormatStepData.UseSmartTemplate) ? SixLinesPerInch : 0; } - } - public float YSize // How big this paragraph is with all of its children - { - get - { - float ysize = SmartTemplateAdjust + _YBottomMost - _YTopMost; - if (MyItemInfo.IsHigh && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) - ysize += SixLinesPerInch; - return ysize; - } - } - private ItemInfo _MyItemInfo; - public ItemInfo MyItemInfo - { - get { return _MyItemInfo; } - set { _MyItemInfo = value; } - } - private vlnParagraph _MyHighLevelParagraph; - - public vlnParagraph MyHighLevelParagraph - { - get - { - if (_MyHighLevelParagraph == null) - { - _MyHighLevelParagraph = GetHighLevelParagraph(); - } - return _MyHighLevelParagraph; - } - } - private vlnParagraph GetHighLevelParagraph() - { - if (MyItemInfo.IsHigh) return this; - return MyParent.GetHighLevelParagraph(); - } - private vlnParagraph _SupInfoSection; - public vlnParagraph SupInfoSection - { - get - { - if (_SupInfoSection == null) - { - _SupInfoSection = GetSupInfoSectionParagraph(); - } - return _SupInfoSection; - } - } - private vlnParagraph GetSupInfoSectionParagraph() - { - if (MyItemInfo.IsSection) return this._SupInfoSection; - return MyParent.GetSupInfoSectionParagraph(); - } - // Tab, Separator, ChangeBar, Box, Circle, Checkoff - private vlnTab _MyTab; - public vlnTab MyTab - { - get - { - if (_MyTab == null) - { - foreach (vlnPrintObject po in PartsLeft) - { - if (po is vlnTab) - { - _MyTab = po as vlnTab; - break; - } - } - } - return _MyTab; - } - } - private vlnPrintObjects _PartsAbove; - public vlnPrintObjects PartsAbove - { - get - { - if (_PartsAbove == null) _PartsAbove = new vlnPrintObjects(); - return _PartsAbove; - } - } - private vlnPrintObjects _PartsBelow; - public vlnPrintObjects PartsBelow - { - get - { - if (_PartsBelow == null) _PartsBelow = new vlnPrintObjects(); - return _PartsBelow; - } - } - private vlnPrintObjects _PartsRight; - public vlnPrintObjects PartsRight - { - get - { - if (_PartsRight == null) _PartsRight = new vlnPrintObjects(); - return _PartsRight; - } - } - private vlnPrintObjects _PartsLeft; - public vlnPrintObjects PartsLeft - { - get - { - if (_PartsLeft == null) _PartsLeft = new vlnPrintObjects(); - return _PartsLeft; - } - } - private vlnPrintObjects _PartsContainer; - public vlnPrintObjects PartsContainer - { - get - { - if (_PartsContainer == null) _PartsContainer = new vlnPrintObjects(); - return _PartsContainer; - } - } - private vlnParagraphs _ChildrenAbove; - public vlnParagraphs ChildrenAbove - { - get - { - if (_ChildrenAbove == null) _ChildrenAbove = new vlnParagraphs(this); - return _ChildrenAbove; - } - } - private vlnParagraphs _ChildrenBelow; - public vlnParagraphs ChildrenBelow - { - get - { - if (_ChildrenBelow == null) _ChildrenBelow = new vlnParagraphs(this); - return _ChildrenBelow; - } - } - private vlnParagraphs _ChildrenRight; - public vlnParagraphs ChildrenRight - { - get - { - if (_ChildrenRight == null) _ChildrenRight = new vlnParagraphs(this); - return _ChildrenRight; - } - } - private vlnParagraphs _ChildrenLeft; - public vlnParagraphs ChildrenLeft - { - get - { - if (_ChildrenLeft == null) _ChildrenLeft = new vlnParagraphs(this); - return _ChildrenLeft; - } - } - private float? _XOffsetCenter = null; - - public float? XOffsetCenter - { - get { return _XOffsetCenter; } - set { _XOffsetCenter = value; } - } - - public bool IsEnhancedBackgroundFormat(ItemInfo itminfo) - { - return ((itminfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds); - } - - public void AdjustXOffsetForTab(ItemInfo itemInfo, int maxRNO, FormatInfo formatInfo, vlnTab myTab, float xMetaAdj) - { - if (itemInfo.IsSupInfoPart) - { - // The SupInfoTabOff was added to the base format during initial development to shift the tab over by 3/4 inch (54) to allow for enough space for Note/Caution tab - int sitabloc = itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoTabOff == null ? 0 : (int)itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoTabOff; - // B2023-069 allow for the adjustment of the Supplemental Information tab at the section level (SecOvrideSupInfoTabOff). - // this will also override the SupInoTabOff setting which is for the entire format - int secOvrSupInfoTab = itemInfo.MyDocStyle.SecOvrideSupInfoTabOff == null ? 0 : (int)itemInfo.MyDocStyle.SecOvrideSupInfoTabOff; - if (secOvrSupInfoTab != 0) sitabloc = secOvrSupInfoTab; - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + sitabloc; - if (myTab != null) - { - myTab.XOffset = XOffset - ((myTab == null) ? 0 : myTab.Width) - 12; - // B2017-253 - Limit the tab offset to 2 points inside the left margin - myTab.XOffset = Math.Max(myTab.XOffset,itemInfo.MyDocStyle.Layout.LeftMargin ?? 72)+2; - float mytbwidth = myTab.Width; - myTab.Width = 2.5f * myTab.Width; - // C2018-022: adjust xoffset of text by 12 if the tab would overwrite the text and the format flag is on: - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoAdjustXOffForLongTab && ((myTab.XOffset + mytbwidth + 12) > XOffset)) - XOffset = 12F + myTab.XOffset + mytbwidth; - } - // B2017-102: need to set width here since using Xoffset because AdjustWidth is called before this adjustment. - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - (sitabloc / 2); - return; - } - // F2019-069: Hold Point designator for Barakah, use parent's tab for xoffset - if (itemInfo.IsStep && itemInfo.FormatStepData.ColUseParentTab && (myTab == null || myTab.Text == "")) - { - if (MyParent != null) - { - XOffset = (MyParent.MyTab == null || MyParent.MyTab.Text == null || MyParent.MyTab.Text.Trim() == "") ? MyParent.XOffset : MyParent.MyTab.XOffset; - return; - } - } - float tabWidth = (myTab == null) ? 0 : myTab.Width; - if (itemInfo.IsStepSection) - { - if (formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Just == "PSLeft") - { - int level = 0; - ItemInfo iilvl = itemInfo; - while (!iilvl.IsProcedure) - { - level++; - iilvl = iilvl.MyParent; - } - if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - { - XOffset = (myTab == null ? 0 : myTab.XOffset) + ((float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos); - } - else - { - level = level <= 2 ? 1 : level - 1; - if (level == 1) - { - // Use the section number position for the section title when the section number is blank - if (formatInfo.PlantFormat.FormatData.SectData.SectionHeader.UseNumPosWhenNumBlank && MyTab != null && MyTab.Text.Trim().Length == 0) - { - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + ((float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos); - } - else - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (level * (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos); - } - else if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - XOffset = (myTab == null ? 0 : myTab.XOffset) + ((float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos); - else - { - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[level].ColSByLevel; - XOffset += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[level].SecTitlePositionAdj; - XOffset -= xMetaAdj; - } - - if (itemInfo.MyDocStyle.SectTitleOffsetOverride != null) + MyPageHelper.MySection = MyItemInfo as SectionInfo; + MyPageHelper.ResetSvg(); + } + } + } + // For Calvert Alarms: A macro exists around the CONDITION/RESPONSE portion. If the page break occurs so that + // this 'table' moved to the following page AND there is an associated note/caution that is not on the next page, + // remove the macro so that the header macro doesn't print on the page with the note (without this, an extraneous + // header for the 'table'is printed. + if (PartsLeft.Count != 0 && (PartsLeft[0] is vlnMacro) && MyPageHelper.ParaBreaks.Count != 0 && MyPageHelper.ParaBreaks[0].MyItemInfo.MyPrevious == null) + if (!MyPageHelper.ParaBreaks[0].MyItemInfo.IsNote && !MyPageHelper.ParaBreaks[0].MyItemInfo.IsCaution) + { + // Only clear the header if it is the first child below + if (ChildrenBelow[0].MyItemInfo.ItemID == MyPageHelper.ParaBreaks[0].MyItemInfo.ItemID) + PartsLeft.Clear(); + //else + // _MyLog.WarnFormat("Would Have Cleared PageHeader '{0}','{1}'", MyItemInfo.MyProcedure.DisplayNumber, MyItemInfo.MyHLS.DisplayText); + } + if (IsWordDocPara) + { + SectionInfo si = SectionInfo.Get(MyItemInfo.ItemID); + //Changing this caused Header issues for FNP FNP-1-FRP-1.3 Attachment 3 (Word Sub-Sections) + //SectionInfo si1 = MyItemInfo.GetSectionInfo(); + //CompareSectionInfo(si, si1); + MyPromsPrinter.NewPage(true); + //_MyLog.InfoFormat("NewPage 9 {0}", cb.PdfWriter.CurrentPageNumber); + // Add Bookmark for Word Subsections + MyPageHelper.PageBookmarks.Add(si, $"{((si.DisplayNumber ?? "") == "" ? "" : $"{si.DisplayNumber} - ")}{si.DisplayText}", null); + MyPageHelper.MyPromsPrinter.CreateWordDocPdf(cb, si); + Processed = true; + { + ProfileTimer.Pop(profileDepth); + return yPageStart; + } + } + float yLocalypagestart = yPageStart; + // yPageStart is offset into roll; YTopMost is offset of topmost of this paragraph. + float yLocation = yPageStart - YTopMost; + + // If this document style has a pagelist item with a continue (some IP2BCK docstyles), clear + // out the variable that flags a continue message + MyPageHelper.OldTemplateContMsg = false; + + if (DebugText.IsOpen) DebugText.WriteLine("ToPdf1:{0},'{1}',{2},{3},{4},{5}", MyItemInfo.ItemID, MyItemInfo.ShortPath, XOffset, yLocation, yPageStart, YTopMost); + int profileDepth1 = ProfileTimer.Push(">>>> vlnParagraph.Paginate"); + int paginate = Paginate(yLocation, yTopMargin, yBottomMargin); + ProfileTimer.Pop(profileDepth1); + bool firstHighLevelStep = MyItemInfo.IsHigh && (MyItemInfo.MyPrevious == null); + bool doSectionTitleContinued = false; // will add " Continued" to the section title if format flag is set + // If SAMG facing page print & doing first pass to generate page break list of supplemental info and + // there was a page break in the step section, but not an associated supinfo item, do the page break when the + // next supinfo item is found: + SectionInfo supInfoSect = MyItemInfo.ActiveSection as SectionInfo; // C2018-003 fixed use of getting the active section + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks && MyPromsPrinter.NeedSupInfoBreak && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) + { + // if this has a caution/note with supinfo, that is id that needs to go in pagination list, unless it is in there. + int aboveSupinfoId = ChildrenAboveHaveSupInfo(); + if (supInfoSect != null) + { + if (supInfoSect.StepSectPageBreaksForSupInfo.Contains(aboveSupinfoId)) aboveSupinfoId = -1; + supInfoSect.StepSectPageBreaksForSupInfo.Add(aboveSupinfoId != -1 ? aboveSupinfoId : MyItemInfo.SupInfos[0].ItemID); + } + MyPromsPrinter.NeedSupInfoBreak = false; + } + + DocStyle docstyle; + bool itemIsPrinted; + switch (paginate) + { + // .oooooo. .oooo. + // d8P' `Y8b d8P'`Y8b + // 888 .oooo. .oooo.o .ooooo. 888 888 + // 888 `P )88b d88( "8 d88' `88b 888 888 + // 888 .oP"888 `"Y88b. 888ooo888 888 888 + // `88b ooo d8( 888 o. )88b 888 .o `88b d88' + // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' `Y8bd8P' + case 0: // No page break + if (MyItemInfo.IsSection) + { + SectionInfo si = MyItemInfo as SectionInfo; + MyPageHelper.PageBookmarks.Add(MyItemInfo, $"{((si.DisplayNumber ?? "") == "" ? "" : $"{si.DisplayNumber} - ")}{si.DisplayText}", null); + DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); + } + // SupInfo has its own pagination and ylocation handling, reset ypagestart & ylocation if continuing on current page. + // The value used was saved when the previous SupInfo step was printed. + if (MyItemInfo.IsSupInfoPart) + { + yPageStart = _yPageStartForSupInfo - SixLinesPerInch; + yLocation = yPageStart - YTopMost; + } + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge) + { + // printing a procedure with section(s) that have supplemental information - determine facing page needed to be merged in. For + // case 0, it is typically at the beginning of the section since the page break occurred in the code that calls this. + // Note that if the procedure has any sections with supinfo, then the entire procedure will need facing pages, either blank page + // or supinfo steps. + // If the section title is printed, then need to get the facing page before the section title is printed and if + // this is the hls where the section title was printed, don't do the facing page. + bool titlePrinted = false; + if (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null)) { - XOffset += (float)itemInfo.MyDocStyle.SectTitleOffsetOverride; - } + // see if the section title is printed. + titlePrinted = (!(MyItemInfo.ActiveSection.MyConfig is SectionConfig sch) || sch.Section_PrintHdr == "Y") || !(MyItemInfo.MyActiveSection as SectionInfo).HasSupInfoSteps; + titlePrinted &= (ShowSectionTitles && !MyItemInfo.MyDocStyle.CancelSectTitle); + } + bool firstSec = true; + foreach (SectionInfo sec in MyItemInfo.MyProcedure.Sections.OfType()) + { + if (sec.IsStepSection) + { + if (MyItemInfo.ActiveSection != null && sec.ItemID == MyItemInfo.ActiveSection.ItemID) break; // C2018-003 fixed use of getting the active section + firstSec = false; + break; + } + } + // If this is first step section and there is no supinfo, the blank page was done in proms printer. + // If this is first step section and there is supinfo, it needs to be put out + bool notFirstOrFirstHasSupInfo = !firstSec || (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection as SectionInfo).HasSupInfoSteps); // C2018-003 fixed use of getting the active section + if (notFirstOrFirstHasSupInfo && ((MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null && !titlePrinted) || (MyItemInfo.IsStepSection && titlePrinted)) && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) + { + // If there is supplemental information to be printed on the facing page, then get the id that has supinfo + // so that it can be retrieved from the pdf for the supinfos for this section. + int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); + if (sid != -1) + { + MyPromsPrinter.DoSupInfoPage(cb, MyPageHelper.TextLayer, MyPageHelper, sid); + } + else + { + MyPromsPrinter.InsertBlankPage(cb); + } + } + } + if (MyItemInfo.IsHigh && MyItemInfo.MyPrevious != null && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) + yPageStart -= SixLinesPerInch; + if (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].CompressFirstPartOfStep) + MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; + if (CompressFoldout) + MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; - } - } - else if (formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Just == "PSCenter") - { - float hdrWidth = itemInfo.MyContent.Text.Length * 6; - float ctr = (((float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin)) / 2; - XOffsetCenter = (float)itemInfo.MyDocStyle.Layout.LeftMargin + ctr - (hdrWidth / 2); - } - return; - } - // B2021-091 added a null reference check - itemInfo was a section and didn't have FormatStepData so just return - if (itemInfo.FormatStepData == null) return; + ///else + /// MyPageHelper.YMultiplier = 1; + break; + // .oooooo. .o + // d8P' `Y8b o888 + //888 .oooo. .oooo.o .ooooo. 888 + //888 `P )88b d88( "8 d88' `88b 888 + //888 .oP"888 `"Y88b. 888ooo888 888 + //`88b ooo d8( 888 o. )88b 888 .o 888 + // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' o888o + case 1: // Break on High Level Step + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) + { + // page break here, determine if there is caution/note above where the page break actually needs to go: + int aboveSupinfoId = ChildrenAboveHaveSupInfo(); + if (supInfoSect != null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0 && aboveSupinfoId > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(aboveSupinfoId); + else if (supInfoSect != null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); + else MyPromsPrinter.NeedSupInfoBreak = true; + supInfoSect?.StepSectPageBreaks.Add(MyItemInfo.ItemID); + } + YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); + docstyle = MyItemInfo.MyDocStyle; + if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yLocation, yTopMargin); + bool doSectionContinue = !MyItemInfo.IsSection && ((docstyle.StructureStyle.Style & E_DocStructStyle.BottomSectionContinue) == E_DocStructStyle.BottomSectionContinue); + if (doSectionContinue) DoBottomContinueMsg(cb, yBottomMargin, yLocation, docstyle, false); + MyPromsPrinter.NewPage(); + //_MyLog.InfoFormat("NewPage 10 {0}", cb.PdfWriter.CurrentPageNumber); + if (MyItemInfo.IsSection && MyParent != null && MyParent.MyItemInfo.IsSection && (MyItemInfo as SectionInfo).IsSeparatePagination()) + { + // F2023-015 for Beaver Valley as two sub-sections that are printed continuously followed by a third sub-section printed + // with separate pagination. This section type uses a different pagelist for the pages after the first page. + // Needed to call ResetDocStyleAndValues to set the new page with the other pagelist sytle. + ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); + RefreshDocStyle(); + yTopMargin = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize) - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin; // C2018-003 fixed use of getting the active section // C2020-002 paper size is now set in the format files + yBottomMargin = Math.Max(0, yTopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); // C2018-003 fixed use of getting the active section + yPageStart = yTopMargin; + } + else if (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious != null)) //do not reset for 1st step + { + //Console.WriteLine("'b1',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); + ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); + //Console.WriteLine("'a1',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); + } + DebugText.WriteLine("Paginate1"); + if (MyItemInfo.IsSection) + { + SectionInfo si = MyItemInfo as SectionInfo; + MyPageHelper.PageBookmarks.Add(MyItemInfo, $"{((si.DisplayNumber ?? "") == "" ? "" : $"{si.DisplayNumber} - ")}{si.DisplayText}", null); - int? bxIndx = itemInfo.FormatStepData.StepLayoutData.STBoxindex; - float? colOvrd = itemInfo.FormatStepData.ColOverride; - if (itemInfo.IsBackgroundStep())//WolfCreekBackgroundFormat && IsHigh||IsNote||IsCaution or ImplicitOR - { - int adj = 2; - if (myTab != null) - { - //B2018-139 use XOffset when processing HLS, Caution, or Note background text and tab - if (itemInfo.IsHigh || (itemInfo.IsNote && (itemInfo.MyParent.IsHigh || itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote)) || (itemInfo.IsCaution && (itemInfo.MyParent.IsHigh || itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote))) - myTab.XOffset = XOffset; - else - { - // F2018-041 seq tabs off of TitleWithTextBelow were running into the step text - myTab.XOffset = XOffset + (itemInfo.FormatStepData.Font.CharsToTwips * adj); // F2018-041 move tab over 2 chars so it positions like paragraphs under TitleWithTextBelow - adj += myTab.Text.Length; // F2018-041 add the length of the tab to the adjustment of the XOffset - } - } - XOffset += (itemInfo.FormatStepData.Font.CharsToTwips * adj); // indent 2 characters for background steps - // B2018-146 Adjust the width to match the HLS Right Margin. - //if (itemInfo.ActiveFormat.Name.StartsWith("WCN")) -- Not needed since IsBackgroundStep - Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; - //else - // Width -= (itemInfo.FormatStepData.Font.CharsToTwips * adj); // Adjust width by 2 characters - return; - } - else if (itemInfo.FormatStepData.UseOldTemplate && itemInfo.IsInTemplate() && - (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd)) // C2018-003 fixed use of getting the active section - { - if (myTab != null) myTab.XOffset = XOffset; - XOffset += myTab.Width; - return; - } - else if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.Type == "TitleWithTextBelow") - { - if ((colOvrd ?? 0) != 0) - XOffset = (float)colOvrd; - else - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - // B2018-146 Adjust the width to match the HLS Right Margin. - if(itemInfo.IsPartOfBackgroundStep()) - //if(itemInfo.ActiveFormat.Name.StartsWith("WCN")) - Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; - return; - } - else if (itemInfo.IsParagraph && - (((itemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds) || - ((itemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations)) && - itemInfo.FormatStepData != null && PreviousIsTitleWithTextBelow(itemInfo)) - { - // This code was needed for fix for B2015-183 && - // IP2 backgrounds so that any 'paragraph's that were at the same - // level as the 'TitleWithTextBelow's would have same left margin (xoffset) as the 'TitleWithTextBelow'. - // an example of this can be found in IP2 Backgrounds, 2-E-0, Step Description Table, Step 22, PLANT-SPECIFIC INFORMATION. - // (NOTE that the IP2 exaxmple was no longer in the data when the work on B2015-183 was done) - if ((colOvrd ?? 0) != 0) - XOffset = (float)colOvrd; - else - { - //Adjuust Indent for Wolf Creek Background format flag - float indentBG1 = itemInfo.IsPartOfBackgroundStep() ? itemInfo.FormatStepData.Font.CharsToTwips * 2 : 0; - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + indentBG1; - // B2018-146 Adjust the width to match the HLS Right Margin. - if (itemInfo.IsPartOfBackgroundStep()) - //if (itemInfo.ActiveFormat.Name.StartsWith("WCN")) - Width = this.MyHighLevelParagraph.XOffset + this.MyHighLevelParagraph.Width - XOffset; - else - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin - indentBG1; - } - return; - } - else if (itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextBelow" && (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || (!itemInfo.IsCaution && !itemInfo.IsNote))) - { - float childindent = itemInfo.MyParent.FormatStepData.ChildIndent ?? 0; - if (myTab != null) - { - float delta = childindent + MyParent.XOffset - myTab.XOffset; - myTab.XOffset += delta; - XOffset += delta; - // B2018-036: set the width of (background/deviation/alarms/etc) steps that have a tab - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || !UseTemplateWidthOrXOff(itemInfo.MyParent)) - { - // B2018-146 Adjust the width to match the HLS Right Margin. - // F2023-112 added format flag for Vogtle Units 3 & 4 backgrounds. This allows use of override width on AND and List sub-step types - if (itemInfo.IsBackgroundStepOrChild() || itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.Vogtle3and4BackgroundFormat) - Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; - else - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin - delta; - } - } - else - { - //Adjust Indent for Wolf Creek Background format flag - float indentBG2 = itemInfo.IsPartOfBackgroundStep() ? itemInfo.FormatStepData.Font.CharsToTwips * 2 : 0; - XOffset = childindent + MyParent.XOffset + indentBG2;//(itemInfo.FormatStepData.Font.CharsToTwips * 2); - // B2016-164: Added the following 'if' so that the width is not recalculated if in the alarm format & the parent has a template - // B2016-168: The fix for 164 broke deviation document printing. The if statement was fixed for both: - // B2019-057 Added a check to see if there is a width override for this step element (Robinson AOP Backgrounds - paragraphs) - float wdthovrd = (itemInfo.FormatStepData.WidthOverride == null) ? 0 : (float)ToInt(itemInfo.FormatStepData.WidthOverride, maxRNO); - if ((!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || !UseTemplateWidthOrXOff(itemInfo.MyParent)) && wdthovrd == 0) - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin - indentBG2; - } - return; - } - else if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.Type == "TitleWithTextRight") - { - if ((colOvrd ?? 0) != 0) - XOffset = (float)colOvrd; - else - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; - return; - } - else if (itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight") - { - XOffset = MyParent.MyParent.XOffset; - // if the step text has a tab, then we need to position the tab to the XOffset and then ajust the text XOffset - // by the length of the tab. - fix for IP2 backgrounds (ex. 2-ECA-3.3, step 6) - if (myTab != null) - { - myTab.XOffset = XOffset; - XOffset += (myTab.Text.Length * myTab.MyFont.CharsToTwips);//myTab.Width - myTab.XOffset; - } - return; - } - if (itemInfo.IsHigh) - { - if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || - ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_SameXOffSubsections) == E_DocStructStyle.DSS_SameXOffSubsections)) - { - // the HLS in the template prints the tab/step on the right edge of page. Don't - // do the other calculations to relocate it. - if (itemInfo.FormatStepData.UseOldTemplate && itemInfo.IsInTemplate()) - { - MyTab.XOffset = XOffset - MyTab.Width; - return; - } - // the following code handles the xoffsets of tabs/HLS in the non-alarm sections for - // the Calvert Alarm format. - if (itemInfo.MyDocStyle.UseColSByLevel) - { - if (myTab != null) - { - myTab.Rtf = myTab.Rtf.Replace(myTab.Text, myTab.Text.TrimStart(" ".ToCharArray())); - // B2022-129: don't indent HLS when flag is on (Barakah - single column step attachment with meta sect) - if (itemInfo.MyDocStyle.AdjSectTitleLoc) - { - myTab.XOffset = MyParent.MyTab.XOffset; - XOffset = MyParent.XOffset; - } - else - { - myTab.XOffset = MyParent.XOffset; - XOffset = myTab.XOffset + MyTab.Width; - } - } - else - XOffset = MyParent.XOffset; // unnumbered hls - return; - } - } - float x = 0; - float xoff = 0; - if ((colOvrd ?? 0) != 0) - x = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)colOvrd; - else - x = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS; + } + // Only do foldout page if not done for section break, i.e. check the there's a previous step. + if (MyItemInfo.MyPrevious != null && MyItemInfo.FoldoutIndex() > -1) + MyPromsPrinter.DoFoldoutPage(cb, "HLS", MyPageHelper.TextLayer, MyPageHelper, MyItemInfo.FoldoutIndex(), false); + // B2018-108 if paginating on first step don't add blank page (it was already added at this point) + // B2023-011: Beaver Valley - continuous section printing on its own page throws off CAS/blank pages + // added the IsSection check to the else if + else if (PromsPrinter.MyFoldoutReader.Count > 0 && MyPageHelper.MyPromsPrinter.InsertBlankPages && (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious != null))) + { + // insert a blank page if this step section had a foldout associated and the checkbox + // on the print dialog, to add blank pages, is checked AND the page did NOT have a + // preceeding foldout. + if (MyItemInfo.FoldoutIndex() <= -1) + { + MyPromsPrinter.InsertBlankPage(cb); + //_MyLog.InfoFormat("NewPage 10 blank {0}", cb.PdfWriter.CurrentPageNumber); + } + } + // See comments under case 0 explaining supinfo/facing page processing. + itemIsPrinted = IsPrintedStepItemForSupInfo(); + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage && itemIsPrinted /*&& !MyItemInfo.IsSection*/ && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) + { + int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); + if (sid != -1) + { + MyPromsPrinter.DoSupInfoPage(cb, MyPageHelper.TextLayer, MyPageHelper, sid); + } + else + { + MyPromsPrinter.InsertBlankPage(cb); // C2019-004: Allow user to define duplex blank page text + } + } + if (MyItemInfo.MyDocStyle.LandscapePageList) + { + System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix(0, 1, -1, 0, cb.PdfDocument.PageSize.Height, 0); + cb.Transform(myMatrix); + } + yPageStart = yTopMargin + YTopMost; + // B2020-001 Catawba had an extra line at the top of a page that paginated on a section (EP/1/A/5000/E0 section B) + // Needed to remove the extra line spacing that is before the start of section B - (section is set for continuous pagination) + if (MyItemInfo.IsSection && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing) + yPageStart += (float)MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[25].StepLayoutData.STExtraSpace; + DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); + SectionTopMessage(cb, yTopMargin); // does wcntraining & suppinfo section title + if (MyPageHelper.CreatingSupInfoPage) yPageStart -= (2 * SixLinesPerInch); + if (doSectionContinue) DoTopContinueMsg(cb, ref yPageStart, yTopMargin, docstyle, null); + // If "ContinueSectionHeader" (format flag) is true then print the section title with "(Continued)" appended to it + // B2020-164 added check for SpecialCaseCalvert to bypass IsSeparateSubsection STP O-67B-2 step 6.5 + // B2025-060 no section continue message if previous was not in same section or sub-section + // fixes Vogtle units 3&4 3-AOP-116 Attachments 2 & 3 + if ((!MyItemInfo.IsSection || MyItemInfo.IsSubsection) && + (MyItemInfo.MyPrevious != null && MyItemInfo.ActiveSection == MyItemInfo.MyPrevious.ActiveSection) && + MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader && + (!MyItemInfo.IsSection || (MyItemInfo.IsSeparateSubsection || MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert))) + { + // B2020-162 - SpecialCaseCalvert flag affect single column procedures, use SpecialCaseCalvertPagination for Two Column procedures instead + // B2020-163 - above bug (162) section header breaking from HLS caused forced pagination. turned out we didn't need to change this for B2020-162. + SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; + doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; + //B2020-123 - Calvert - set CalvertPrintedSubSectTitle flag to fix section continue bug + //B2020-166 - Calvert - only set CalvertPrintedSubSectTitle flag if doSectionTitleContinued is set + if (doSectionTitleContinued && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) CalvertPrintedSubSectTitle = true; // B2020-123 + } - xoff = x - XOffset; - // ColSByLevel will specify the column in which the High Level Step starts with - // respect to the overall level calculation based on sections & meta-sections. - // Only a few of the single column formats use this: WCN1, CAL1, RGEBCK - if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TieTabToLevel - && !(itemInfo.MyDocStyle.SpecialStepsFoldout && itemInfo.MyDocStyle.UseColSByLevel)) - { - int indxLevel = itemInfo.PrintLevel + itemInfo.CurrentSectionLevel(); - // B2021-113: BNPP1new - subsection & HLS should be same level (xoffset of tab & text) - if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) indxLevel++; - float colsbylevel = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[indxLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].ColSByLevel; - float seclvlindent = colsbylevel - (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS; - float adjCols = (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS + seclvlindent; - float xtabcol = adjCols - ((myTab == null || myTab.Text == null) ? 0 : (myTab.Text.Length * 7.2f)); - if (indxLevel > 1 && myTab != null) myTab.XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + xtabcol; - else if (myTab != null) myTab.XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + colsbylevel; - if (myTab != null) - { - myTab.Rtf = myTab.Rtf.Replace(myTab.Text, myTab.Text.TrimStart(" ".ToCharArray())); - if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList != null && - formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList.Count > 0) - // B2021-113: BNPP1new - subsection & HLS should be same level (xoffset of tab & text) - if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) - XOffset += tabWidth; - else - XOffset = myTab.XOffset + GetLeftJustify(formatInfo, indxLevel); // 2.1.1 goes here xoffset = 136 - else - XOffset = myTab.XOffset + (myTab.Text.Length * (float)itemInfo.FormatStepData.Font.CPI) - colsbylevel; - } - } - else - { - XOffset += xoff; - // For Calvert, adjust from the left margin and current section's tab. This is used - // in BGEEOP (see EOP-0/Purpose ). However, it caused BGESTP's to print LossOfAC steps (unnumbered HLS) too - // far to the left. The ForceAlignNullTabWSectHead was introduced so that for that step type (LossOfAC) in STP/OI format, - // the SectData.SectionHeader.Pos was used rather than SectData.SectionNumber.Pos - if (myTab == null && !itemInfo.FormatStepData.ForceAlignNullTabWSectHead && itemInfo.FormatStepData.AlignNullTabWSectHead && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - else if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead) - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; - if (myTab != null) - { - if (itemInfo.MyDocStyle.AlignHLSTabWithSect || itemInfo.FormatStepData.AlignHLSTabWithSectOvride) - { - float orgXOffset = MyTab.XOffset; - myTab.XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; - XOffset = myTab.XOffset + myTab.Width; - // F2025-040 Adjust the Cont Act box position around HLS number - if (myTab.MyMacro != null) myTab.MyMacro.XOffset += (MyTab.XOffset - orgXOffset); - } - else - { - myTab.XOffset += xoff; - if (myTab.MyMacro != null) myTab.MyMacro.XOffset += xoff; - } - } - else - { - if (itemInfo.MyDocStyle.AlignHLSTabWithSect) - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; - } - } - } - else if (((colOvrd ?? 0) != 0) && (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.NullBox)) - { - float tabOffset = (myTab == null ? 0 : myTab.XOffset) - XOffset; - XOffset = (float)colOvrd; - if (myTab != null) myTab.XOffset = XOffset + tabOffset; - return; - } - else if (((colOvrd ?? 0) != 0) && (IsEnhancedBackgroundFormat(itemInfo) && (itemInfo.IsNote || itemInfo.IsCaution))) - { - float tabOffset = (myTab == null ? 0 : myTab.XOffset); - // Adjust the position of the Note/Caution text by the difference of the colOverride and the tab xoffset - XOffset += ((float)colOvrd - tabOffset); - if (myTab != null) myTab.XOffset = (float)colOvrd; // set the note/caution tab offset to the colOverride - return; - } - // put in for Point Beach (wep2) we don't want to do this if we are processing a boxed substep (cont. action substep) - else if (bxIndx != null && (itemInfo.IsCaution || itemInfo.IsNote || - !itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.ContActBoxOnSubSteps)) - { - Box bx = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; - if (bx == null) - { - if ((colOvrd ?? 0) != 0) - { - // 16-bit code subtracted the left margin - //xoff = ((float)colOvrd - (float)itemInfo.MyDocStyle.Layout.LeftMargin) - XOffset; - //XOffset += xoff; - //if (myTab != null) myTab.XOffset += xoff; - //xoff = MyParent.XOffset - myTab.XOffset; - //XOffset += xoff; - float tabOffset = (myTab == null ? 0 : myTab.XOffset) - XOffset; + if (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].CompressFirstPartOfStep) + MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; + else + MyPageHelper.YMultiplier = 1; + break; + // .oooooo. .oooo. + // d8P' `Y8b .dP""Y88b + // 888 .oooo. .oooo.o .ooooo. ]8P' + // 888 `P )88b d88( "8 d88' `88b .d8P' + // 888 .oP"888 `"Y88b. 888ooo888 .dP' + // `88b ooo d8( 888 o. )88b 888 .o .oP .o + // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' 8888888888 + case 2: // Break within a Step' + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) + { + if (supInfoSect != null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); + else MyPromsPrinter.NeedSupInfoBreak = true; + supInfoSect?.StepSectPageBreaks.Add(MyItemInfo.ItemID); + } + YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); + docstyle = MyItemInfo.MyDocStyle; + bool doAlarmBox = false; + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + { + // Recognize that the break occurred WITHIN the CONDITION/RESPONSE table. + // Otherwise, we get extraneous header/top of box lines in pdf. + if (MyPageHelper.AlarmYoffStart > 0) + { + // if the first step in box is what broke to next page, then + // don't print the box on this page, only print it on next page: + doAlarmBox = true; + if (MyItemInfo.MyPrevious == null && MyParent.HasCalvertMacro) + MyPageHelper.AlarmYoffStart = 0; + else if (MyPageHelper.AlarmYoffEnd == 0) + { + // doThreeContinues flags when continue messages are printed in the + // bottom of the CONDITION/RESPONSE table columns. + doThreeContinues = MyItemInfo.StepLevel > 1; + MyPageHelper.AlarmYoffEnd = CalculateYLocation(yLocation, yTopMargin); + } + else if (MyPageHelper.AlarmYoffEnd > 0) + doAlarmBox = false; - XOffset = (float)colOvrd; - if (myTab != null) myTab.XOffset = XOffset + tabOffset; - return; - } - else - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + tabWidth + XOffsetBox; - } - else - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)bx.TxtStart + _MyBoxLeftAdj + tabWidth + XOffsetBox; - if (myTab != null) myTab.XOffset = XOffset - tabWidth; - } - else if (itemInfo.IsRNOPart && itemInfo.MyParent != null && itemInfo.MyParent.IsRNOPart && itemInfo.FormatStepData.NumberWithLevel) - { - // xoffset is same as parent RNO (this is a BGE format flag). Instead of RNO's being siblings, - // they had a parent/child relationship. So want the child to have same xoffset as parent, i.e. - // the same xoffset. - XOffset = MyParent.XOffset; - myTab.XOffset = MyParent.MyTab.XOffset; - return; - } - else if (itemInfo.IsRNOPart && (colOvrd > 0 || !((ItemInfo)itemInfo.ActiveParent).IsHigh) && itemInfo.FormatStepData.OffsetTab) - { - if (colOvrd > 0) - { - XOffset = (int)colOvrd; - if (!((ItemInfo)itemInfo.MyParent).IsHigh) - { - ItemInfo hls = itemInfo.MyHLS; - XOffset -= (itemInfo.MyTab.Offset - hls.MyTab.Offset); - } - } - // if this format has the centerline & numberwithlevel (special tabbing for rno) then - // position rno xoffset of the tab to be close to centerline & text indented from there (only BGE) - if (itemInfo.MyDocStyle.CenterLineX != null && itemInfo.FormatStepData.NumberWithLevel) - { - // if the tab is 3 char or smaller, make the indent amount for the rno text 4 characters. - // if bigger, make it the additional tab size. - int len = myTab.Text.Trim().Length; - int adj = len <= 3 ? 4 : (len - 3) + 4; - float rnoOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)itemInfo.MyDocStyle.CenterLineX + 5; - float tPtPerChar = itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TabPtsPerChar ?? 6; - XOffset = rnoOffset + tPtPerChar * adj; - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - 11; // 11 is about size of char, so don't touch right line. - if (myTab != null) myTab.XOffset = rnoOffset; - } - // if the step is within the rno and we're numbering the high level rno, we've got to account for the - // indenting (increased x offset) for the top level rno's tab, if there is no top level rno: - else if (itemInfo.FormatStepData.NumberHighLevel && (itemInfo.MyHLS.RNOs == null || itemInfo.MyHLS.RNOs.Count <= 0)) - { - // add in the size that an RNO off HLS would take. - tabWidth += itemInfo.MyTab.RNOTabWidthAdjust; - XOffset += tabWidth; - if (myTab != null) myTab.XOffset += tabWidth; - } - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) - { - MyTab.XOffset = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset); - XOffset = MyTab.XOffset + tabWidth - MyTab.TabAlign; - } - } - else if (MyParent != null) - { - if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - else if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) - { - if (MyTab != null) - { - MyTab.XOffset = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset); - XOffset = MyTab.XOffset + tabWidth - MyTab.TabAlign; - if (myTab.MyMacro != null && myTab.MyMacro.XOffset != 0) myTab.MyMacro.XOffset += tabWidth - myTab.TabAlign; - } - } - else if (itemInfo.IsSequential && itemInfo.MyParent.IsHigh && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.Align1StLevSubWHLS) == E_DocStructStyle.Align1StLevSubWHLS)) - { - XOffset = MyParent.XOffset; - if (myTab != null) myTab.XOffset = (MyParent.MyTab != null ? MyParent.MyTab.XOffset : XOffset); - } - else if (itemInfo.IsSequential && itemInfo.MyHLS.FormatStepData.AppendDotZero)// F2018-025 shift first level substep to column position of high level step Westinghouse wst1 step type 50 - { - if (itemInfo.MyParent.IsHigh) - { - XOffset = MyParent.XOffset; - if (myTab != null) myTab.XOffset = (MyParent.MyTab != null ? MyParent.MyTab.XOffset : XOffset); - } - else - { - myTab.XOffset = MyParent.XOffset; - XOffset = myTab.XOffset + MyTab.Width; - } - } - else if (myTab != null && itemInfo.IsSequential && formatInfo.PlantFormat.FormatData.SectData.UseMetaSections && formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList.Count > 0) - { - int indxLevels = itemInfo.PrintLevel + itemInfo.CurrentSectionLevel(); - // B2021-113: BNPP1new - subsection & HLS should be same level (xoffset of tab & text) - if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) indxLevels++; - float tableftadj = GetLeftJustify(formatInfo, indxLevels); - if (tableftadj != 0) - { - // the order of this is important. First adjust the tab's xoffset for the width of - // the tab. The offset of text needs to be adjusted by the 'leftjustify' format variable - // if it existed for this level. - myTab.XOffset += tabWidth; - if (tableftadj != 0 && myTab.Width < tableftadj) - tabWidth = myTab.Width = tableftadj; - XOffset += tabWidth; - myTab.Rtf = myTab.Rtf.Replace(myTab.Text, myTab.Text.TrimStart(" ".ToCharArray())); - Width = MyParent.Width - myTab.Width; - } - else // if no left justify, right align the tab - { - XOffset += tabWidth - (myTab == null ? 0 : myTab.TabAlign); - if (myTab != null) - { - myTab.XOffset += tabWidth - myTab.TabAlign; - if (myTab.MyMacro != null && myTab.MyMacro.XOffset != 0) myTab.MyMacro.XOffset += tabWidth - myTab.TabAlign; - } - } - } + } + } + } + if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yLocation, yTopMargin); + // B2019-115 Locate Bottom Continue Message below AER Table if necesssary + float bcm_yLocation = TableBottom == -1 ? yLocation : Math.Min(TableBottom, yLocation); + DoBottomContinueMsg(cb, yBottomMargin, bcm_yLocation, docstyle, doThreeContinues); + MyPromsPrinter.NewPage(); + // C2018-003 fixed use of getting the active section + // F2023-112 Vogtle Units 3 & 4 background document format DSS_PageListBkgndStpContMsg to print continue message next to step number + if (MyItemInfo.IsStep && (MyItemInfo.ActiveSection != null && + ((MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) || + ((MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListBkgndStpContMsg) == E_DocStructStyle.DSS_PageListBkgndStpContMsg))) + { + // check if parent (can be HLS, Caution or Note) has the UseOldTemplate. If so, + // flag that a continue message should be printed as part of a pagelist header (if pagelist + // has CM: page list item) + ItemInfo itm = MyItemInfo; + while (itm.IsStep && !itm.FormatStepData.UseOldTemplate) itm = itm.MyParent; + // don't put out continue if the page break item is the same as background step item (caution/note or hls) + if (itm.IsStep && itm.ItemID != MyItemInfo.ItemID) + { + MyPageHelper.OldTemplateContMsg = true; + MyPageHelper.ResetSvg(); + } + } + //_MyLog.InfoFormat("NewPage 11 {0}", cb.PdfWriter.CurrentPageNumber); + //Console.WriteLine("'b2',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); + ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); + //Console.WriteLine("'a2',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); - //else if ((itemInfo.FormatStepData.ColOverride ?? 0) > 0) - //{ - // XOffset = (float)itemInfo.FormatStepData.ColOverride; - // MyTab.XOffset = XOffset; - // return; - //} - else // if no left justify, right align the tab - { - // The following fixes F2016-033: Print the Verification Point at left margin. - if (itemInfo.ActiveFormat.Name.ToUpper().StartsWith("VCB") && (itemInfo.FormatStepData.ColOverride ?? 0) > 0) - { - XOffset = (float)itemInfo.FormatStepData.ColOverride; - } - else - { - XOffset += tabWidth - (myTab == null ? 0 : myTab.TabAlign); - if (myTab != null) - { - myTab.XOffset += tabWidth - myTab.TabAlign; - if (myTab.MyMacro != null && myTab.MyMacro.XOffset != 0) myTab.MyMacro.XOffset += tabWidth - myTab.TabAlign; - } - // B2018-146 Adjust the width to match the HLS Right Margin. - if (itemInfo.IsBackgroundStepOrChild()) - Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; - } - } - } - // if format had a tab adjustment for step type, use it. MyTab.Offset is only set for FNP formats - // to get the correct xoffset for their tabs/text. The issue is that they use very large tabs - // because levels of substeps include the parent tab. This code will only be run for FNP. - if (itemInfo.MyTab != null && itemInfo.MyTab.Offset != 0) - { - float xOffTabNew = (MyParent.MyTab != null ? MyParent.MyTab.XOffset : MyParent.XOffset) + itemInfo.MyTab.Offset; - xOffTabNew += MyParent.MyTab == null ? 0 : MyParent.MyTab.TabOffset; - float xIncrement = xOffTabNew - MyTab.XOffset; - myTab.XOffset += xIncrement; - XOffset += xIncrement; - Width -= xIncrement; - } - } - private bool PreviousIsTitleWithTextBelow(ItemInfo itemInfo) - { - while (itemInfo.MyPrevious != null) - { - if (itemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow") return true; - itemInfo = itemInfo.MyPrevious; - } - return false; - } + DebugText.WriteLine("Paginate2"); + if (MyItemInfo.MyHLS.FoldoutIndex() > -1) + MyPromsPrinter.DoFoldoutPage(cb, "Break within Step", MyPageHelper.TextLayer, MyPageHelper, MyItemInfo.MyHLS.FoldoutIndex(), false); // temporary foldout + else if (PromsPrinter.MyFoldoutReader.Count > 0 && MyPageHelper.MyPromsPrinter.InsertBlankPages) + { + MyPromsPrinter.InsertBlankPage(cb); + _MyLog.InfoFormat("NewPage Break within step blank {0}", cb.PdfWriter.CurrentPageNumber); + } + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage && !MyItemInfo.IsSection && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) + { + int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); + if (sid != -1) + { + MyPromsPrinter.DoSupInfoPage(cb, MyPageHelper.TextLayer, MyPageHelper, sid); + } + else + { + MyPromsPrinter.InsertBlankPage(cb); + } + } + // if there is a 'container vlnbox' around the HLS, flag that the drawn box must also break: + if (MyHighLevelParagraph != null && MyHighLevelParagraph.PartsContainer != null && MyHighLevelParagraph.PartsContainer.Count > 0 && + !((MyHighLevelParagraph.MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) + { + foreach (vlnPrintObject vpo in MyHighLevelParagraph.PartsContainer) + { + if (vpo is vlnBox vb) + { + vb.ContainsPageBreak = true; + PartsContainer.Add(vb); + } + } + } - private static float GetLeftJustify(FormatInfo formatInfo, int indxLevels) - { - LeftJustifyList jstlst = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList; - float tableftadj = 0; - foreach (LeftJustify lj in jstlst) - { - if (lj.Index == indxLevels) - { - tableftadj = lj.Size ?? 0; - break; - } - } - return tableftadj; - } - private float _CheckOffWidth = 0; - public float CheckOffWidth - { - get { return _CheckOffWidth; } - set { _CheckOffWidth = value; } - } - private float _AdjustHeader = 0;// B2018-096 AEP 082.002CD Note Box overlapping Step Box - public float AdjustHeader - { - get { return _AdjustHeader; } - set { _AdjustHeader = value; } - } - public void AdjustWidth(ItemInfo itemInfo, int maxRNO, FormatInfo formatInfo, vlnTab myTab) - { - int? bxIndx = itemInfo.IsStep ? itemInfo.FormatStepData.StepLayoutData.STBoxindex : null; - float? widOvrd = 0; - float xwid = 0; - if (itemInfo.IsStep && itemInfo.MyHLS != null && UseTemplateWidthOrXOff(itemInfo) && (xwid = GetWidthOrStartFromTemplate(itemInfo, formatInfo, true)) > 0) - widOvrd = xwid; - else - widOvrd = itemInfo.FormatStepData == null ? null : itemInfo.FormatStepData.WidthOverride == null ? null : - (float?)ToInt(itemInfo.FormatStepData.WidthOverride, maxRNO); - // Calvert subheaders in valve lists - the text gets centered, so the width is the width - // of the page (also, don't do this for alarms, thus the !SpecialCaseCalvert Alarms, since - // alarms use Caution1 as the annunciator): - if (itemInfo.IsStep && itemInfo.MyHLS != null && !itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && - itemInfo.MyHLS.FormatStepData.UseOldTemplate && itemInfo.MyDocStyle.ComponentList && itemInfo.IsCaution1) - { - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin; - return; - } + // If there is a box, adjust the yTopMost to include it. + float yTopMost = YTopMost; + if ((MyItemInfo.IsCautionPart || MyItemInfo.IsNotePart) && MyParent.PartsAbove.Count > 0) + yTopMost = MyParent.PartsAbove[0].YOffset; + yTopMost = Math.Min(yTopMost, YVeryTop); + yPageStart = yTopMargin + yTopMost;// -2 * SixLinesPerInch; + DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); + if (EmptyTopMostPart) yPageStart += SixLinesPerInch; + // If "ContinueSectionHeader" (format flag) is true then print the section title with "(Continued)" appended to it + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader) + { + // if this is calvert OI/STP, then also check that docstyle has a top continue message + // in the document style that includes 'Continued' + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + { + string myMsg = MyItemInfo.MyDocStyle.Continue.Top.Message; + if (myMsg == null || myMsg == "") + { + // There is no message, but still need to check if there is a Section Title Continued message: + // This was added for BGE OI34 (if break was within step, no section title continue message was printed) + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader) + { + SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; + doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; + } + else + doSectionTitleContinued = false; + } + else + { + SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; + doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; + } + } + else + { + SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; + doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; + } + } + bool addExtraLines = SectionTopMessage(cb, yTopMargin); + if (MyPageHelper.CreatingSupInfoPage) yPageStart -= (2 * SixLinesPerInch); + if (!addExtraLines && (!doSectionTitleContinued || !SectionShowTitles)) + addExtraLines = DoTopContinueMsg(cb, ref yPageStart, yTopMargin, docstyle, doThreeContinues && MyItemInfo.MyParent != null && MyItemInfo.MyParent.MyTab != null ? MyItemInfo.MyParent.MyTab.CleanText : null); + // B2020-128: If compression flag is on RNO, see if there is an AER to the left and do the 7lpi multiplier + if (CompressPartOfStep || CompressRnoWithAerToTheLeft()) + { + MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; + CompressPartOfStep = false; + } + else + MyPageHelper.YMultiplier = 1; - // Calvert Alarms had a case where the Title With Text Below (type 42) did not match - // any of the template items, but needed the width from the template. The previous step (of - // same type) was in the template. Check for this case. The issue can be found in - // Unit 1 Alarms/1c06/Alarm E-48/'General Information' section. - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && widOvrd == 0) - { - if (itemInfo.MyPrevious != null && itemInfo.MyPrevious.TemplateIndex > 1) widOvrd = GetWidthOrStartFromTemplate(itemInfo.MyPrevious, itemInfo.MyPrevious.ActiveFormat, true); - } + // For Calvert Alarms, if there was a page break and there is an box around the current + // step, need to add the header for the box, which is stored in a macro. Also set the + // 'AlarmYoffStart' value to where the vertical lines of the box start on this page. + if (doAlarmBox && MyItemInfo.StepLevel > 1) + { + float alrmY = yTopMargin - (2 * SixLinesPerInch); // CalculateYOffset(yPageStart, yTopMargin); + vlnMacro vlnm = new vlnMacro((float)docstyle.Layout.LeftMargin - 12, alrmY, "H4") + { + UseInternalY = true // B2020-121: Account for Header on Caution or Note + }; + PartsLeft.Add(vlnm); + MyPageHelper.AlarmYoffStart = alrmY - SixLinesPerInch; + yPageStart -= (4 * SixLinesPerInch); + if (ChildrenRight.Count > 0 && ChildrenRight[0].ChildrenAbove.Count > 0 && ChildrenRight[0].ChildrenAbove[0].MyItemInfo.IsCautionOrNotePart) + yPageStart += (SixLinesPerInch); // B2020-121: Account for Header on Caution or Note + } + // For Calvert Alarms, if there is no box & this is top of page, if previous step + // had box (macro), adjust up page. The constructor (vlnParagraph), inserted these + // lines after the box so that the following text did not print right next to box. + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + if (MyItemInfo.MyPrevious != null && MyItemInfo.MyPrevious.TemplateIndex > 0 && MyItemInfo.ActiveFormat.PlantFormat.FormatData.Templates[MyItemInfo.MyPrevious.TemplateIndex].hmacro > 0) + yPageStart += (3 * SixLinesPerInch); + } + // Now check if this is a template type step & if so, add the HLS's prefix/suffix to it. + // Since the entire checklist HLS (checklist table header) is printed as part of the + // continue, create a new paragraph to handle pagination and printing. + if (MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.FormatStepData.UseSmartTemplate) + { + DoSubs = false; + vlnParagraph smartPara = new vlnParagraph(MyParent.MyParent, cb, MyItemInfo.MyHLS, MyParent.XOffset, yPageStart, 0, 0, MyParent.MyItemInfo.ActiveFormat, null, " (Continued)", 0, false, MyPromsPrinter) + { + PrintHeader = true + }; + _ = smartPara.ParagraphToPdf(cb, yPageStart, yTopMargin, yBottomMargin); + yPageStart -= smartPara.Height; + DoSubs = true; + } + if (addExtraLines) yPageStart -= (2 * SixLinesPerInch); + if (MyItemInfo.IsRNOPart && MyItemInfo.FormatStepData.DoubleSpace && MyItemInfo.FormatStepData.SpaceDouble) yPageStart += SixLinesPerInch; + break; + // .oooooo. .oooo. + // d8P' `Y8b .dP""Y88b + // 888 .oooo. .oooo.o .ooooo. ]8P' + // 888 `P )88b d88( "8 d88' `88b <88b. + // 888 .oP"888 `"Y88b. 888ooo888 `88b. + // `88b ooo d8( 888 o. )88b 888 .o o. .88P + // `Y8bood8P' `Y888""8o 8""888P' `Y8bod8P' `8bd88P' + case 3: // Break on High Level Step (SevenLinesPerInch) + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks) + { + if (supInfoSect != null && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); + else MyPromsPrinter.NeedSupInfoBreak = true; + supInfoSect?.StepSectPageBreaks.Add(MyItemInfo.ItemID); + } + if (!firstHighLevelStep || (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage)) // B2017-229: Added supinfo print check to run facing page logic + { + YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); + if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yLocation, yTopMargin); + MyPromsPrinter.NewPage(); // HLS (7 lpi) breakif (MyItemInfo.IsSection) + //_MyLog.InfoFormat("NewPage 12 {0}", cb.PdfWriter.CurrentPageNumber); + //Console.WriteLine("'b3',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); + ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin); + //Console.WriteLine("'a3',{0},'{1}',{2},{3},{4},{5},{6}", MyItemInfo.ItemID, MyItemInfo.ShortPath, yTopMargin, yPageStart, yLocation, YTopMost, YOffset); + DebugText.WriteLine("Paginate3"); + if (MyItemInfo.IsSection) + { + SectionInfo si = MyItemInfo as SectionInfo; + MyPageHelper.PageBookmarks.Add(MyItemInfo, $"{((si.DisplayNumber ?? "") == "" ? "" : $"{si.DisplayNumber} - ")}{si.DisplayText}", null); + } + if (MyItemInfo.FoldoutIndex() > -1) + MyPromsPrinter.DoFoldoutPage(cb, "HLS (7 lpi) break", MyPageHelper.TextLayer, MyPageHelper, MyItemInfo.FoldoutIndex(), false); + else if (PromsPrinter.MyFoldoutReader.Count > 0 && MyPageHelper.MyPromsPrinter.InsertBlankPages) + { + // insert a blank page if this step section had a foldout associated and the checkbox + // on the print dialog, to add blank pages, is checked + MyPromsPrinter.InsertBlankPage(cb); + //_MyLog.InfoFormat("NewPage 12 lpi blank {0}", cb.PdfWriter.CurrentPageNumber); + } + // See comments under case 0 explaining supinfo/facing page processing. + itemIsPrinted = IsPrintedStepItemForSupInfo(); + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && !MyPageHelper.CreatingSupInfoPage && itemIsPrinted /*&& !MyItemInfo.IsSection */ && !MyItemInfo.IsInSupInfo && (MyItemInfo.MyProcedure as ProcedureInfo).ProcHasSupInfoData) + { + int sid = GetIdThatHasSupInfoItems(MyItemInfo, MyItemInfo.ItemID); + if (sid != -1) + { + MyPromsPrinter.DoSupInfoPage(cb, MyPageHelper.TextLayer, MyPageHelper, sid); + } + else + { + // B2020-031: Don't put out an extra blank page if section has title that is printed (blank page is output then) + bool titlePrinted = false; + if (MyItemInfo.IsSection || (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null)) + { + // see if the section title is printed. + titlePrinted = (!(MyItemInfo.ActiveSection.MyConfig is SectionConfig sch) || sch.Section_PrintHdr == "Y") || !(MyItemInfo.MyActiveSection as SectionInfo).HasSupInfoSteps; + titlePrinted &= (ShowSectionTitles && !MyItemInfo.MyDocStyle.CancelSectTitle); + } + if (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null && !titlePrinted) + MyPromsPrinter.InsertBlankPage(cb); + } + } + if (MyItemInfo.MyDocStyle.LandscapePageList) + { + System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix(0, 1, -1, 0, cb.PdfDocument.PageSize.Height, 0); + cb.Transform(myMatrix); + } - // for IP2 backgrounds, set widths appropriately for template items: - if (itemInfo.IsStep && (itemInfo.ActiveSection != null && (itemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd)) // C2018-003 fixed use of getting the active section - { - if (itemInfo.FormatStepData.Type.ToUpper() == "TITLEWITHTEXTBELOW") - { - Width = MyParent.Width; - return; - } - if (itemInfo.MyPrevious != null && itemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow") - { - Width = MyParent.MyParent.Width; - return; - } - if (widOvrd == 0 && itemInfo.MyParent.IsStep && - (itemInfo.MyParent.FormatStepData.Type.ToUpper() == "TITLEWITHTEXTBELOW" || - (((itemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) && - itemInfo.FormatStepData != null && MyParent.MyItemInfo.MyPrevious != null && MyParent.MyItemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow"))) - { - Width = MyParent.MyParent.Width + (MyParent.MyParent.MyTab != null ? MyParent.MyParent.MyTab.Width : 0); - Width -= (MyTab != null ? MyTab.Width : 0); - return; - } - } + // If "ContinueSectionHeader" (format flag) is true then print the section title with "(Continued)" appended to it + if (!MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader) + { + SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig; + doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle; + } + } + // if printing the section title, we already have the y location (note that only do this for the + // first step in the section. + if (MyItemInfo.MyPrevious != null || MyItemInfo.MyParent == null || !MyItemInfo.MyParent.IsStepSection || !ShowSectionTitles || MyItemInfo.MyDocStyle.CancelSectTitle || MyItemInfo.MyDocStyle.SpecialStepsFoldout) + { + yPageStart = yTopMargin + YTopMost; + } - //widOvrd = itemInfo.FormatStepData == null ? null : itemInfo.FormatStepData.WidthOverride; - // Don't adjust the RNO width if in single column mode: - if (itemInfo.IsRNOPart && itemInfo.MyParent.IsHigh && itemInfo.ActiveSection != null && itemInfo.ActiveSection.ColumnMode != 0 && itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAlt != null) // C2018-003 fixed use of getting the active section - { - string[] splitRNOWidthAlt = itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAlt.Split(','); - float ovrd = (itemInfo.RNOLevel < splitRNOWidthAlt.Length) ? float.Parse(splitRNOWidthAlt[itemInfo.RNOLevel]) : 0; - if (ovrd > 0) - widOvrd = ovrd; // + 6; // Change bars on RNO column (signoff line) would not line up with 16-bit without this - NSP Alarms - } - if ((widOvrd ?? 0) != 0) - { - //F2023-112 Vogtle Units 3 & 4 Backgrounds. Don't use override width of paragraph when it's off of TitleWithTextRight - // We need to allow the code to calculate the width of that paragraph for this case (later in this function) - if (!(itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.Vogtle3and4BackgroundFormat && itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight")) - { - Width = (float)widOvrd; - // if there's a box, we may need to do an adjustment on the width, if the tab data was changed - // so don't return. - if (bxIndx == null) return; - } - } - float tabWidth = (myTab == null) ? 0 : myTab.Width; - if (itemInfo.IsHigh) - { - float CheckOffAdj = 0; - bool ChkOff = itemInfo.MyDocStyle.UseCheckOffs; - // C2019-040 use format flag to see if any of the steps in this section have a checkoff set - previously we check if the format file name starts with VCB (VCB no longer a customer) - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert || itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckoffsWithoutHeader) - { - SectionInfo si = itemInfo.ActiveSection.GetSectionInfo(); - ChkOff = si.HasInitials; // this determines if any steps within the section have checkoffs. - } - bool FmtHasAdj = false; - if (ChkOff) - { - if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffAdjustment != null) - { - FmtHasAdj = true; - CheckOffAdj = -(float)formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffAdjustment; - } - // C2019-040 use format flag to not readjust the CheckOffAdj value - previously we check if the format file name starts with VCB (VCB no longer a customer) - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckoffsWithoutHeader) // Don't do the following if in a vcb format (part of fix F2016-039) - { - if (!HasCheckOffHeading(itemInfo, formatInfo) && CheckOffAdj < 0) - CheckOffAdj += (float)(9 * 7.2); // 9 is the size of the SIGNOFF adjustment - else if (!FmtHasAdj && HasCheckOffHeading(itemInfo, formatInfo)) - // For Robinson, tried using font's CharsToTwips but it made it too narrow, so used hardcoded 6: - CheckOffAdj = -((float)9 * 6); - } - } - float adjwidth = CheckOffAdj; - CheckOffWidth = -CheckOffAdj; - adjwidth = AdjustMetaWidth(itemInfo, formatInfo, adjwidth, FmtHasAdj); - Width = ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, maxRNO); - Width += _WidthAdjust; - Width += adjwidth; + MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; + DoCheckOffHeader(cb, MyItemInfo, yLocation, yTopMargin, yPageStart); + break; + } + // If "doSectionTitleContinued" is true then print the section title with "(Continued)" appended to it + // format must have ContinueSectinHeader format flag set to true + //B2025-048 Problem with Printing CAS Steps + // skip this if printing CAS or CTAS - was causing it to + // skip/overwrite data + if (doSectionTitleContinued) + { + vlnParagraph sectContPara; + string contMsg = (MyItemInfo.ActiveSection != null) ? MyItemInfo.ActiveSection.MyDocStyle.Continue.SectionTitle.AppendToTitle : ""; // C2018-003 fixed use of getting the active section + // For Calvert, the xoffset will be the highest level sections xoffset (there are metasections, + // don't use their xoffset or the continue message is indented too much) + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + { + float secContinueTabXoff = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin; + float secContinueXoff = 0f; + vlnParagraph fndTopSect = this; + while (fndTopSect.MyParent != null) + { + fndTopSect = fndTopSect.MyParent; + } + if (fndTopSect != null && fndTopSect.MyTab != null) + { + secContinueTabXoff = fndTopSect.MyTab.XOffset; + secContinueXoff = fndTopSect.XOffset; + } + // get to the correct section for the message, i.e. if on a section, the message should be the parent + // section (not the activesection which is myself); if on a step, the message should be the active section + ItemInfo sectForCont = MyItemInfo.IsSection && MyItemInfo.MyParent.IsSection ? MyItemInfo.MyParent : MyItemInfo.ActiveSection; + //B2025-054 Wrong Page Numbers in CAS Summary + // when section title continued and CAS + //to avoid overwriting data + // - this will be built at a different call to vlnParagraph + if (MyPromsPrinter.PromsPrinterPrintType != PromsPrinterPrintType.Normal) + MyPromsPrinter.ShouldPrint_CAS_CTAS = false; + sectContPara = new vlnParagraph(MyParent.MyParent, cb, sectForCont, MyParent.XOffset, 0, 0, 0, MyParent.MyItemInfo.ActiveFormat, null, (contMsg == null || contMsg == "") ? " (Continued)" : contMsg, 0, false, MyPromsPrinter); + if (sectContPara.PartsLeft.Count > 0) + { + vlnTab vt = sectContPara.MyTab; + string ctab = GetSectCombinedTab(MyItemInfo); + vt.Rtf = GetRtf(ctab, vt.MyFont); + float wd = vt.GetTextWidth(vt.MyFont, ctab); + vt.XOffset = secContinueTabXoff; + vt.Width = secContinueXoff - secContinueTabXoff; + sectContPara.XOffset = secContinueXoff; + if ((wd + 12) > secContinueXoff - secContinueTabXoff) // 12 is 2 characters + { + float dif = wd + 12 - (secContinueXoff - secContinueTabXoff); + vt.Width += dif; + sectContPara.XOffset += dif; + sectContPara.Width -= dif; + } - // if AlignHLSTabWithSect is set, we moved the starting x location of the HLS, and following steps - // to be under section header. Adjust the width accordingly, or the text may go out of the margin. - if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) - Width = Width + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; - else if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead) - Width = Width + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; - else if (itemInfo.MyDocStyle.AlignHLSTabWithSect) - Width = Width - (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; + } - // B2022-002: Section text is printing into the INITIAL column (BNPP1new). If this flag is set adjust the width of the - // section text to that of the first hls (child) text and its tab. This is to prevent the very long section titles (that should have - // been steps) from extending into the INITIAL (checkoff) column. - if (formatInfo.PlantFormat.FormatData.SectData.AdjWidthForCheckOff && MyParent != null && MyParent.MyItemInfo.IsSection && ChkOff && CheckOffWidth != 0 && itemInfo.ItemID == itemInfo.FirstSibling.ItemID) - { - SectionInfo si = MyParent.MyItemInfo.GetSectionInfo(); - if (si.HasInitials) MyParent.Width = Width + ((myTab == null) ? 0 : myTab.Width); - } - } - else if (bxIndx != null) - { - Box bx = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; - if (bx == null) - { - // NOT SURE IF WE NEED TO TEST FOR THE NULLBOX FORMAT FLAG, MAYBE "bx == null" IS THE SAME THING - //if (formatInfo.MyStepSectionLayoutData.NullBox) - if (widOvrd != 0) - Width = (float)widOvrd - tabWidth; - else - Width = (float)formatInfo.MyStepSectionLayoutData.WidT - tabWidth; - } - else - { - float oldWidth = _WidthAdjustBox + (float)bx.TxtWidth - tabWidth; // add 1 to get it to wrap like 16Bit - // B2018-096 AEP 082.002CD Note Box overlapping Step Box - if (MyParent.MyItemInfo.FormatStepData != null && MyParent.MyItemInfo.FormatStepData.BoxIt) // B2018-100 not for parents that are sections // B2018-098 only adjust width if parent has Boxit turned on - { - Width = Math.Min(MyParent.Width + MyParent.XOffset - XOffset, oldWidth); - AdjustHeader = (Width - oldWidth) / 2; - } - else - Width = oldWidth; - } - } - else if ((itemInfo.IsCaution || itemInfo.IsNote) && !itemInfo.FormatStepData.UseOldTemplate) - { - float mycolT = (float)formatInfo.MyStepSectionLayoutData.ColT; - if (formatInfo.MyStepSectionLayoutData.Dev_Format) - Width = (float)formatInfo.MyStepSectionLayoutData.WidT + 1; - else if (itemInfo.IsInRNO) - { - // C2014-009: Condition/Response adjust xoffset & width - // B2020-117 add a check that there is only one Caution/Note/Warning - if (MyItemInfo.FormatStepData.CenterOneLineAdjust && MyItemInfo.FirstSibling == MyItemInfo.LastSibling) - { - int rnoOff = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); - if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - XOffset = MyTopRNO.MyTab.XOffset + 7.2f; - Width = MyParent.Width + (MyParent.XOffset - XOffset); - } - else - { - XOffset = rnoOff + MyHighLevelParagraph.XOffset; - Width = MyParent.Width; - } - } - // B2020-117 There are muliple Cautions, Notes, or Warnings in the Calvert Alarm Contition/Response - // Need to adjust the starting positon of the bulleted tab, text and width - else if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - XOffset = MyTopRNO.MyTab.XOffset + 7.2f; - this.MyTab.XOffset = XOffset; - XOffset += this.MyTab.Width; - Width = MyParent.Width + (MyParent.XOffset - XOffset); - } - else - Width = (MyParent.XOffset + MyParent.Width) - (XOffset + mycolT); - } - else - { - // B2016-269: if caution/note & not boxed, with tab adjust width based on xoffset of tab - // so text doesn't print out of right border. - // B2017-027: Added a check for column mode - we only want to do this if in single column mode - if (!MyItemInfo.MyParent.IsHigh && MyTab != null && MyTab.YOffset == YOffset && MyItemInfo.ActiveSection != null && MyItemInfo.ActiveSection.ColumnMode == 0) // C2018-003 fixed use of getting the active section - { - // B2017-xxx if this is a caution/note off of a substep in the supinfo column, need to look up for its supinfo part, not - // its HLS. - if (MyItemInfo.IsInSupInfo) - { - vlnParagraph supinfopart = this; - while (supinfopart.MyParent != null && !supinfopart.MyItemInfo.IsSupInfoPart) supinfopart = supinfopart.MyParent; - XOffset = supinfopart.XOffset; - MyTab.XOffset = XOffset - MyTab.Width - 10; - Width = supinfopart.Width; - } - else - Width = MyHighLevelParagraph.Width - MyTab.Width - (MyTab.XOffset - MyHighLevelParagraph.XOffset) - 6; - } - else - Width = (float)formatInfo.MyStepSectionLayoutData.WidT - 6 - mycolT; - } - XOffset += mycolT; // adjust caution/note text position - if (PartsLeft != null && PartsLeft.Count > 0)// adjust tab position - { - if (myTab != null && (itemInfo.IsNote || itemInfo.IsCaution)) - Width -= myTab.Width; - foreach (vlnPrintObject vpo in PartsLeft) - vpo.XOffset += mycolT; - } - } - else if (itemInfo.IsSection) - { - // B2023-074 The itemInfo we are processing is a section (number and title). Change maxRNO to zero to getting the width. - // The Width is used when printing the section number and title (when the check box on the properties page is checked) - // and is assumemed the section is a single column section (maxRNO = 0) and uses the format variable WidSTablePrint - // which holds the widths for then the section has one column, two column, or three column. - // For printing section numbers and titles like this, we always want to accomodate for lone section title text. - // So the initial width should always be set to the one column width value so that it can spane across the page. - Width = ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, 0); - float adjwidths = 0; - adjwidths = AdjustMetaWidth(itemInfo, formatInfo, adjwidths, false); - Width += (adjwidths + _WidthAdjust); - } - else if (MyParent == null) - { - // 72 points / inch - 7 inches (about width of page) - Width = 72 * 7; - } - else if (itemInfo.IsRNOPart && itemInfo.ActiveSection != null && itemInfo.ActiveSection.ColumnMode != 0 && itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAltAll != null) // C2018-003 fixed use of getting the active section - { - // This code was added for AEP. Other code that adjusted RNO widths was only adjusting the RNO widths - // off of the HLS. AEP needed adjusting for all RNOs. - float ovrd = (float)itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAltAll; - if (ovrd > 0) - Width = ovrd - tabWidth; - if (XOffset + Width > (float)itemInfo.MyDocStyle.Layout.PageWidth) - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - 5; - } - else if (itemInfo.IsRNOPart && !((ItemInfo)itemInfo.ActiveParent).IsHigh) - { - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAdj != null && !((ItemInfo)itemInfo.ActiveParent).IsInRNO) - Width = MyParent.Width + float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAdj); - else - Width = MyParent.Width; - } - else if (itemInfo.IsRtfRaw) // this needs to be before the check for 'IsTablePart' - the rtfraw may be a table part, but the size is defined by raw rtf - { - System.Drawing.Size sz = RtfRawItem.GetRtfRawSize(MyItemInfo.MyContent.Text); - Height = sz.Height; - Width = sz.Width; - Rtf = MyItemInfo.MyContent.Text; - } - else if (itemInfo.IsTablePart) - { - Width = 72 * 7; // TODO: Need to determine the Width of the Table based upon the contents - } - else if (itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight") // B2019-141: Background steps width too small - { - Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset; - } - else if (itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote) - { - if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) - Width = MyParent.MyParent.Width - tabWidth + (myTab == null ? 0 : myTab.TabAlign); - else - Width = MyParent.Width - tabWidth + (myTab == null ? 0 : myTab.TabAlign); - Width -= 72 * (itemInfo.FormatStepData.CautionOrNoteSubstepIndent == null ? 0 : (float)itemInfo.FormatStepData.CautionOrNoteSubstepIndent / (float)itemInfo.FormatStepData.Font.CPI); - } - else - { - float adjwidth = 0; - if (itemInfo.IsRNOPart && itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthSameAsHighParent && itemInfo.MyParent.IsHigh) - Width = adjwidth + MyParent.Width; - else if (itemInfo.MyTab != null && itemInfo.MyTab.Position != 0) - Width = adjwidth + MyParent.Width; - else if (MyParent.WidthNoLimit != 0) - Width = adjwidth + MyParent.WidthNoLimit - tabWidth + (myTab == null ? 0 : myTab.TabAlign); - else if ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) - Width = adjwidth + MyParent.Width - (MyTab != null ? MyTab.Width : 0); - else - Width = adjwidth + MyParent.Width - tabWidth + (myTab == null ? 0 : myTab.TabAlign); - } - if (itemInfo.IsSequential && itemInfo.MyParent.IsHigh && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.Align1StLevSubWHLS) == E_DocStructStyle.Align1StLevSubWHLS)) - Width += 10; // FIX THIS!!! - } + _ = sectContPara.ParagraphToPdf(cb, yTopMargin, yTopMargin, yBottomMargin); + if (sectContPara.SectionContinuePrinted) + yPageStart -= sectContPara.Height + SixLinesPerInch; + } + else + { + //B2025-054 Wrong Step Numbers + // when section title continued and CAS + //to avoid overwriting data + // - this will be built at a different call to vlnParagraph + if (MyPromsPrinter.PromsPrinterPrintType != PromsPrinterPrintType.Normal) + MyPromsPrinter.ShouldPrint_CAS_CTAS = false; + sectContPara = new vlnParagraph(MyParent.MyParent, cb, MyItemInfo.ActiveSection, MyParent.XOffset, 0, 0, 0, MyParent.MyItemInfo.ActiveFormat, null, (contMsg == null || contMsg == "") ? " (Continued)" : contMsg, 0, false, MyPromsPrinter); + _ = sectContPara.ParagraphToPdf(cb, yTopMargin, yTopMargin, yBottomMargin); + if (sectContPara.SectionContinuePrinted) + yPageStart -= sectContPara.Height + SixLinesPerInch; + } + } + //out of section title section - reset this back to true (default) + MyPromsPrinter.ShouldPrint_CAS_CTAS = true; - private float AdjustMetaWidth(ItemInfo itemInfo, FormatInfo formatInfo, float adjwidth, bool coadj) - { - SectData sd = formatInfo.PlantFormat.FormatData.SectData; - if (((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_SameXOffSubsections) == E_DocStructStyle.DSS_SameXOffSubsections)) - { - // don't adjust the width if there already was an adjustment for checkoffs - for VCB only (F2016-039) - VCB no longer a customer - // C2019-040 use format flag to adjust the width (was already don for checkoffs) - previously we check if the format file name starts with VCB (VCB no longer a customer) - if (!(itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckoffsWithoutHeader && coadj)) - adjwidth = MyTab != null ? -MyTab.Width : 0; - } - else if (sd.UseMetaSections) - { - if (sd.StepSectionData.StepSectionLayoutData.TieTabToLevel) - { - if (ShowSectionTitles - && !itemInfo.MyDocStyle.CancelSectTitle - && !(itemInfo.MyDocStyle.SpecialStepsFoldout && itemInfo.MyDocStyle.UseColSByLevel)) - { - int indxLevel = itemInfo.PrintLevel + itemInfo.CurrentSectionLevel(); - //F2022-023 Used the SubSectAndHighSameLevel (BNPP1New format) flag to get the proper level if we have sub-sections so that we get the proper WidSAdjByLevel value - if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) indxLevel++; - adjwidth += formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[indxLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].WidSAdjByLevel ?? 0; ; - float colsbylevel = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[indxLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].ColSByLevel; - float seclvlindent = colsbylevel - (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS; - adjwidth -= seclvlindent; - if (itemInfo.IsStep) adjwidth -= AdjustForSectionLevelTab(); - if (itemInfo.IsSection && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining) - adjwidth -= (float)((itemInfo.MyTab.CleanText.Trim().Length * 72) / itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.SectionHeader.Font.CPI); - } - } - else - { - if (formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex > 0) - adjwidth += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[itemInfo.PrintLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].ColSByLevel; - } - } - return adjwidth; - } + // see if this hls has footnotes, add to the footnote datastructure for processing at end of page. + if (MyItemInfo.IsHigh && MyPageHelper.NotesToFootNotesHLS.ContainsKey(MyItemInfo.ItemID)) AddFootNote(cb); - // for Component Table, don't increment yoff unless last item in table that HAS data associated - // with it (there may be empty cells at end). - public bool UseTemplateKeepOnCurLine(ItemInfo itemInfo) - { - if (!itemInfo.IsStep || !itemInfo.MyDocStyle.ComponentList) return false; - if (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert - && itemInfo.MyHLS.FormatStepData.UseOldTemplate) return true; - return false; - } - private bool UseTemplateWidthOrXOff(ItemInfo itemInfo) - { - if (!itemInfo.IsStep) return false; - if (itemInfo.MyHLS == null) return false; - if (itemInfo.MyHLS.FormatStepData.UseSmartTemplate || (itemInfo.MyDocStyle.ComponentList && itemInfo.MyHLS.FormatStepData.UseOldTemplate)) - { - ItemInfo useForTemplate = itemInfo.IsHigh ? itemInfo : itemInfo.MyParent; - int topIndx = useForTemplate.GetSmartTemplateTopLevelIndx(); - int tpIndx = -1; - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - if (itemInfo.IsCaution1) return false; - else tpIndx = useForTemplate.GetSmartTemplateIndex(topIndx, itemInfo.MyContent.Text); - } - else - tpIndx = useForTemplate.GetSmartTemplateIndex(topIndx, (int)useForTemplate.MyContent.Type); - if (tpIndx > -1) return true; - } - return false; - } - private float GetWidthOrStartFromTemplate(ItemInfo itemInfo, FormatInfo formatInfo, bool bGetWidth) - { - int topIndx = itemInfo.GetSmartTemplateTopLevelIndx(); - int tmplIndx = 0; - if (itemInfo.MyDocStyle.ComponentList && !itemInfo.IsHigh) - { - // The following was added so that the Calvert Alarms sequentials under the CONDITION/RESPONSE would be - // printed as 2 column (data within the template definition set the columns to 2) - if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) - { - if (itemInfo.IsSequential && itemInfo.MyParent.TemplateIndex > 0) - { - if (bGetWidth && itemInfo.MyParent.ColumnMode == 1) // 2 columns - return (ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, itemInfo.ColumnMode) - MyTab.Width); - } - tmplIndx = itemInfo.TemplateIndex; - if (tmplIndx == -1) return 0; - } - else - { - // The ComponentTable format (FNP component table as one example), uses a template - // where the items in the template below the HLS are all paragraphs (the intermediate steps - // are TitleWithTextRight). Find the ordinal of in this list to get the index. Use the ordinal - // as an offset from the HLS's index into the template. - tmplIndx = itemInfo.MyParent.Ordinal + topIndx; - if (tmplIndx < 0 || tmplIndx > formatInfo.PlantFormat.FormatData.Templates.Count - 1) return 0; - } - } - else - { - tmplIndx = itemInfo.GetSmartTemplateIndex(topIndx, (int)itemInfo.MyContent.Type); - if (tmplIndx == -1) return 0; - } - // Calvert Alarms' template defines number of columns & their width. - if (bGetWidth && formatInfo.PlantFormat.FormatData.Templates[tmplIndx].width == 0) - { - int nocol = formatInfo.PlantFormat.FormatData.Templates[tmplIndx].nocolm == 0 ? 0 : formatInfo.PlantFormat.FormatData.Templates[tmplIndx].nocolm - 1; - return ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, nocol); - } - int ncol = bGetWidth ? formatInfo.PlantFormat.FormatData.Templates[tmplIndx].width : formatInfo.PlantFormat.FormatData.Templates[tmplIndx].start; - // now convert to the units for this format. The template width data is in number of columns. - return (ncol * itemInfo.FormatStepData.Font.CharsToTwips) + (bGetWidth ? 1 : 0); // + 1 is slight adjustment so column doesn't wrap - } - private float AdjustForSectionLevelTab() - { - string sectTab = MyItemInfo.ActiveSection.MyTab.CleanText.TrimEnd(); - if (sectTab.EndsWith(".0")) return 0; - string myTab = MyItemInfo.MyTab.CleanText; - // -1 below code, +1 for '.' and -2 for standard wid of tab - // standard wid of this tab is 2 (ex: '1.') - // so adjust width if longer than normal - return (float)(sectTab.Length - 1) * 72 / (float)MyItemInfo.FormatStepData.Font.CPI; - } - private bool HasCheckOffHeading(ItemInfo itemInfo, FormatInfo formatInfo) - { - if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList.MaxIndex != 0) - { - // does this section have a check off heading? - SectionConfig sc = (itemInfo.ActiveSection != null) ? itemInfo.MyActiveSection.MyConfig as SectionConfig : null; // C2018-003 fixed use of getting the active section - if (sc != null && sc.Section_CheckoffHeaderSelection > 0) return true; - } - if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderInPagelist) return true; - return false; - } - } + yPageStart = ChildrenAbove.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + // B2017-122: if doing supinfo pagebreaks, if there should be a break on a step (not hls) that has a caution/note do it here: + if (!MyItemInfo.IsHigh && ChildrenAbove != null && ChildrenAbove.Count > 0 && MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.DoPageBreaks && MyPromsPrinter.NeedSupInfoBreak && MyItemInfo.SupInfos != null && MyItemInfo.SupInfos.Count > 0) + { + // if this has a caution/note with supinfo, that is id that needs to go in pagination list, unless it is in there. + int aboveSupinfoId = ChildrenAboveHaveSupInfo(); + if (supInfoSect != null) + { + if (supInfoSect.StepSectPageBreaksForSupInfo.Contains(aboveSupinfoId)) aboveSupinfoId = -1; + supInfoSect.StepSectPageBreaksForSupInfo.Add(MyItemInfo.SupInfos[0].ItemID); + } + MyPromsPrinter.NeedSupInfoBreak = false; + } + yPageStart = ChildrenLeft.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - /// - /// First order by stepLevel, then within a stepLevel, order by descending yLocation on page. - /// Want to find maximum y value that fits on page, i.e. put the most on page that can - /// fit which is defined by the largest yLocation - /// - public class StepLevelList : SortedDictionary> - { - public StepLevelList() - : base() - { - } - public void Add(int stepLevel, float yLocation, vlnParagraph para) - { - if (stepLevel == 0) return; - if (!this.ContainsKey(stepLevel)) - this.Add(stepLevel, new SortedDictionary()); - // using a negative for yLocation so that its in descending order: - // B2020-112: Make various adjustments to location if there are format flags used - // B2020-116: Only make the 112 change for Calvert - // B2020-151: check for SpecialCaseCalvertPagination flag instead of SpecialCase Calvert flag so only EOPs/AOPs are affected - float adjust = 0; - if (para.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination) - adjust = para.YVeryTop - para.YTop; - //if (para.MyItemInfo.MyParent.IsHigh && (para.ChildrenAbove == null || para.ChildrenAbove.Count == 0)) - //{ - // //Console.WriteLine("Adjust Add extra Line (flag) = '{0}'", para); - // adjust -= para.AdjustForXBlankW1stLevSub; - //} - //else if (para.MyParent.MyItemInfo.IsHigh && (para.MyParent.ChildrenAbove != null && para.MyParent.ChildrenAbove.Count > 0) - // && para.MyParent.ChildrenAbove[0] == para) - //{ - // //Console.WriteLine("Adjust Add extra Line (flag) = '{0}'", para); - // adjust -= para.MyParent.AdjustForXBlankW1stLevSub; - //} + // Handle the PageBreakOnStep flag for a HLS. This will put out the page break right before + // a HLS. One example of this use is for backgrounds (CALBCK). + // 'this' below is a highlevel step, and the only time that ParaBreaks[0] will == 'this' is + // when the PageBreakOnStep flag is true. + if (MyPageHelper.ParaBreaks != null && MyPageHelper.ParaBreaks.Count > 0 && + MyPageHelper.ParaBreaks[0] == this && this.MyItemInfo.FormatStepData.PageBreakOnStep)// B2017-224 Top Continue Messages Add check for PageBreakOnStep 9/26/2017 Ginna SAMGs SAG-8 Step 4 + { + ShowPageBreak(1, CheckForCompression("PageBreakOnStep/Caution/Note HLS"), "Yes", YTop - YBottomMost, yTopMargin - yBottomMargin, yTopMargin - yBottomMargin, false); + YTopMost = OutputOtherPageSteps(cb, YTopMost, yPageStart, yTopMargin, yBottomMargin); + MyPageHelper.BottomMessage.Clear(); + MyPageHelper.TopMessage = null; + MyPromsPrinter.NewPage(); + if (CompressPartOfStep) + { + MyPageHelper.YMultiplier = _SevenLinesPerInch / SixLinesPerInch; + CompressPartOfStep = false; + } + MyPageHelper.ParaBreaks.RemoveAt(0); + yPageStart = yTopMargin + YTop; + } + // The following sets the beginning/ending y location for the lines around the + // CONDITION/RESPONSE text for Calvert Alarm format + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + int tindx = MyItemInfo.TemplateIndex; + if (tindx >= 0) + { + // save this position to start drawing the alarm box lines around substeps: + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.Templates[MyItemInfo.TemplateIndex].row > 0) + MyPageHelper.AlarmYoffStart = CalculateYOffset(yPageStart, yTopMargin) - SixLinesPerInch; + else if (MyPageHelper.AlarmYoffStart > 0 && MyPageHelper.AlarmYoffEnd == 0) + MyPageHelper.AlarmYoffEnd = CalculateYOffset(yPageStart, yTopMargin) + (2 * SixLinesPerInch); + } + } + int profileDepth2 = ProfileTimer.Push(">>>> vlnParagraph.ParagraphToPdf"); + // B2020-162 - SpecialCaseCalvert flag affect single column procedures, use SpecialCaseCalvertPagination for Two Column procedures instead + if (MyItemInfo.IsSubsection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination) CalvertPrintedSubSectTitle = true; // B2020-123 + yPageStart = ParagraphToPdf(cb, yPageStart, yTopMargin, yBottomMargin); + ProfileTimer.Pop(profileDepth2); + // If the yPageStart changes by more than a small amount (pagination) in the RNO (right column), then update + // yPageStart for the AER (left column). + float yPageStartRNO = ChildrenRight.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); + if (yPageStartRNO - yPageStart > 24) // 24 is two lines + yPageStart = yPageStartRNO; + yPageStart = ChildrenBelow.ToPdf(cb, yPageStart, ref yTopMargin, ref yBottomMargin); - if (!this[stepLevel].ContainsKey(-(yLocation + adjust))) - this[stepLevel].Add(-(yLocation + adjust), para); - } - } - public class ParagraphLocations : List - { - public ParagraphLocations() - : base() - { - } - public void Add(vlnParagraph myParagraph, float yTopMost) - { - ParagraphLocation foundOverlap = FindOverlap(myParagraph); - if (foundOverlap == null) - { - this.Add(new ParagraphLocation(yTopMost, myParagraph)); - return; - } - ParagraphLocation doubleOverlap = FindOverlap(foundOverlap); - while (doubleOverlap != null) - { - doubleOverlap.Merge(foundOverlap); - this.Remove(foundOverlap); - foundOverlap = doubleOverlap; - doubleOverlap = FindOverlap(foundOverlap); - } - } + if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null) // last hls, add the 'end' message, if there is one + { + docstyle = MyItemInfo.MyDocStyle; + // if the EndForSingle format flag is set to false, then we do not print an End message if the section + // is a single column section. + //bool _skipEndMessage = MyPageHelper.MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; + // C2018-003 fixed use of getting the active section + // B2017-201 if si is null we need to get it via the ItemID + if (!(MyItemInfo.ActiveSection is SectionInfo si)) + si = SectionInfo.Get(MyItemInfo.MyActiveSection.ItemID); // MyActiveSection does not try to resolve anything - ActiveSection is call above and will resolve and set MyActiveSection + bool _skipEndMessage = (si == null || si.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One) && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle; + bool _lastSect = true; + if (si != null && si.MyActiveParent.IsSection) // is this meta/subsection. Only put end message out on last section + { + ItemInfo mysect = si as ItemInfo; + if (mysect.NextItem != null && !docstyle.End.EndMessageOnEachSubSection) _lastSect = false; + } + string myMsg = docstyle.End?.FixedMessage; + if (myMsg != null && !_skipEndMessage && _lastSect) + { + // If the flag is 0 or 1, just put the end message out right below this vlnParagraph: + float msg_yLocation = CalculateYLocation(yPageStart - YBottomMost, yTopMargin); + // use the 'flag' to position the message. + if (docstyle.End.Flag > 2) // >2 position at an absolute location defined by docstyle.End.Flag. + { + msg_yLocation = yTopMargin - (float)(docstyle.End.Flag * SixLinesPerInch); + } + float adjMsgY = 0; + if (docstyle.End.Flag < 0) // Adjust this many lines down the page. + { + adjMsgY = (float)(-docstyle.End.Flag * SixLinesPerInch); + if (msg_yLocation - adjMsgY > docstyle.Layout.FooterLength) msg_yLocation -= adjMsgY; + } + if (myMsg.Contains("{Section Number}")) myMsg = myMsg.Replace("{Section Number}", MyItemInfo.ActiveSection.DisplayNumber); + if (myMsg.Contains("%-12s")) + myMsg = myMsg.Replace("%-12s", MyItemInfo.MyProcedure.DisplayNumber.PadRight(12)); + if (yTopMargin - docstyle.Layout.PageLength >= msg_yLocation && docstyle.End.Message != null && docstyle.End.Message != "" && docstyle.End.Flag <= 2) + { + // B2018-037: adjust location of end message to bottom of page if it is too low. This occurs when data just doesn't + // fit on the page, but will locate end message at a more reasonable location. + msg_yLocation = (float)yTopMargin - (float)docstyle.Layout.PageLength; + _MyLog.WarnFormat("End Message LOW on page: {0}, {1}, {2}, Page {3}", msg_yLocation, MyItemInfo.ItemID, MyItemInfo.ShortPath, MyPageHelper.CurrentPageNumber + 1); + } + float xpos; + if ((docstyle.End.Margin ?? 0) != 0) + { + xpos = (float)docstyle.Layout.LeftMargin + (float)docstyle.End.Margin; + MyPageHelper.BottomMessage.Add(new vlnText(cb, this, myMsg, myMsg, xpos, msg_yLocation, docstyle.End.Font)); + } + else + { // Center the bottom message + float wtpm = (float)docstyle.Layout.PageWidth - (float)docstyle.Layout.LeftMargin; + //B2022-126 was using the wrong font definition to calaculate the centering position + // ** B2023-099 commented out and restored the previous calculation. This caused problems centering the END message in Ginna + // their END message prints with the Prestige Elite font but he centering calc uses Courier New + //xpos = XOffsetBox + (float)docstyle.Layout.LeftMargin + (wtpm - (myMsg.Length * docstyle.End.Font.CharsToTwips)) / 2; + xpos = XOffsetBox + (float)docstyle.Layout.LeftMargin + (wtpm - (myMsg.Length * MyItemInfo.FormatStepData.Font.CharsToTwips)) / 2; + xpos = Math.Max(xpos, XOffsetBox + (float)docstyle.Layout.LeftMargin); + vlnText vttmp = new vlnText(cb, this, myMsg, myMsg, xpos, msg_yLocation, docstyle.End.Font); + MyPageHelper.BottomMessage.Add(vttmp); + MyPageHelper.MyGaps.Add(new Gap(msg_yLocation, msg_yLocation - vttmp.Height)); + yPageStart -= (vttmp.Height + adjMsgY); + } + } + } + if (yLocalypagestart != yPageStart) DebugText.WriteLine("ToPdf-yPagestartDiff:{0},{1},{2},{3}", MyPageHelper.MyPdfContentByte.PdfWriter.CurrentPageNumber, MyItemInfo.ItemID, yLocalypagestart, yPageStart); - private ParagraphLocation FindOverlap(vlnParagraph myParagraph) - { - foreach (ParagraphLocation paraLoc in this) - if (paraLoc.Overlap(myParagraph)) - return paraLoc; - return null; - } - private ParagraphLocation FindOverlap(ParagraphLocation myParaLoc) - { - foreach (ParagraphLocation paraLoc in this) - if (paraLoc != myParaLoc && paraLoc.Overlap(myParaLoc)) - return paraLoc; - return null; - } - internal StepLevelList BuildStepLevelList(bool KeepStepsOnPage) - { - StepLevelList myList = new StepLevelList(); - foreach (ParagraphLocation paraLoc in this) - { - int level = paraLoc.StepLevel; - if (KeepStepsOnPage) - { - // B2020-116: change from checking for type 20001 to looking for a non-high sequential since some - // step types were sequential but not 20001 - bool keepBullettedTogether = paraLoc.MyParagraph.MyItemInfo.IsSubStep; - if (!paraLoc.MyParagraph.MyItemInfo.IsHigh) - { - bool AlarmPagination = paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.AlarmPagination; - if (paraLoc.MyParagraph.MyItemInfo.IsSequential) - { - if (DontBreakHere(paraLoc)) - //if (paraLoc.MyParagraph.MyItemInfo.MyPrevious == null) // First substep - level = 0; - else - level = 1; // AlarmPagination?3:1; // B2023-091: backout B2023-088 make it easier to break on a sequential for alarms - } - else if (AlarmPagination && paraLoc.MyParagraph.MyItemInfo.IsSubStep) - { - // make it harder to break on first caution or note & within a list if doing Alarm Pagination: - vlnParagraph myPara = paraLoc.MyParagraph; - if ((myPara.MyItemInfo.IsCaution || myPara.MyItemInfo.IsNote) && myPara.MyItemInfo.MyPrevious == null) level = 1; - else if (myPara.MyItemInfo.MyPrevious != null || myPara.MyItemInfo.NextItem != null) level = 2; - } - } - } - // For B2015-014, some migrated data for background documents had the TitleWithTextBelow with associated paragraphs - // as siblings rather than children. Pagination was sometimes putting the TitleWithTextBelow on one page and the - // paragraphs on next. The following code checks thse types, if in enhanced documents but not the Short Form Deviations. - if (paraLoc.MyParagraph.MyItemInfo.ActiveFormat != null - && ((paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds) - || (((paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations) - && paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.EnhancedShortFormDev)) - { - if (!paraLoc.MyParagraph.MyItemInfo.IsTitle && paraLoc.MyParagraph.MyItemInfo.MyPrevious != null && paraLoc.MyParagraph.MyItemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow") level = 0; - } - paraLoc.MyParagraph.levelForPagination = level; - myList.Add(level, paraLoc.YTop, paraLoc.MyParagraph); - } - return myList; - } - private bool DontBreakHere(ParagraphLocation paraLoc) - { - if (paraLoc.MyParagraph.MyItemInfo.MyPrevious == null) // First substep - return true; - vlnParagraph myPara = paraLoc.MyParagraph; - while (!myPara.MyItemInfo.IsHigh) - { - if (myPara.MyItemInfo.IsCaution) return true; - if (myPara.MyItemInfo.IsNote) return true; - myPara = myPara.MyParent; - } - return false; - } - } - public class ParagraphLocation - { - public override string ToString() - { - return string.Format("{0} {1} - {2} - '{3}'", this.MyParagraph.MyItemInfo.ItemID, this.StepLevel, this.YTop, this.MyParagraph.MyItemInfo.ShortPath); - } - private float _YTop; - public float YTop - { - get { return _YTop; } - set { _YTop = value; } - } - private float _YBottom; - public float YBottom - { - get { return _YBottom; } - set { _YBottom = value; } - } - private int _StepLevel; - public int StepLevel - { - get { return _StepLevel; } - set { - //if (MyParagraph.MyItemInfo.InList(97960,84472,91010)) - // Console.WriteLine("stop"); - _StepLevel = value; } - } - private vlnParagraph _MyParagraph; - public vlnParagraph MyParagraph - { - get { return _MyParagraph; } - set { _MyParagraph = value; } - } - public ParagraphLocation(float yTopMost, vlnParagraph myParagraph) - { - MyParagraph = myParagraph; - YTop = myParagraph.YVeryTop - yTopMost; - YBottom = myParagraph.YBottom - yTopMost; - StepLevel = myParagraph.MyItemInfo.StepLevel; - // B2020-115 Set a very large figure's Step Level so that pagination will happen prior to the figure. - if (myParagraph.MyItemInfo.IsFigure && myParagraph.MyParent.Height + myParagraph.Height > vlnParagraph.hMax) - { - StepLevel = 1;// Set figure as a guaranteed break location - } - } - public bool Overlap(vlnParagraph otherParagraph) - { - if (Between(otherParagraph.YTop, YTop, YBottom)) return true; - if (Between(otherParagraph.YBottom, YTop, YBottom)) return true; - if (Between(YTop, otherParagraph.YVeryTop, otherParagraph.YBottom)) return true; - if (Between(YBottom, otherParagraph.YVeryTop, otherParagraph.YBottom)) return true; - return false; - } - public static bool Between(float x, float lower, float higher) - { return x > lower && x < higher; } - public bool Overlap(ParagraphLocation otherParagraphLocation) - { - if (Between(otherParagraphLocation.YTop, YTop, YBottom)) return true; // The top is within the other - if (Between(otherParagraphLocation.YBottom, YTop, YBottom)) return true; // The bottom is within the other - if (Between(YTop, otherParagraphLocation.YTop, otherParagraphLocation.YBottom)) return true; // the other top is within this one - if (Between(YBottom, otherParagraphLocation.YTop, otherParagraphLocation.YBottom)) return true;// I believe this is unnecessary - return false; - } - public void Merge(vlnParagraph otherParagraph) - { - if (StepLevel < otherParagraph.MyItemInfo.StepLevel) MyParagraph = otherParagraph; - YTop = Math.Min(YTop, otherParagraph.YVeryTop); - YBottom = Math.Max(YBottom, otherParagraph.YBottom); - StepLevel = Math.Max(StepLevel, otherParagraph.MyItemInfo.StepLevel); - } - public void Merge(ParagraphLocation otherParagraphLocation) - { - if (StepLevel < otherParagraphLocation.StepLevel) MyParagraph = otherParagraphLocation.MyParagraph; - YTop = Math.Min(YTop, otherParagraphLocation.YTop); - YBottom = Math.Max(YBottom, otherParagraphLocation.YBottom); - StepLevel = Math.Max(StepLevel, otherParagraphLocation.StepLevel); - } - } + // if doing NotesToFootnotes (Calvert valve list format), get the bottom location so that + // footnotes will be printed after last text on page. This is used for the end of the section. + // Pages that broke within pagination logic above had footnote location set during pagination code. + if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0) + MyPageHelper.NotesToFootNotesYoffset = CalculateYLocation(yPageStart - YBottomMost, yTopMargin); + ProfileTimer.Pop(profileDepth); + return yPageStart; + } + // B2020-128: If compression flag is on RNO, see if there is an AER to the left and do the 7lpi multiplier + private bool CompressRnoWithAerToTheLeft() + { + if (!MyItemInfo.IsInRNO) return false; + foreach (vlnParagraph vPara in MyPageHelper.MyParagraphs.Values) + { + if (!vPara.Processed) + { + if (vPara.YOffset <= YOffset && vPara.CompressPartOfStep) return true; + } + } + return false; + } + private bool IsPrintedStepItemForSupInfo() + { + bool printedMySectTitle = true; + if (MyItemInfo.IsSection) + { + // see if the section title is printed. + SectionConfig sch = (MyItemInfo.ActiveSection != null) ? MyItemInfo.ActiveSection.MyConfig as SectionConfig : null; // C2018-003 fixed use of getting the active section + printedMySectTitle = (sch == null || sch.Section_PrintHdr == "Y") || !(MyItemInfo.ActiveSection as SectionInfo).HasSupInfoSteps; + printedMySectTitle &= (ShowSectionTitles && !MyItemInfo.MyDocStyle.CancelSectTitle); + } + return printedMySectTitle; + } + private int ChildrenAboveHaveSupInfo() + { + if (ChildrenAbove == null || ChildrenAbove.Count < 1) return -1; + foreach (vlnParagraph p in ChildrenAbove) + { + if (p.MyItemInfo.SupInfos != null && p.MyItemInfo.SupInfos.Count > 0) return p.MyItemInfo.SupInfos[0].ItemID; + } + return -1; + } + // Find the step that has supplemental information from this step down page until a preferred page break is found + // or a regular page break. + // It is used to determine whether there is a supinfo facing page or if there should be a blank page. + private bool FoundStepPageBreak = false; + private int GetIdThatHasSupInfoItems(ItemInfo ii, int startid) + { + if (ii == null) return -1; + FoundStepPageBreak = false; + // if this item has supinfo, return its id + if (ii.SupInfos != null && ii.SupInfos.Count > 0) return ii.SupInfos[0].ItemID; + + // see if any substeps of this item have supinfo, and if so, return the substep's id + int id = GetSubThatHasSupInfoItems(ii, startid); + if (id != -1) return id; + if (FoundStepPageBreak) return -1; // Set in GetSubThatHasSupInfoItems + + // Now go to the next item, check if it or any of its substeps have supinfo, and if so, return the id + ItemInfo sib = ii.NextItem; + id = GetIdThatHasSupInfoItemsSibNext(sib, startid); + if (id != -1) return id; + if (FoundStepPageBreak) return -1; // Set in GetIdThatHasSupInfoItemsSibNext + + // B2017-122: if this is a note or caution off substep, check if substep has supinfo: + if ((ii.IsNote || ii.IsCaution) && !ii.MyParent.IsHigh) + { + if (ii.MyParent.SupInfos != null && ii.MyParent.SupInfos.Count > 0) return ii.MyParent.SupInfos[0].ItemID; + int sbfromNC = GetSubThatHasSupInfoItems(ii.MyParent, startid); + if (sbfromNC != -1) return sbfromNC; + if (FoundStepPageBreak) return -1; // Set in GetSubThatHasSupInfoItems + } + + // Go to the parent, and find its next and check if it or any of its substeps or next steps or any of their substeps have supinfo, + // and if so, return the id. + ItemInfo par = ii.MyParent; + ItemInfo parsnxt = par.GetNext(); + //B2023-068 check if we are already at the section or procedure level + if (!par.IsSection && !par.IsProcedure && parsnxt != null) + { + par = parsnxt; + while (par != null && !par.IsSection) + { + id = GetIdThatHasSupInfoItemsSibNext(par, startid); + if (id != -1) return id; + par = par.MyParent; + ItemInfo sparsnxt = par.GetNext(); + if (!par.IsSection && sparsnxt != null) par = sparsnxt; + else return -1; + } + } + return -1; + } + + private int GetIdThatHasSupInfoItemsSibNext(ItemInfo ii, int startid) + { + while (ii != null) + { + // B2017-193 Error occured when a section in the MRU was being loaded as an iteminfo + if (!(ii.ActiveSection is SectionInfo supInfoSect)) supInfoSect = SectionInfo.Get(ii.ActiveSection.ItemID); + // if there is a pagebreak on this step section step, quit looking for supinfos. The + // break has to occur here. + if (supInfoSect.StepSectPageBreaks.Contains(ii.ItemID)) + { + FoundStepPageBreak = true; + return -1; + } + if (ii.SupInfos != null && ii.SupInfos.Count > 0) + { + // check if this is in the list of page breaks for supinfos, if not it may have one of its cautions/notes rather than its id: + if (!supInfoSect.StepSectPageBreaksForSupInfo.Contains(ii.SupInfos[0].ItemID)) + { + if (ii.Cautions != null) + { + foreach (ItemInfo caution in ii.Cautions) + if (caution.SupInfos != null && caution.SupInfos.Count > 0 && supInfoSect.StepSectPageBreaksForSupInfo.Contains(caution.SupInfos[0].ItemID)) return caution.SupInfos[0].ItemID; + } + if (ii.Notes != null) + { + foreach (ItemInfo note in ii.Notes) + if (note.SupInfos != null && note.SupInfos.Count > 0 && supInfoSect.StepSectPageBreaksForSupInfo.Contains(note.SupInfos[0].ItemID)) return note.SupInfos[0].ItemID; + } + } + return ii.SupInfos[0].ItemID; + } + int id = GetSubThatHasSupInfoItems(ii, startid); + if (id == -2) return -1; + if (id != -1) return id; + ii = ii.NextItem; + } + return -1; + } + private int GetSubThatHasSupInfoItems(ItemInfo ii, int startid) + { + if (ii.MyContent.ContentParts != null) + { + if (!(ii.ActiveSection is SectionInfo supInfoSect)) supInfoSect = SectionInfo.Get(ii.ActiveSection.ItemID); + foreach (PartInfo pi in ii.MyContent.ContentParts) + { + if ((E_FromType)pi.FromType != E_FromType.SupInfo) + { + foreach (ItemInfo iic in pi.MyItems) + { + // B2018-021: added code to be sure that check isn't on current step, i.e. startid != iic.ItemID & + // flag when the following page break is found so the next supplemental information page isn't printed + // on a step where the step is on the following page from the one we are looking for. + if (startid != iic.ItemID) + { + if (supInfoSect.StepSectPageBreaks.Contains(iic.ItemID)) + { + FoundStepPageBreak = true; + return -1; + } + if (iic.SupInfos != null && iic.SupInfos.Count > 0) return iic.SupInfos[0].ItemID; + int id = GetSubThatHasSupInfoItems(iic, startid); + if (id != -1) return id; + } + } + } + } + } + return -1; + } + private float GetSectionTopMessageSize() + { + // B2016-134: Account for wcntraining section top continue if item has container + float retval = 0; + if (MyItemInfo.MyDocStyle.SectTop != null && MyItemInfo.MyDocStyle.SectTop.Message != null) + { + if (PartsContainer != null && PartsContainer.Count > 0) retval = SixLinesPerInch * 1; + } + return retval; + } + // For WCNTRN (Wolf Creek Training format): the following prints the section number (and continued, if + // section is continued from previous page) in the Responsibility column. + private bool SectionTopMessage(PdfContentByte cb, float yTopMargin) + { + if (MyPageHelper.CreatingSupInfoPage) + { + float scttopWidths = "Supplemental Information".Length * 6; + float ctrs = ((float)MyItemInfo.MyDocStyle.Layout.PageWidth - (float)MyItemInfo.MyDocStyle.Layout.LeftMargin) / 2; + float sctcntrXs = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ctrs - (scttopWidths / 2); + VE_Font vf = MyItemInfo.MyDocStyle.Font; + // F2017-039: The following null check was added in case the format's doc style does not have a font defined: + if (vf == null || vf.Style == null || vf.Family == null || vf.Size == null || vf.CPI == null) vf = MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font; + E_Style sty = E_Style.Underline; + if (vf != null && vf.Style != null) sty = (E_Style)(vf.Style | E_Style.Underline); + vf = new VE_Font(vf.Family, (int)vf.Size, sty, (float)vf.CPI); + MyPageHelper.TopMessage = new vlnText(cb, this, "Supplemental Information", "Supplemental Information", sctcntrXs, yTopMargin + 0.1F, vf); + return true; + } + bool addextra = false; + if (MyItemInfo.MyDocStyle.SectTop != null && MyItemInfo.MyDocStyle.SectTop.Message != null) + { + float sectMsgY; + if (PartsContainer == null || PartsContainer.Count == 0) + sectMsgY = CalculateYLocation(YTop, yTopMargin); + else + { + // B2016-134: Account for section top continue if item has container, i.e. move section top continue message above the container + sectMsgY = CalculateYLocation(YTopMost - (SixLinesPerInch * 3), yTopMargin); // 3 is # of lines: header, box, blank line moving up page + addextra = true; + } + VE_Font sctMsgFont = MyItemInfo.MyDocStyle.SectTop.Font; + string scttop; + if (!MyItemInfo.IsStepSection && MyItemInfo.MyDocStyle.SectTop.Message != null) + scttop = MyItemInfo.MyDocStyle.SectTop.Message.Replace("%s", (MyItemInfo.ActiveSection as SectionInfo).DisplayNumber); + else + scttop = (MyItemInfo as SectionInfo).DisplayNumber; + float scttopWidth = scttop.Length * 6; + float ctr = (float)MyItemInfo.MyDocStyle.SectTop.Margin; + float sctcntrX = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ctr - (scttopWidth / 2); + vlnText mySectMsg = new vlnText(cb, this, scttop, scttop, sctcntrX, sectMsgY, sctMsgFont); + PartsLeft.Add(mySectMsg); + } + return addextra; + } + // Added to try to resolve a problem when printing FNP-1-FRP-I.3 Attachment 3 Table 1. + // May be needed to evaluate this problem in the future. + //private void CompareSectionInfo(SectionInfo si, SectionInfo si1) + //{ + // if (si.ItemID != si1.ItemID) + // Console.WriteLine("Different"); + // if (si.ActiveFormat.FullName != si1.ActiveFormat.FullName) + // Console.WriteLine("Different"); + // if (si.ActiveParent != si1.ActiveParent) + // Console.WriteLine("Different"); + // if (si.ActiveSection.ItemID != si1.ActiveSection.ItemID) + // Console.WriteLine("Different"); + // if (si.MyDocStyle.Name != si1.MyDocStyle.Name) + // Console.WriteLine("Different"); + //} + private void AddFootNote(PdfContentByte cb) + { + // for calvert valve lists footnotes, if there is footnote data, save it for vlnSvgPageHelper + // which puts the footnotes out when page is printed. + List myNotes = MyPageHelper.NotesToFootNotesHLS[MyItemInfo.ItemID]; + foreach (int myNote in myNotes) + { + ItemInfo inote = StepInfo.Get(myNote); + + // first check if this exact text is already in the foot note list. If it is + // in there, don't add it. + bool inlist = false; + if (MyPageHelper.NotesToFootNotes != null) + { + foreach (vlnParagraph vp in MyPageHelper.NotesToFootNotes) + { + if (vp.MyItemInfo.MyContent.Text == inote.MyContent.Text) + { + inlist = true; + break; + } + } + } + if (!inlist) + { + vlnParagraph vpFNote = new vlnParagraph(null, cb, inote, (float)MyItemInfo.MyDocStyle.Layout.LeftMargin, 0, 0, 0, MyItemInfo.ActiveFormat, null, null, 0, false, MyPromsPrinter) + { + Width = (float)MyItemInfo.MyDocStyle.Layout.PageWidth - (float)MyItemInfo.MyDocStyle.Layout.LeftMargin, + Height = 0, + XOffset = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + }; + if (MyPageHelper.NotesToFootNotes == null) MyPageHelper.NotesToFootNotes = new List(); + MyPageHelper.NotesToFootNotes.Add(vpFNote); + } + } + MyPageHelper.NotesToFootNotesHLS.Remove(MyItemInfo.ItemID); + } + private bool DoTopContinueMsg(PdfContentByte cb, ref float yPageStart, float yTopMargin, DocStyle docstyle, string subTab) + { + bool addExtraLine = false; + if ((bool)docstyle.Continue.Top.UseStepTabs) + { + // UseStepTabs is a format flag added for Comanche Peak to print out step tabs as + // a top comtinue message. This code will go up through parents putting out + // their tabs - at this y location, but at the tabs' x location + vlnParagraph myPar = this; + MyPageHelper.TopMessageRs = new List(); + while (!myPar.MyItemInfo.IsHigh) + { + myPar = myPar.MyParent; + foreach (vlnPrintObject vpo in myPar.PartsLeft) + { + if (vpo is vlnTab) + { + vlnTab vt = vpo as vlnTab; + string cltxt = vt.Text; + // replace C# representation of unicode character "\u25CF" which is hex + // with the rtf representation @"\u9679?" + if (cltxt.Contains("\u25CF")) cltxt = cltxt.Replace("\u25CF", @"\u9679?"); // handle a bullet, if it isn't unicode yet + float msgTopMargin = yTopMargin; + // B2017-106: if caution/note move the message up a little so it doesn't touch the caution/note lines: + if (MyItemInfo.IsNote || MyItemInfo.IsCaution) msgTopMargin += 4; + // B2018-140: if table move the message up a little so it doesn't touch the table lines: + if (MyItemInfo.IsTable) msgTopMargin += 6; + MyPageHelper.TopMessageRs.Add(new vlnText(cb, this, cltxt, cltxt, vt.XOffset, msgTopMargin, vt.MyFont)); + } + else if (vpo is vlnText) // As of 6/22/15, CP wants the step designator in the continue message also. + { + vpo.YOffset = yTopMargin; + int nlcnt = 1; // number of lines to adjust the yoffset for the next step designator we are adding to TopMessageRs + string rtxt; + int istr; + int Rsidx; + MyPageHelper.TopMessageRs.Add(vpo as vlnText); // this appends a previous step designator associated with this sub-step (there may be more than one and/or might have multiple lines) + // we are processing the step designator on the top continue message in reverse order + // we therefore need to adjust the y location of multiple step designors attached tothe top continue message + if (MyPageHelper.TopMessageRs.Count > 3) + { + Rsidx = MyPageHelper.TopMessageRs.Count - 1; + rtxt = MyPageHelper.TopMessageRs[Rsidx].Text; + // find the number of lines to shift existing TopMessageRs step designators down + istr = rtxt.IndexOf("\\line", 0); + while (istr != -1) + { + nlcnt++; + istr = rtxt.IndexOf("\\line", istr + 1); + } + // move the previous TopMessageRs step designators down + Rsidx -= 2; // index to the previous step desginator + while (Rsidx > 0) + { + MyPageHelper.TopMessageRs[Rsidx].YOffset -= (nlcnt * SixLinesPerInch); + Rsidx -= 2;// every other TopMessageRs is a step designator + } + } + // for Comanche Peak - if step breaks on a sub-step, and both the high level step and the sub-step have a step designator + // then since the high level step and its step designator are printed as part of the top continue message, + // move the step designator associated with the sub-step down so that it does not print on top of the + // ones in the top continue message. + if (this.PartsLeft.Count > 1) // was a step designator printed for the sub-step? + { + // count the number of lines in the step designator text in the top continue message + nlcnt = 0; // reset for the number of lines to push the sub-step's step designator down + Rsidx = MyPageHelper.TopMessageRs.Count - 1; // note that TopMessageRs[0] is a tab not a step designator + while (Rsidx > 0) + { + nlcnt++; + rtxt = MyPageHelper.TopMessageRs[Rsidx].Text; + istr = rtxt.IndexOf("\\line", 0); + while (istr != -1) + { + nlcnt++; + istr = rtxt.IndexOf("\\line", istr + 1); + } + Rsidx -= 2; // every other TopMessageRs is a step designator + } + if (nlcnt > 0) + { + for (int idx = 1; idx < this.PartsLeft.Count; idx++) + { + vlnPrintObject vpol = this.PartsLeft[idx]; + vpol.YOffset += (nlcnt * SixLinesPerInch); // move the existing step designator down + } + } + } + } + } + } + return false; + } + + string myMsg = docstyle.Continue.Top.Message; + MyPageHelper.TopMessageRs = new List(); + // bug fix B2106-099 + // when there are more than one Caution/Note off of a high level background step, + // the second, third, etc background Caution/Note pages begin printing two additional lines from the top of the page + // to fix, added a check to see the the item we are printing has the PageBrrakOnStep flag set, if it's set, + // then DON'T add two lines to the yPageStart (for the top conitnue message) + if (myMsg != null && myMsg != "" && !MyItemInfo.IsSection && !MyItemInfo.FormatStepData.PageBreakOnStep) // B2020-123 + { + // C2019-044 for BNPP put the top continue message on the same row as the Checkoff/Signoff header + // This is done by specifing a row positon in the top continue definition in the format. + // If the top continue messsage RowOverride is being used, don't move the yPageStart down (don't need to make room for it) + if (docstyle.Continue.Top.RowOverride == null) + yPageStart -= 2 * SixLinesPerInch;// Allow two lines for top continue message + if (myMsg.IndexOf(@"%sR") > -1) + { + ItemInfo myAer = MyItemInfo.IsHigh ? MyItemInfo : MyItemInfo.MyParent; + if (MyItemInfo.IsInRNO) + { + // If this is an RNO part, find the parent that is not an RNO (the reason for this is + // that RNO parts are structured as parent/child not sibling relationships, for + // example, RNO part 1.2 is the child of 1.1 not sibling). Also, if this is a caution + // or note of the RNO part, do the same because it should not use the RNO part's tab. + // However, the RNO Part will have the combined tab using its parent because this is + // needed if any of its children, for example substeps, need the combined tab. + if (((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.IsRNOPart) || MyItemInfo.IsRNOPart) + { + ItemInfo ip = MyItemInfo.MyParent; + while (ip.IsRNOPart) ip = ip.MyParent; + myMsg = myMsg.Replace(@"%sR", ip.CombinedTab); + } + // B2020-154: Incorrect top continue message tab in RNO column if for single level substep with a Caution/Note + else if ((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.MyParent.IsRNOPart) + { + if (DebugPagination.IsOpen) DebugPagination.WriteLine("***===>,'Yes','Case 1:Changed RNO Continue Message',{0},{1},,{3},'{4}'", MyItemInfo.ItemID, YSize, 0, 0, this); + ItemInfo ip = MyItemInfo.MyParent; + while (!ip.IsRNOPart) ip = ip.MyParent; + myMsg = myMsg.Replace(@"%sR", ip.CombinedTab); + } + // B2020-154: Incorrect top continue message tab in RNO column for substep with a Caution/Note within parent substeps + else if ((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.MyParent.IsInRNO) + { + if (DebugPagination.IsOpen) DebugPagination.WriteLine("***===>,'Yes','Case 2:Changed RNO Continue Message',{0},{1},,{3},'{4}'", MyItemInfo.ItemID, YSize, 0, 0, this); + myMsg = myMsg.Replace(@"%sR", MyItemInfo.MyParent.MyParent.CombinedTab); + } + else + myMsg = myMsg.Replace(@"%sR", MyItemInfo.MyParent.CombinedTab); + float xor = MyTopRNO.MyTab.XOffset; + MyPageHelper.TopMessageRs.Add(new vlnText(cb, this, myMsg, myMsg, xor, yTopMargin + 0.1F, docstyle.Continue.Top.Font)); + // get aer message, go up parent until find aer and use its combined tab: + myAer = MyItemInfo; + while (myAer.IsInRNO) myAer = myAer.MyParent; + } + else if (!MyItemInfo.IsHigh && (MyItemInfo.IsNote || MyItemInfo.IsCaution)) + { + ItemInfo ip1 = MyItemInfo.MyParent; + if (!ip1.IsHigh) myAer = ip1.MyParent; + } + myMsg = docstyle.Continue.Top.Message.Replace(@"%sR", myAer.CombinedTab); + } + if (myMsg.IndexOf(@"%s") > -1) + { + if (MyItemInfo.MyParent.IsSection && (docstyle.StructureStyle.Style & E_DocStructStyle.BottomSectionContinue) == E_DocStructStyle.BottomSectionContinue) + myMsg = myMsg.Replace(@"%s", MyItemInfo.MyParent.MyTab.CleanText.Trim()); + else + { + // F2020-023: tab includes parent tab and if caution/note don't use its parent, go up another level + string noBullet = MyItemInfo.IsCautionOrNotePart ? MyItemInfo.MyParent.MyParent.CombinedTab : MyItemInfo.MyParent.CombinedTab; + // F2026-002 Vogtle Units 3&4, don't include the RNO sub-step tab if the parent is an AER sub-step + if (docstyle.Continue.Top.DontIncludeRNOTabIfHasAERParent && MyItemInfo.MyParent.IsRNOPart && !MyItemInfo.MyParent.MyParent.IsRNOPart) + noBullet = MyItemInfo.MyParent.MyParent.CombinedTab; + // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. + // B2021-085 & 087: crash if noBullet was null. Also, if null, see if text in parent. if no text, replace the + // "%s." with noBullet (null) which won't put out just a '.' as step number. + if (docstyle.Continue.Top.RemoveBullet) + { + if (noBullet == null && MyItemInfo.IsCautionOrNotePart) noBullet = MyItemInfo.MyParent.CombinedTab; + if (noBullet != null) + { + int ind = noBullet.IndexOf(".o"); + if (ind < 0) ind = noBullet.IndexOf(".*"); + if (ind > -1) noBullet = noBullet.Substring(0, ind); + } + else + { + myMsg = myMsg.Replace(@"%s.", noBullet); + } + } + myMsg = myMsg.Replace(@"%s", noBullet); + } + } + if (myMsg.IndexOf(@"%3d") > -1) + myMsg = myMsg.Replace(@"%3d", MyItemInfo.MyHLS.Ordinal.ToString()); + if (myMsg.IndexOf(@"%2d") > -1) + myMsg = myMsg.Replace(@"%2d", MyItemInfo.MyHLS.MyTab.CleanTextNoSymbols.Trim(" .".ToCharArray()).PadLeft(2)); + if (myMsg.IndexOf(@"%d") > -1) + myMsg = myMsg.Replace(@"%d", MyItemInfo.MyHLS.MyTab.CleanTextNoSymbols.Trim(" .".ToCharArray())); + if (myMsg.IndexOf(@"%c") > -1) + myMsg = myMsg.Replace(@"%c", " "); + + // Top Continue message includes high level step tab and text + if ((docstyle.Continue.Top.HLS ?? 0) == 1) + { + myMsg = docstyle.Continue.Top.Message; // reset because we did replace strings in code above + ItemInfo parentStep = MyItemInfo.MyHLS; // get the high level step + myMsg = string.Format(myMsg, parentStep.CombinedTab, parentStep.DisplayTextKeepSpecialChars); + } + // B2023-115 Top continue message for Vogtle Alarms: 1st version done on 12/6/23. Changes to logic as per request + // from engineering done on 12/12/23. See comment below for logic for 12/12/23 (history of this file has previous + // logic) + if (((docstyle.Continue.Top.HLS ?? 0) == 4) || ((docstyle.Continue.Top.HLS ?? 0) == 7)) + { + // Vogtle Alarms: Their alarms are set up differently than standard procedures - the HLS in Vogtle + // alarms is a section in other procedures. The top continue message is shown when a break occurs: + // • A continued message will appear on the top of the page ONLY if the pagination occurs anywhere + // within the first level substep. If, for example, the page break occurs between substep 3 and substep + // 4 as in example 2, no continued message will appear on the top of the page. + // • If a continued message is needed, the continued message will include the first level substep number + // if it is a sequential substep, such as “5. (continued)”. If it is NOT a sequential substep, then only + // the word “(continued)” will appear. + // • If a page break occurs between high level steps, such as before “Causes:”, then no continued message is needed. + + // F2024-027 & F2024-028 + // Vogtle Units 3&4 needed similar top continue messages in the Local Alarms attachments as they have for the MCR Alarm point pages + // with the exception that when High Level Step (grouping text) is split and continued to the next page, the top continue message + // needs to be the HLS text with "(continued)" appended to it. + // Added a TOP.HLS value of 7 to allow for this minor difference and is set in the docstyle for that section + + bool doMessage = true; + if (MyItemInfo.IsHigh) doMessage = false; // at high, don't do message + if (MyItemInfo.MyParent.IsHigh) doMessage = false; // at first level, don't do message + // Caution/Note on first level, don't do message + if ((MyItemInfo.IsCaution || MyItemInfo.IsNote) && MyItemInfo.MyParent.MyParent.IsHigh) doMessage = false; + myMsg = docstyle.Continue.Top.Message; + if (doMessage) + { + // Get to highest level below HLS + ItemInfo cur = MyItemInfo; + while (!cur.MyParent.IsHigh) cur = cur.MyParent; + // if sequential, add on step number, otherwise just put out message: + myMsg = !cur.IsSequential ? myMsg : $"{cur.CombinedTab}. {myMsg}"; + } + // F2024-027 & F2024-028 added else if to check of the case where we want to use the High Level Step text in the top continue message + else if (((docstyle.Continue.Top.HLS ?? 0) == 7) && MyItemInfo.MyParent != null && MyItemInfo.MyParent.IsHigh) + { + myMsg = $"{MyItemInfo.MyParent.DisplayText} {myMsg}"; + } + else // if not doing message, clear it & set yPageStart back to what it was before handling message + { + myMsg = ""; + yPageStart += 2 * SixLinesPerInch; + } + } + // B2021-138: Top continue message for Barakah Single column New (2021) format was incorrect for some lower + // sub-steps. + if ((docstyle.Continue.Top.HLS ?? 0) == 6) + { + myMsg = docstyle.Continue.Top.Message; // reset because we did replace strings in code above + ItemInfo parentStep = MyItemInfo.MyHLS; + string ctab = parentStep.CombinedTab; + if (!MyItemInfo.MyParent.IsHigh) // If lower sub-step, get parent substep tab, skipping caution/note if in one of those + ctab = (MyItemInfo.IsInCautionOrNote) ? MyItemInfo.MyParent.MyParent.CombinedTab : MyItemInfo.MyParent.CombinedTab; + myMsg = string.Format(myMsg, ctab, parentStep.DisplayTextKeepSpecialChars); + } + // Calvert Alarms, step description have the alarm number as part of the top continue message + // Also, if the break is within the CONDITION/RESPONSE, there are continue messages in both columns at the top + // of the table, note that the continue messages WITHIN table are only printed when the + // steplevel is greater than 2 - this is from 16bit. + // NOTE THAT this code is not complete - the positioning & addition of step tab for within table are not working correctly + if ((docstyle.Continue.Top.HLS ?? 0) == 3) + { + MyPageHelper.TopMessageSub1s = new List(); + MyPageHelper.TopMessageSub2s = new List(); + + string tabText = @"\ul\b " + MyHighLevelParagraph.MyItemInfo.MyTab.CleanText.Trim() + @"\b0\ulnone"; + // B2017-185: added the replace of unicode dash to regular dash for the continue message so it matches the step text: + string stepText = @"\b " + MyHighLevelParagraph.MyItemInfo.MyContent.Text.Replace(@"\u8209?", "-") + @"\b0"; + vlnText vt1 = new vlnText(cb, this, tabText, tabText, MyHighLevelParagraph.MyTab.XOffset, yTopMargin + 0.1F, docstyle.Continue.Top.Font) + { + Width = MyHighLevelParagraph.MyTab.Width + }; + MyPageHelper.TopMessageRs.Add(vt1); + vlnText vt2 = new vlnText(cb, this, stepText, stepText, MyHighLevelParagraph.XOffset, yTopMargin + 0.1F, docstyle.Continue.Top.Font) + { + Width = MyHighLevelParagraph.Width + }; + MyPageHelper.TopMessageRs.Add(vt2); + + // the following code is used to print the top continue messages in the Calvert Alarm format + // CONDITION/RESPONSE table. Messages only get printed if the break is on a substep at steplevel > 2. + // see comments within code for what the tab contains, it varies depending on which side + // break occurred & how deep in the step the break occurred. + if (subTab != null && MyItemInfo.StepLevel > 2) + { + bool incond = !MyItemInfo.IsInRNO; + float ybot = yTopMargin + (4 * SixLinesPerInch); + string concatrnoTab = ""; // constructed tab for Response side + string concataerTab = ""; // constructed tab for Condition side + float xoffTab; // position for Response tab + float xoffMsg; // position for Response message + vlnParagraph useAerParaForTab; // use this paragraph under Conditions for locating tab & message + if (incond) + { + // If break is in Condition side of table, use Condition tab of parent & no tab for Response side. + // Both sides have the message '(continued)'. + useAerParaForTab = MyParent; + concataerTab = MyParent.MyTab != null ? MyParent.MyTab.Text.TrimEnd() : ""; + xoffTab = 0; // no rno tab + xoffMsg = ToInt(MyItemInfo.ActiveFormat.MyStepSectionLayoutData.ColRTable, 1) + (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ((useAerParaForTab != null && useAerParaForTab.MyTab != null) ? useAerParaForTab.MyTab.Width : 7.2f); + } + else + { + // break occurred in Response side. Use the tabs up to highest RNO concatenated together. + vlnParagraph useRnoParaForTab = MyParent; + vlnParagraph useParaForTab = MyParent; + while (useParaForTab.MyItemInfo.IsInRNO) + { + concatrnoTab = (useParaForTab.MyTab != null ? useParaForTab.MyTab.Text.TrimEnd() : "") + concatrnoTab.Trim(); + if (concatrnoTab.Length > 0 && concatrnoTab[0] > '\xff') concatrnoTab = ""; + useRnoParaForTab = useParaForTab; + useParaForTab = useParaForTab.MyParent; + } + xoffTab = useRnoParaForTab.MyTab.XOffset; + xoffMsg = useRnoParaForTab.XOffset; + + // aer message when rno broke. Need to concatenate up the Condition side also until + // hitting 1st non-sequential, i.e. moves out of Condition/Response table. + useAerParaForTab = useParaForTab; // useParaForTab is 1st found non-Response step, i.e. moved into Condition side of table + while (useParaForTab.MyItemInfo.IsSequential) + { + concataerTab = (useParaForTab.MyTab != null ? useParaForTab.MyTab.Text.TrimEnd() : "") + concataerTab.Trim(); + useAerParaForTab = useParaForTab; + useParaForTab = useParaForTab.MyParent; + } + } + // For RNO tab, add a vlntext for tab and one for continue message: + float xoff1 = xoffMsg; + if (!incond) + { + vlnText vtc = new vlnText(cb, this, concatrnoTab, concatrnoTab, xoffTab, ybot, docstyle.Continue.Bottom.Font); + MyPageHelper.TopMessageSub1s.Add(vtc); + if ((vtc.IParagraph.Chunks[0]) is Chunk chk) + { + float xoff2 = xoffTab + chk.GetWidthPoint() + 6; + // If the "(continue)" is going to overlap the tab, then move the "Continue)" so that it doesn't overlap. + if (xoff2 > xoff1) xoff1 = xoff2; + } + } + MyPageHelper.TopMessageSub1s.Add(new vlnText(cb, this, myMsg, myMsg, xoff1, ybot, docstyle.Continue.Bottom.Font)); + + // for aer tab, add a vlntext for tab and one for continue message: + MyPageHelper.TopMessageSub2s.Add(new vlnText(cb, this, concataerTab, concataerTab, useAerParaForTab.MyTab.XOffset, ybot, docstyle.Continue.Bottom.Font)); + MyPageHelper.TopMessageSub2s.Add(new vlnText(cb, this, myMsg, myMsg, useAerParaForTab.XOffset, ybot, docstyle.Continue.Bottom.Font)); + addExtraLine = true; + } + } + if (!PageBreakOnStep) + { + float colPos = docstyle.Layout.LeftMargin + docstyle.Continue.Top.Margin ?? 0; + if (!docstyle.Continue.Top.PlaceAtLeftMargin) //F2019-033 when true position with respect only to the left margin + colPos += XOffsetBox; //XOffsetbox get set when the tables, figures & equations were beyond the border and needed repositioned + // C2019-044 for BNPP, put the top continue message on the same row as the checkoff/signoff heading + // RowOverride specifies the position of the top continue message + // For BNPP, RowOverride is set to the same row as the checkoff header is set to in the pagelist + if (docstyle.Continue.Top.RowOverride != null) + { + float adjRowPosition = (float)docstyle.Layout.TopMargin - (float)docstyle.Continue.Top.RowOverride; + MyPageHelper.TopMessage = new vlnText(cb, this, myMsg, myMsg, colPos, yTopMargin + 0.1F + adjRowPosition, docstyle.Continue.Top.Font);// MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font); + } + else + MyPageHelper.TopMessage = new vlnText(cb, this, myMsg, myMsg, colPos, yTopMargin + 0.1F, docstyle.Continue.Top.Font);// MyItemInfo.ActiveFormat.PlantFormat.FormatData.Font); + + } + else + MyPageHelper.TopMessage = null; + } + return addExtraLine; + } + + private void DoBottomContinueMsg(PdfContentByte cb, float yBottomMargin, float yLocation, DocStyle docstyle, bool doThreeContinues) + { + // Console.WriteLine("Page {0} - yLocation {1}", cb.PdfWriter.PageNumber, yLocation); + string myMsg = docstyle.Continue.Bottom.Message; + + // a format flag exists that states to only put a BOTTOM message if it is a certain type (RNO) + // check for this.... + bool RNOContinueOnly = MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly; + bool doBottom = !RNOContinueOnly || (MyItemInfo.IsInRNO && RNOContinueOnly); + if (doBottom && myMsg != null && myMsg != "") + { + myMsg = ReplaceStepBottomContinue(myMsg); + float msg_yLocation = 0; + if (myMsg.Contains("{par}")) + { + myMsg = myMsg.Replace("{par}", ""); + msg_yLocation = -SixLinesPerInch; + } + float yBtmMarginForMsg = yBottomMargin; + + // one of the format flags for FNP had an adjustment for printing the section title only + // on the first page of the section. Adjust the location of the bottom continue message + // if this adjustment was made (the current topmargin may not reflect the value within + // the document style) + if (MyPageHelper.PrintedSectionPage > 0) + { + if (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PrintSectOnFirst) == E_DocStructStyle.DSS_PrintSectOnFirst) // C2018-003 fixed use of getting the active section + { + float localYTopMargin = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize) - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.TopMargin; // C2020-002 paper size is now set in the format files + yBtmMarginForMsg = Math.Max(0, localYTopMargin - (float)MyItemInfo.ActiveSection.MyDocStyle.Layout.PageLength); + } + } + // include space for phone list when determining bottom continue message location + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.PrintPhoneList && MyPageHelper.PhoneListHeight != 0) + yBtmMarginForMsg += (MyPageHelper.PhoneListHeight - vlnPrintObject.SixLinesPerInch); + // B2019-079: Account for compression when locating the bottom continue message + if (MyPageHelper.YMultiplier != 1) + { + //float topOfPage = PDFPageSize.PaperSizePoints(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PDFPageSize.PaperSize) - (float)MyItemInfo.MyDocStyle.Layout.TopMargin; // A4 paper logic + float topOfPage = 792 - (float)MyItemInfo.MyDocStyle.Layout.TopMargin; + yLocation = topOfPage - (topOfPage - yLocation) * MyPageHelper.YMultiplier; + } + switch (docstyle.Continue.Bottom.Location) + { + case E_ContBottomLoc.EndOfText: // place continue string at end of text + // msg_yLocation accounts for extra lines in message from docstyle; and BottomContent is the actual + // location of the last line of text on page. + // B2019-079 changed yLocaton - msg_yLocation to '+'. The msg_ylocation has an adjustment for adding an extra line by moving down the page, this was moving + // the line up the page (double negative). + msg_yLocation = yLocation + msg_yLocation - (SixLinesPerInch * MyPageHelper.YMultiplier); //B2019-021 yLocation accounts for checkoffs + if (yBottomMargin + (docstyle.Layout.FooterLength ?? 0) > msg_yLocation) + { // Adjusted Continue Message Y Offset + //DebugPagination.WriteLine("====>> {0},'{1}'", msg_yLocation, MyItemInfo.ShortPath); + float msg_yLocationOld = msg_yLocation = yBottomMargin + (docstyle.Layout.FooterLength ?? 0); + if (MyPageHelper.BottomContent != null) + msg_yLocation = Math.Min(yBottomMargin + (docstyle.Layout.FooterLength ?? 0), (float)MyPageHelper.BottomContent - SixLinesPerInch);// RHM20150525 - Table Scrunch + if (msg_yLocationOld != msg_yLocation) + _MyLog.WarnFormat("Continue Message Moved from {0} to {1} for {2}", msg_yLocationOld, msg_yLocation, this);// RHM20150525 - Table Scrunch + } + break; + case E_ContBottomLoc.BtwnTextAndBottom: // place continue string between end of text & bottom of page + msg_yLocation = msg_yLocation + yLocation - ((yLocation - yBottomMargin) / 2); // +SixLinesPerInch; // (need this for IP3) + msg_yLocation = Math.Max(msg_yLocation, yBottomMargin + SixLinesPerInch); + break; + case E_ContBottomLoc.BottomOfPage: // place continue message at bottom of page + msg_yLocation = msg_yLocation + yBtmMarginForMsg + (float)docstyle.Layout.FooterLength; + break; + case E_ContBottomLoc.BelowBottom1: + msg_yLocation += yBtmMarginForMsg; + break; + case E_ContBottomLoc.BottomWithFooter: // put bottom message AND if in CONDITION/RESPONSE table, in both columns. + msg_yLocation += yBtmMarginForMsg; + break; + case E_ContBottomLoc.EndOfText2: // Like EndOfText but limited within yBottomMargin + msg_yLocation = Math.Max(msg_yLocation + yLocation - SixLinesPerInch, yBottomMargin + SixLinesPerInch); + break; + case E_ContBottomLoc.BtwnTextAndBottom2: + // Like BtwnTextAndBottom but accounts for line spacing of step & is 1 line up on page (for BGE - Procedure Steps - 2 column) + float adj = (!MyItemInfo.IsSection && MyItemInfo.FormatStepData.StepLayoutData.EveryNLines == 1) ? SixLinesPerInch : 0; + msg_yLocation = msg_yLocation + yLocation - ((yLocation - yBottomMargin) / 2) + adj;// +SixLinesPerInch; + if (msg_yLocation < yBottomMargin) msg_yLocation = yBottomMargin; + break; + default: + _MyLog.WarnFormat("**** BOTTOM CONTINUE MESSAGE NOT CODED FOR LOCATION {0}*****", docstyle.Continue.Bottom.Location); + break; + } + if (!PageBreakOnStep) + { + float xoffB; + // Added for Calvert Alarms: if 'doThreeContinues', continue message at bottom of page + // and a continue message at the bottom of each column. + if (doThreeContinues) + { + float ybot = yLocation; + xoffB = (float)docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; + MyPageHelper.BottomMessageA = new vlnText(cb, this, myMsg, myMsg, xoffB, ybot, docstyle.Continue.Bottom.Font); + xoffB = docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.MarginR ?? 0; + MyPageHelper.BottomMessageR = new vlnText(cb, this, myMsg, myMsg, xoffB, ybot, docstyle.Continue.Bottom.Font); + MyPageHelper.AlarmYoffEnd -= SixLinesPerInch; + float tmp = (((float)docstyle.Layout.PageWidth - (float)docstyle.Layout.LeftMargin) / 2) - (myMsg.Length / 2 * 5); + xoffB = (float)docstyle.Layout.LeftMargin + tmp; + } + else if (docstyle.Continue.Bottom.Location == E_ContBottomLoc.BottomWithFooter) + { + float tmp = (((float)docstyle.Layout.PageWidth - (float)docstyle.Layout.LeftMargin) / 2) - (myMsg.Length / 2 * 5); + xoffB = (float)docstyle.Layout.LeftMargin + tmp; + } + else if (RNOContinueOnly) + { + float colR = float.Parse(MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColRTable.Split(",".ToCharArray())[MyItemInfo.ColumnMode]); + xoffB = colR + docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; + } + else if (MyItemInfo.IsInRNO && (docstyle.Continue.Bottom.MarginR ?? 0) > 0) + { + xoffB = (float)docstyle.Layout.LeftMargin + (float)docstyle.Continue.Bottom.MarginR; + MyPageHelper.BottomMessageR = new vlnText(cb, this, myMsg, myMsg, xoffB, msg_yLocation, docstyle.Continue.Bottom.Font); + xoffB = (float)docstyle.Layout.LeftMargin + (float)docstyle.Continue.Bottom.Margin; + + } + // FloatingContinueMessage format flag: + // if breaking at the AER put continue message in left column, + // if breaking RNO put continue message in Right column. + else if (MyItemInfo.IsInRNO && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.FloatingContinueMessage) + { + float colR = float.Parse(MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColRTable.Split(",".ToCharArray())[MyItemInfo.ColumnMode]); + xoffB = colR + docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; + } + else + xoffB = docstyle.Layout.LeftMargin + docstyle.Continue.Bottom.Margin ?? 0; + MyPageHelper.BottomMessage.Clear(); // B2017-207 should be only one continue message - was putting an extra continue message in middle of page for V.S.Summer (ex. AOP set, 900.4 Attachment 12) + MyPageHelper.BottomMessage.Add(new vlnText(cb, this, myMsg, myMsg, xoffB, msg_yLocation, docstyle.Continue.Bottom.Font)); + } + } + if (PageBreakOnStep) MyPageHelper.BottomMessage.Clear(); + } + + private void RefreshDocStyle() + { + MyItemInfo.ActiveSection = null; + MyItemInfo.MyDocStyle = null; + MyPageHelper.MySection = MyItemInfo as SectionInfo; + MyPageHelper.ResetSvg(); + MyPageHelper.PrintedSectionPage = 0; + } + + private string ReplaceStepBottomContinue(string myMsg) + { + string tb; + if (MyItemInfo.IsSection) + tb = MyItemInfo.MyTab.CleanText.Trim(); + else + tb = MyItemInfo.MyHLS.MyTab.CleanTextNoSymbols; + // if the tab ends with .0, remove it if it was added because of the virtualdotinhls flag. + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.VirtualDotInHLSTab && tb.Contains(".0")) tb = tb.Replace(".0", ""); + if (myMsg.IndexOf(@"%d") > -1) + myMsg = myMsg.Replace(@"%d", tb.Trim()); + if (myMsg.IndexOf(@"%0d") > -1) + myMsg = myMsg.Replace(@"%0d", tb.Trim(" .".ToCharArray())); + if (myMsg.IndexOf(@"%2d") > -1) + myMsg = myMsg.Replace(@"%2d", tb.Trim(" .".ToCharArray()).PadLeft(2)); + if (myMsg.IndexOf(@"%3d") > -1) + myMsg = myMsg.Replace(@"%3d", MyItemInfo.MyHLS.Ordinal.ToString()); + // F2020-023: tab includes parent tab and if caution/note don't use its parent, go up another level + if (myMsg.IndexOf(@"%s") > -1) // %s was added for F2020-023 + { + string tmp = tb.Trim(); + if (!MyItemInfo.MyParent.IsHigh) + { + tmp = MyItemInfo.IsCautionOrNotePart ? MyItemInfo.MyParent.MyParent.CombinedTab : MyItemInfo.MyParent.CombinedTab; + // C2021-024: WCN1 if bullet exists in combined tab, stop right before bullet. + // B2021-085 & 087: crash if noBullet was null. Also, if null, see if text in parent. if no text, replace the + // "%s." with noBullet (null) which won't put out just a '.' as step number. + if (MyItemInfo.MyDocStyle.Continue.Bottom.RemoveBullet) + { + if (tmp == null && MyItemInfo.IsCautionOrNotePart) tmp = MyItemInfo.MyParent.CombinedTab; + if (tmp != null) + { + int ind = tmp.IndexOf(".o"); + if (ind < 0) ind = tmp.IndexOf(".*"); + if (ind > -1) tmp = tmp.Substring(0, ind); + } + else + { + myMsg = myMsg.Replace(@"%s.", tmp); + } + } + } + myMsg = myMsg.Replace(@"%s", tmp); + } + return myMsg; + } + private vlnParagraph TopMostChild => ChildrenAbove.Count > 0 ? ChildrenAbove[0].TopMostChild : this; + private bool EmptyTopMostPart + { + get + { + if (TopMostChild.PartsAbove.Count == 0) return false; + if (TopMostChild.PartsContainer != null && TopMostChild.PartsContainer.Count > 0) return false; // B2016-198: not 'EmptyTopMostPart' if there is a box. + foreach (vlnPrintObject po in TopMostChild.PartsAbove) + { + if (!(po is vlnHeader hd)) return false; + if (hd.Text != "") return false; + } + return true; + } + } + + public float TableBottom { get; set; } = -1; + private float OutputOtherPageSteps(PdfContentByte cb, float YTopMost, float yPageStart, float yTopMargin, float yBottomMargin) + { + // B2019-115 Locate Bottom Continue Message below AER Table if necessary - Initialize TableBottom to -1 + TableBottom = -1; + float retval = YTopMost; + // Find any items remaining in MyPageHelper.MyParagraphs that should be printed on this page. + vlnParagraphs process = new vlnParagraphs(null); + int processed = 0; + foreach (vlnParagraph vPara in MyPageHelper.MyParagraphs.Values) + { + if (!vPara.Processed) + { + if (vPara.MyItemInfo.IsTable && (vPara.YOffset <= YTopMost) && vPara.MyItemInfo.ActiveSection.ColumnMode > 0 && vPara.Height + yBottomMargin < yPageStart - vPara.YOffset) //B2019-120 Byron ELEC-1 step 3 second table was not printing on following page + { + if (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID) + { + // B2019-115 Locate Bottom Continue Message below AER Table if necessary + _MyLog.WarnFormat("\r\n=-=-=> Table Print on First Page {0} {1} ColumnMode = {2}", vPara.MyItemInfo.ItemID, vPara.MyItemInfo.ShortPath, vPara.MyItemInfo.ActiveSection.ColumnMode); + process.Add(vPara); + // Console.WriteLine("Table YOffset {0} height {1} Bottom = {2} yPageStart = {3} Bottom {4}", vPara.YOffset, vPara.Height, vPara.YOffset + vPara.Height - yPageStart, yPageStart, this.YBottom); + } + } + else if (((vPara.YOffset + vPara.Height) < YTopMost)) + { + // B2019-028: Added check for active section in next line so that following section text doesn't overlap or start too far down on page for case where there is a subsection + // with subsections of type Step/Word/Step + if (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID) + { + // B2019-077: 2.0 SCOPE empty section not printing for WES (revert to previous code line versus above) + process.Add(vPara); + } + else // 20150701 Complicated RNO change + _MyLog.WarnFormat("Less Than: Step Could Have Fit {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); + } + else if (((vPara.YOffset + vPara.Height) == YTopMost)) + { + + if (this.MyItemInfo.ItemID != vPara.MyItemInfo.ItemID) + { + process.Add(vPara); + _MyLog.WarnFormat("New AerRno PageBreak Logic: Step Could Have Fit {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); + } + else // RHM20150507 Table Scrunch + _MyLog.WarnFormat("Equal: Step Could Have Fit {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); + } + else if (((vPara.YOffset) < YTopMost)) + { + retval = Math.Min(retval, vPara.YTopMost); + } + } + else + processed++; + } + //Console.WriteLine("~~~ {0} has {1} Steps {2} Processed {3} to Process", MyItemInfo.ShortPath, MyPageHelper.MyParagraphs.Count + // , processed,process.Count); + foreach (vlnParagraph vPara in process) + { + vPara.ParagraphToPdf(cb, yPageStart, yTopMargin, yBottomMargin); + // B2019-115 Locate Bottom Continue Message below AER Table if necessary + if (vPara.MyItemInfo.IsTable) + { + if (TableBottom == -1) + TableBottom = (yPageStart - vPara.YOffset) - vPara.Height - SixLinesPerInch; + else + TableBottom = Math.Min(TableBottom, (yPageStart - vPara.YOffset) - vPara.Height - SixLinesPerInch); + } + } + return retval; + } + private float _YVeryTop = -1; + public float YVeryTop + { + get + { + if (_YVeryTop == -1) + { + _YVeryTop = YTop; + _YVeryTop = VeryTop(PartsAbove, _YVeryTop); + _YVeryTop = VeryTop(PartsContainer, _YVeryTop); + } + return _YVeryTop; + } + } + + private float VeryTop(vlnPrintObjects parts, float yVeryTop) + { + if (parts != null) + foreach (vlnPrintObject part in parts) + if (part.YOffset < yVeryTop) + yVeryTop = part.YOffset; + return yVeryTop; + } + /// + /// This gets the height of the step with it's Caution's, Notes and potentially any First Substeps + /// + /// + // F2024-006: Vogtle Alarms pagination - added 'includeFirstSub' to get that size of the first substep with the parent step + // to help determine pagination + private float GetFirstPieceSize(bool includeFirstSub = false) + { + vlnParagraph paraLast = GetFirstPieceLastPart(includeFirstSub); + float retval = (paraLast.YBottom) - YTopMost; + //Console.WriteLine(MyItemInfo.DBSequence); + return retval; + } + public override float YBottom + { + get + { + float bottom = YOffset + Height; + if (PartsBelow != null) + { + foreach (vlnPrintObject part in PartsBelow) + { + float partBottom = part.YBottom; + bottom = Math.Max(partBottom, bottom); + } + } + return bottom; + } + } + public float YVeryBottom + { + get + { + float bottom = YOffset + Height; + if (ChildrenBelow != null) + foreach (vlnParagraph child in ChildrenBelow) + bottom = Math.Max(child.YVeryBottom, bottom); + if (ChildrenLeft != null) + foreach (vlnParagraph child in ChildrenLeft) + bottom = Math.Max(child.YVeryBottom, bottom); + if (ChildrenRight != null) + foreach (vlnParagraph child in ChildrenRight) + bottom = Math.Max(child.YVeryBottom, bottom); + if (PartsBelow != null) + foreach (vlnPrintObject part in PartsBelow) + bottom = Math.Max(part.YBottom, bottom); + return bottom; + } + } + public float YBottomText => YOffset + Height; + + public float YBottomForBox { get; set; } = 0; + // F2024-006: Vogtle Alarms pagination - added 'includeFirstSub' to get that size of the first substep with the parent step + // to help determine pagination - even when PaginateOnFirstSubstep is turned on + private vlnParagraph GetFirstPieceLastPart(bool includeFirstSub = false) + { + vlnParagraph para = this; + if ((!MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PaginateOnFirstSubstep || includeFirstSub) && ChildrenBelow != null && ChildrenBelow.Count > 0) + { + // If the substep has a separator (OR, AND) then return the last substep rather than the first. + string mySep = ChildrenBelow[0].MyItemInfo.FormatStepData.Sep ?? "{Null}"; + if (mySep != "{Null}" && mySep != "") + para = ChildrenBelow[ChildrenBelow.Count - 1].GetFirstPieceLastPart(); + else + { + // MNS Pagination - Mike Weiner Case 1a to keep step together with any non-sequential substeps (ANDs, EQ List) + bool keepEqListTogether = ChildrenBelow[0].MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PutOnPageByItself; + if (keepEqListTogether && !ChildrenBelow[0].MyItemInfo.IsSequential && !this.MyItemInfo.IsHigh) // Extend to the last Item. + para = ChildrenBelow[ChildrenBelow.Count - 1].GetFirstPieceLastPart(); + else + para = ChildrenBelow[0].GetFirstPieceLastPart(includeFirstSub); + } + } + if (ChildrenRight != null && ChildrenRight.Count > 0) + { + foreach (vlnParagraph paraRight in ChildrenRight) + { + vlnParagraph paraRightLast = paraRight.GetFirstPieceLastPart(includeFirstSub); + if (paraRightLast.YBottom > para.YBottom) + para = paraRightLast; + } + } + return para; + } + /// + /// Find items from previous page (yLocation less than yTop) and remove them from the list. + /// yTop is the new starting location on the next page for this step. + /// + /// + /// + private void RemoveProcessedParagraphs(StepLevelList myList, float yTop) + { + // the two CleanUpLists are used to remove items from + // the original list because list items cannot be removed in a + // 'foreach'. + List CleanupListStepLevel = new List(); + foreach (int stepLevel in myList.Keys) + { + List CleanupListYLocation = new List(); + SortedList AdjustYLocation = new SortedList(); + foreach (float yLocation in myList[stepLevel].Keys) + { + if (-yLocation <= yTop) + CleanupListYLocation.Add(yLocation); + else + AdjustYLocation.Add(-yLocation, yLocation); // order in ascending order + } + foreach (float yLocation in CleanupListYLocation) + myList[stepLevel].Remove(yLocation); + foreach (float yLocation in AdjustYLocation.Keys) + { + vlnParagraph para = myList[stepLevel][-yLocation]; + myList[stepLevel].Remove(-yLocation); + // shift yLocation by yTop to work with items whose locations + // are defined from the top of the new page rather than + // from the beginning of the step. + // Note that yLocation is negative to have items in descending + // order so that adding yTop decrements their values. + if (!myList[stepLevel].ContainsKey(yTop - yLocation)) + myList[stepLevel].Add(yTop - yLocation, para); + } + if (myList[stepLevel].Count == 0) + CleanupListStepLevel.Add(stepLevel); + } + foreach (int stepLevel in CleanupListStepLevel) + myList.Remove(stepLevel); + } + /// + /// Builds a list of paragraphs by StepLevel and yLocation in descending order. + /// + /// + /// + private void BuildLocationList(float yTopMost, ParagraphLocations myLocations) + { + foreach (vlnParagraph child in ChildrenAbove) + child.BuildLocationList(yTopMost, myLocations); + foreach (vlnParagraph child in ChildrenLeft) + child.BuildLocationList(yTopMost, myLocations); + + // Add a list entry consisting of StepLevel, yoffset from the beginning of this step, paragraph itself + myLocations.Add(this, yTopMost); + + foreach (vlnParagraph child in ChildrenRight) + child.BuildLocationList(yTopMost, myLocations); + foreach (vlnParagraph child in ChildrenBelow) + child.BuildLocationList(yTopMost, myLocations); + } + private readonly int COL_WID_ADJ = 6; // adjusts for incorrect use of WidSTable when breaking a line (it breaks 6 chars too short) + + private static readonly VlnFlexGrid _MyFlexGrid = new VlnFlexGrid(1, 1); + public static VlnFlexGrid MyFlexGrid => _MyFlexGrid; + + public pkParagraph MyPlaceKeeper { get; set; } = null; + public pkParagraph MyContAct { get; set; } = null; + public pkParagraph MyTimeCriticalAction { get; set; } = null; + public static bool InList(int id, params int[] ids) + { + foreach (int listid in ids) + if (id == listid) return true; + return false; + } + + public bool PrefixSpecialCharacter { get; set; } = false; + public string Prefix { get; set; } + public string Suffix { get; set; } + private float RoughSizeOfPage => (float)(MyItemInfo.MyDocStyle.Layout.PageLength /*- MyItemInfo.MyDocStyle.Layout.TopMargin*/ - MyItemInfo.MyDocStyle.Layout.FooterLength); + + public PromsPrinter MyPromsPrinter { get; set; } + public static float _yPageStartForSupInfo = 0; + public vlnParagraph(vlnParagraph parent, PdfContentByte cb, ItemInfo itemInfo, float xoff, float yoff, int rnoLevel, int maxRNO, FormatInfo formatInfo, string prefix, string suffix, float yoffRightParent, bool loadChildren, PromsPrinter pp) + { + MyPromsPrinter = pp ?? parent.MyPromsPrinter; + int profileDepth = ProfileTimer.Push(">>>> vlnParagraph"); + Prefix = prefix; + Suffix = suffix; + MyItemInfo = itemInfo; + MyContentByte = cb; + if (itemInfo.IsFootnote && loadChildren) + { + // notestofootnoteshls is a list, a hls can have more than one note + if (MyPageHelper.NotesToFootNotesHLS.ContainsKey(itemInfo.MyHLS.ItemID)) + MyPageHelper.NotesToFootNotesHLS[itemInfo.MyHLS.ItemID].Add(itemInfo.ItemID); + else + { + List notesList = new List + { + itemInfo.ItemID + }; + MyPageHelper.NotesToFootNotesHLS.Add(itemInfo.MyHLS.ItemID, notesList); + } + Processed = true; // don't want to print during normal ToPdf/ParagraphToPdf cycle - print in vlnsvgpagehelper + ProfileTimer.Pop(profileDepth); + return; + } + // do some 'setup' for Calvert Alarms: + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + // The CONDITION/RESPONSE portion of the alarm uses a macro to print the 'table' heading, + // i.e. the lines/boxes and text for CONDITION and RESPONSE. This does not have a tab, + // tabs are where the macros are usually stored, so flag this for future reference. + // The 2nd if is executed when the step is at the same y offset as the parent, i.e. DEVICE & SETPOINT text. + if (itemInfo.TemplateIndex > 0 && itemInfo.ActiveFormat.PlantFormat.FormatData.Templates[itemInfo.TemplateIndex].hmacro > 0) + HasCalvertMacro = true; + if (KeepOnParentLine(itemInfo)) yoff = parent.YOffset; + } + float yOffOrig = yoff; + // Save step text information to be used to create a PlaceKeeper (Calver Cliffs) + BuildPlacekeeper(parent, itemInfo); + + // Save step text information to be used to create a Continuous Action Summary + if (MyPromsPrinter.ShouldPrint_CAS_CTAS) BuildContinuousActionSummary(parent, itemInfo); + + // F2022-024 Time Critical Step + // Save step text information to be used to create a Time Critical Action Summary + if (MyPromsPrinter.ShouldPrint_CAS_CTAS) BuildTimeCriticalActionSummary(parent, itemInfo); + + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.BoxLeftAdj != null) + _MyBoxLeftAdj = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.BoxLeftAdj); + ShowSectionTitles = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ShowSectionTitles || itemInfo.MyDocStyle.ShowSectionTitles; + if (itemInfo.IsSection && itemInfo.ActiveSection.DisplayText.ToUpper().Contains("") && !itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.PrintNoTitle) ShowSectionTitles = false; + HasIndent = itemInfo.IsStep && itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.DontResetIndentOnNewline; + + int MetaLevel = 0; // if meta section, stores what level this section is. + float savCheckListBottomMost = 0; + //int[] problemIDs = { 889 }; + //List lProblemIDs = new List(problemIDs); + //if (lProblemIDs.Contains(itemInfo.ItemID)) + // Console.WriteLine("Found Item {0}", itemInfo.ItemID);formatInfochecko + MyParent = parent; + // The following code determines the last paragraph for an RNO + // MyTopRNO finds the Top paragraph for an RNO + if (itemInfo.IsInRNO) + { + if (rnoLevel <= maxRNO && itemInfo.IsRNOPart) // Not top level RNO + MyTopRNO = this; + else + MyTopRNO = MyParent.MyTopRNO; + if (MyTopRNO != null) MyTopRNO.LastRNO = this; + } + if (!MyPageHelper.MyParagraphs.ContainsKey(itemInfo.ItemID) && !itemInfo.IsFootnote) + { + MyPageHelper.MyParagraphs.Add(itemInfo.ItemID, this); + } + + XOffset = xoff; + if (!MyItemInfo.IsStep && !MyItemInfo.IsStepSection && MyItemInfo.MyContent.MyEntry != null) + { + IsWordDocPara = true; + // special case - this is a 'Word Doc' paragraph. The Processed flag is used to know + // that steps need put out on a page for the pagination logic, and since there are no steps + // we don't want to have to worry about putting this out for pagination logic. + Processed = true; + ProfileTimer.Pop(profileDepth); + return; + } + YTopMost = YOffset = yoff; + vlnTab mytab = null; + bool doSectTab = false; + // if this substep has a caution or note as its parent, then there may have been a special indent done on the + // substep... check the CautionOrNoteSubstepIndent value, this is the additional indent amount in number + // of characters. + if (itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote) + { + // if this is a Note or Caution off of a Note or Caution (Catawba EG/1A/CSAM/SACGR1 step 1) + // then indent it the length of its tab + if (itemInfo.IsCaution || itemInfo.IsNote) + XOffset += (!itemInfo.IsBackgroundStep()) ? (itemInfo.FormatStepData.TabData.IdentPrint.Length - 1) * 6 : 0; // B2018-139 don't adjust XOffset when processing a Caution, or Note background text is is off of Caution or Note WCN BG SAG-10 step 4 + + else + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) + XOffset = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset); + else + XOffset += 72 * (itemInfo.FormatStepData.CautionOrNoteSubstepIndent == null ? 0 : (float)itemInfo.FormatStepData.CautionOrNoteSubstepIndent / (float)itemInfo.FormatStepData.Font.CPI); + } + + if (itemInfo.IsStep && itemInfo.MyHLS != null && itemInfo.MyHLS.FormatStepData.UseSmartTemplate && + itemInfo.FormatStepData.StepLayoutData.AlignWithParentTab + || (itemInfo.Steps != null && itemInfo.Steps.Count > 0 && itemInfo.Steps[0].FormatStepData.StepLayoutData.AlignWithParentTab)) + itemInfo.MyTab = null; + + float xMetaAdj = 0; + + if (itemInfo.IsFootnote) itemInfo.MyTab = null; + + if (itemInfo.IsSupInfoPart) XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + + //if (itemInfo.MyTab != null && itemInfo.MyTab.Text != null && itemInfo.MyTab.Text != "") + // bug fix - if the section does not have a section number, then we need to build an empty tab for the itemInfo + // so that we place the section title in the correct location. so we need to go into this IF code block + // even if itemInfo has a MyTab that is an empty string when itemInfo is a section - 2/11/2015 + if (itemInfo.MyTab != null && itemInfo.MyTab.Text != null && (itemInfo.MyTab.Text != "" || itemInfo.IsSection)) + { + float localXOffset = XOffset; + bool doprint = true; + if (itemInfo.IsSection) + { + MyItemInfo.ActiveSection = null; + MyItemInfo.MyDocStyle = null; + DocStyle ds = MyItemInfo.MyDocStyle; + + if (!ds.ComponentList && ShowSectionTitles + && !MyItemInfo.MyDocStyle.CancelSectTitle + && !MyItemInfo.MyDocStyle.SpecialStepsFoldout) // Don't ouput the Step Section title + { + if (MyItemInfo.MyConfig is SectionConfig sch && sch.Section_PrintHdr != "Y") + { + doprint = false; + YTopMost = 0; + } + } + else + doprint = false; + } + // if printing the supplemental info facing page, don't put out the section title. ToPdf will put out 'Supplemental Information' title. + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && MyPageHelper.CreatingSupInfoPage && itemInfo.IsSection) doprint = false; + if (doprint && itemInfo.IsSection && !itemInfo.MyDocStyle.CancelSectTitle && (itemInfo.MyConfig as SectionConfig).Section_IsFoldout != "Y") //C2019-042 Section_IsFoldout checks Section Number, Section Title, and use of check box + { + doSectTab = true; + if (itemInfo.IsStepSection && formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Just.Contains("PSLeft")) + { + float offset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + if (formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos != null) + { + ItemInfo iilvl = itemInfo; + while (!iilvl.IsProcedure) + { + // see if this metasection, walking up the tree, has its header printed, + // if so, indent for it. + SectionConfig sch1 = iilvl.MyConfig as SectionConfig; + if (sch1.Section_PrintHdr == "Y" || MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.UseMetaSections) + MetaLevel++; + iilvl = iilvl.MyParent; + } + + if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + { + if (MetaLevel == 1) + offset += (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + else + { + SectionConfig sc = itemInfo.MyParent.MyConfig as SectionConfig; + if (MyParent != null) + { + // if the parent is not printed, then adjust the xoffset based on + // the level of the metasection. Note that the 'if (MetaLevel==20) MetaLevel = 1' + // line of code was added so that the xoffsets between 16 & 32 bit are closer. + // This code was added to fix problems in BGE OI34, Appendix sections/subsection xoffsets. + if (sc != null && sc.Section_PrintHdr == "N") + { + if (MetaLevel == 2) MetaLevel = 1; + xMetaAdj = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[0].ColSByLevel; + for (int i = 0; i < MetaLevel; i++) + { + xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[i].SecNumPositionAdj; + } + offset += xMetaAdj; + } + else + { + offset = (sc != null && sc.SubSection_AutoIndent == "Y") ? MyParent.XOffset + : (MyParent.MyTab != null) ? MyParent.MyTab.XOffset : XOffset; + } + } + } + } + else + { + + MetaLevel = MetaLevel <= 2 ? 1 : MetaLevel - 1; + if (MetaLevel == 1) + offset += (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + else + { + xMetaAdj = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[0].ColSByLevel; + for (int i = 0; i < MetaLevel; i++) + { + xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + xMetaAdj += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[i].SecNumPositionAdj; + + } + offset += xMetaAdj; + itemInfo.MyTab.Text = itemInfo.MyTab.Text.TrimEnd(" ".ToCharArray()); + itemInfo.MyTab.CleanText = itemInfo.MyTab.CleanText.TrimEnd(" ".ToCharArray()); + if (((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_SameXOffSubsections) == E_DocStructStyle.DSS_SameXOffSubsections)) + offset += (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + } + } + } + localXOffset = offset; + } + } + if (!itemInfo.IsSection || doSectTab) + { + if (itemInfo.IsSupInfoPart) // get combined tab if on a supinfo facing page: + mytab = GetSupInfoTab(cb, itemInfo, yoff, doSectTab, localXOffset); + else if (itemInfo.MyTab.AltPrintTab != null) + mytab = new vlnTab(cb, this, itemInfo.MyTab.AltPrintTab, itemInfo.MyTab.AltPrintTab, localXOffset, yoff, itemInfo.MyTab.MyFont, doSectTab, StepRTB.MySymbolFontName, itemInfo.MyTab.RemovedStyleUnderline); + else + { + string clntxt = itemInfo.MyTab.CleanText; + if (!string.IsNullOrEmpty(itemInfo.FormatStepData?.TabData?.MacroEditTag) && itemInfo.FormatStepData.TabData.MacroEditTag == "_" && clntxt.StartsWith("_")) + clntxt = clntxt.Substring(1); + mytab = new vlnTab(cb, this, itemInfo.MyTab.Text, clntxt, localXOffset, yoff, itemInfo.MyTab.MyFont, doSectTab, StepRTB.MySymbolFontName, itemInfo.MyTab.RemovedStyleUnderline); + } + PartsLeft.Add(mytab); + if (mytab.MyMacro != null) PartsLeft.Add(mytab.MyMacro); + } + } + else if (itemInfo.IsSupInfoPart) // if it was an empty tab - it may have been a caution/note + { + mytab = GetSupInfoTab(cb, itemInfo, yoff, doSectTab, XOffset); + PartsLeft.Add(mytab); + } + // if this is the High Level RNO step (MyTopRNO) and we are numbering the RNO, adjust the xoffset to start the tab + // at the x location rather than starting the text at the x location: + AdjustWidth(itemInfo, maxRNO, formatInfo, mytab); + bool adjustAgain = ((itemInfo.MyTab != null && itemInfo.MyTab.Position == 0) || (itemInfo.MyPrevious != null && itemInfo.MyPrevious.FormatStepData != null && itemInfo.MyPrevious.FormatStepData.TabData.IsTransition)); + if (!itemInfo.IsSection && itemInfo.FormatStepData.NumberHighLevel && itemInfo.IsRNOPart && (MyTopRNO == null || itemInfo.ItemID == MyTopRNO.MyItemInfo.ItemID)) + { + // adjust the x-offset of the RNO to include the tab. + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthSameAsHighParent) + { + vlnParagraph hls = GetHighLevelParagraph(); + float RnoOffset1 = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); + float offset = hls.Width + RnoOffset1 + hls.XOffset; +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Kept for Debugging + vlnTab tb = hls.MyTab; +#pragma warning restore IDE0059 // Unnecessary assignment of a value + if (MyTopRNO == null) + Width -= (float)itemInfo.ActiveFormat.MyStepSectionLayoutData.SingleColumnRNOIndent; + offset -= Width; + float inc = offset - XOffset; + if (mytab != null) + mytab.XOffset += inc;// +(itemInfo.MyParent.IsHigh ? 6.8f : 0); + XOffset += inc; + adjustAgain = false; + } + else if (itemInfo.FormatStepData.AdjHighLevelTab != null && itemInfo.ColumnMode > 0) + // For Farley (only plant format to use AdjHighLevelTab), determine the xoffset based on + // where the right edge of the text is. Their RNO's are numbered with parent numbering + // so the calculations for determining the xoffset backs up from the right edge. + { + float rightTextEdge = this.MyHighLevelParagraph.XOffset + this.MyHighLevelParagraph.Width; + int colRx = int.Parse(formatInfo.MyStepSectionLayoutData.ColRTable.Split(",".ToCharArray())[itemInfo.ColumnMode]); + rightTextEdge += (colRx + (itemInfo.FormatStepData.AdjHighLevelTab ?? 0)); + float diff = rightTextEdge - (XOffset + Width); + if (mytab != null) mytab.XOffset += diff; + XOffset += diff; + adjustAgain = false; + } + else if (mytab != null) + { + float adjusttab = (itemInfo.MyParent.IsHigh) ? itemInfo.FormatStepData.AdjHighLevelTab ?? 0 : 0; + mytab.XOffset += (mytab.Width + adjusttab); + XOffset = mytab.XOffset + mytab.Width; + if (adjusttab != 0) Width += (mytab.Width); + } + } + if (adjustAgain) + { + AdjustXOffsetForTab(itemInfo, maxRNO, formatInfo, mytab, xMetaAdj); + // Used in Ginna's Attachment format. + // if the Note/Caution is off of a sub-step, then adjust the width so that the Caution/Note text box does not extend past the HLS text box + if (itemInfo.IsCautionOrNotePart && maxRNO == 0 && (itemInfo.ActiveSection != null && itemInfo.ActiveSection.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.LimitCautionNoteWidthToHLS)) // C2018-003 fixed use of getting the active section + { + float wMax = MyHighLevelParagraph.Width + MyHighLevelParagraph.XOffset - XOffset; + if (wMax < Width && (Width + XOffset > MyItemInfo.MyDocStyle.Layout.PageWidth)) Width = wMax; + } + } + + if (itemInfo.IsSection && MyParent == null && itemInfo.MyDocStyle.SupplementalInformation && MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge) + { + _SupInfoSection = new vlnParagraph(this, cb, itemInfo, xoff, yoff, rnoLevel, maxRNO, formatInfo, null, null, yoffRightParent, false, pp); + MyPromsPrinter.SupInfoPdfPageCount = -1; + } + // For Calvert Alarms: if within the CONDITION/RESPONSE table, indent by 1 character. + // Sequential substeps are ok because of the tab string, but items without a tab & other step + // types were writing over the CONDITION/RESPONSE vertical table line. This code uses + // 7.2 for the character size to match 16bit output. + if (itemInfo.IsStep && !itemInfo.IsSequential && !itemInfo.IsCaution && !itemInfo.IsNote && MyParent.HasCalvertMacro) + { + XOffset += 7.2f; + if (mytab != null) mytab.XOffset += 7.2f; + } + if ((itemInfo.IsCaution || (itemInfo.IsNote && !itemInfo.IsFootnote)) && (itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) + { + if (itemInfo.IsInRNO) + { + XOffset = MyTopRNO.MyTab != null ? MyTopRNO.MyTab.XOffset : MyTopRNO.XOffset; + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - 10; + } + else + { + XOffset = MyHighLevelParagraph.MyTab.XOffset; + Width = MyHighLevelParagraph.MyTab.Width + MyHighLevelParagraph.Width - 6; // make width 1/2 char smaller so it doesn't touch line + } + } + if (UseTemplateWidthOrXOff(itemInfo)) + { + float txoff = GetWidthOrStartFromTemplate(itemInfo, itemInfo.ActiveFormat, false); + if (txoff > 0) XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + txoff; // GetWidthOrStartFromTemplate(itemInfo, itemInfo.ActiveFormat, false); + } + if (itemInfo.MyHeader != null && itemInfo.MyHeader.Text != null && !doSectTab) + yoff += SetHeader(this, cb, itemInfo, formatInfo); + else if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.SeparateBox && itemInfo.FirstSibling.MyHeader != null && itemInfo.FirstSibling.MyHeader.Text != null) + yoff += SetHeader(this, cb, itemInfo.FirstSibling, formatInfo); + float yoffLeft = yoff; + if (ChildrenAbove != null) + ChildrenAbove.StepDesignator = null; //reset StepDesignator + if (DoSubs && itemInfo.Cautions != null && (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || itemInfo.Cautions[0].FormatStepData.Type != "Caution1") && !(itemInfo.IsCaution || itemInfo.IsNote)) + { + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format) + { + // For deviations, the Cautions are always in the same place. + // Fix for Catawba E-1 deviation for step 10. Has note/caution off of a paragraph instead of HLS + if (loadChildren) yoffLeft = ChildrenLeft.Add(cb, itemInfo.Cautions, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); + } + else + { + if (yoffRightParent > yoff && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) != E_DocStructStyle.DoubleBoxHLS)) yoff = yoffRightParent; + if (loadChildren) yoff = ChildrenAbove.Add(cb, itemInfo.Cautions, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); + } + } + if (DoSubs && itemInfo.Notes != null && !(itemInfo.IsCaution || itemInfo.IsNote)) + { + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.Dev_Format) + { + // For deviations, the Cautions are always in the same place. + // Fix for Catawba E-1 deviation for step 10. Has note/caution off of a paragraph instead of HLS + float xoffDev = (float)itemInfo.MyDocStyle.Layout.LeftMargin + 6 + (float)(itemInfo.ActiveFormat.MyStepSectionLayoutData.WidT); + if (loadChildren) yoffLeft = Math.Max(yoffLeft, ChildrenLeft.Add(cb, itemInfo.Notes, xoffDev, yoff, yoff, rnoLevel, maxRNO, formatInfo)); + } + else + { + // Notes/Cautions span the page. If the right (RNO) column is below current yoff, use the + // yoff from this. Without this, an overlap of text between the note and the bottom of the + // RNO was occurring for FNP - Unit 2/AOP, AOP-4.0. + if (yoffRightParent > yoff && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) != E_DocStructStyle.DoubleBoxHLS)) yoff = yoffRightParent; + if (loadChildren) + { + float yoffadj = 0; + if (itemInfo.IsTable && MyFlexGrid.BorderStyle == C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None && !MyFlexGrid.TopRowHasBorder()) + yoffadj = SixLinesPerInch; // adjust the yoffset if the note is off of a borderless table + yoff = ChildrenAbove.Add(cb, itemInfo.Notes, xoff, yoff + yoffadj, yoff + yoffadj, rnoLevel, maxRNO, formatInfo) - yoffadj; + } + } + } + if (itemInfo is StepInfo && ((itemInfo as StepInfo).MyConfig as StepConfig).Step_PreferredPagebreak) HasPrefPageBreak = true; + // The following adds supplemental information items to the SupInfoSection list off of the section level paragraph for printing + // of the sup info pdf. The SupInfoSection list is just a flat list of all supplemental information within the section. + if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && loadChildren && itemInfo.SupInfos != null) + { + SupInfoSection.ChildrenBelow.Add(cb, itemInfo.SupInfos, XOffset, 0, 0, rnoLevel, maxRNO, formatInfo); + } + + // Without the following, BGE had gaps in y-direction if the AER/RNO both had cautions/notes. + // The only time this needs done is if caution/notes are printed in separate columns in dual + // column mode (used the DoubleBoxHLS BGE flag for this - if another plant needs this, make it + // a more generic flag). + if (itemInfo.IsRNOPart && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS) && + rnoLevel == maxRNO && ChildrenAbove.Count > 0 && MyParent.ChildrenAbove.Count > 0) + { + float yDeltaRno = yoff - yOffOrig; + float yDeltaAer = SixLinesPerInch + yOffOrig - MyParent.ChildrenAbove[0].YTopMost; + if (yDeltaRno > yDeltaAer) + { + foreach (vlnParagraph chlda in MyParent.ChildrenAbove) + { + chlda.AdjustYOffset(yDeltaAer - yDeltaRno); + } + foreach (vlnParagraph chld in ChildrenAbove) + chld.AdjustYOffset(yDeltaAer); + yoff -= yDeltaAer; + } + else + { + foreach (vlnParagraph chld in ChildrenAbove) + chld.AdjustYOffset(yDeltaRno); + yoff -= yDeltaRno; + } + } + // Comanche Peak uses CAUTION2 type to enter a Step Designator, which is placed to the left of the step number. + // The Step Designator information is saved during the processing of the Cautions (ChildrenAbove) + // defined in the vlnParagraphs class (of which ChildrenAbove is defined) + if (ChildrenAbove.StepDesignator != null) + { + string pref = ChildrenAbove.StepDesignator; + float colOvrd = (float)(ChildrenAbove.StepDesignatorColumn ?? 0); + float xPref = (colOvrd > 0) ? colOvrd : mytab.XOffset - (pref.Length * (72 / (float)MyItemInfo.FormatStepData.Font.CPI)); + PartsLeft.Add(new vlnText(cb, this, pref, pref, xPref, yoff, ChildrenAbove.StepDesignatorFont)); + ChildrenAbove.StepDesignator = null; + ChildrenAbove.StepDesignatorColumn = null; + } + DoAnnotationPrintableText(cb, itemInfo, yoff); // Look in annotation type to see if annotation has text that should be printed (like a step designator) + + // if this is a hls with a box, adjust the starting y location for the hls. this is done here + // in case this hls had a boxed caution and/or note before it. Also, this code is here rather + // than in the vlnparagraphs.add code because the yoff in that code will position the box, but + // this code positions the hls (in y direction), without this, the hls starts on the box line. + int bxIndx = itemInfo.IsSection ? 0 : itemInfo.FormatStepData.StepLayoutData.STBoxindex ?? 0; + if (itemInfo.IsHigh && bxIndx > 0) + { + int boxLnAdjust = itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.DiffContActBox ? 1 : 2; + yoff += (boxLnAdjust * SixLinesPerInch); // this yoff is where the BOX starts (boxLnAdjust was added for WEP2) + } + + // If the format has that extra space should be put out before the step, then + // handle this by using the 'PartsAbove' structure. By using the parts above, the extra + // space above will be done regardless of where page breaks fall. + float addExtraSpace = 0; + if (MyItemInfo.FormatStepData != null && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing) + addExtraSpace = MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0; + if (MyItemInfo.MyParent != null && MyItemInfo.MyParent.FormatStepData != null) + addExtraSpace = (MyItemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight" || MyItemInfo.FormatStepData == null) ? 0 : MyItemInfo.FormatStepData.StepLayoutData.STExtraSpace ?? 0; + // If a high level step, the 16bit code uses the value of the extra space + // from the high level step format regardless of what type of high level step it is: + // Added check for UseSTExtraRealValue, if set, we want to use what is set for the specific step type + // Added check for CustomSpacing (was also in 16-bit logic) + if (!MyItemInfo.ActiveFormat.MyStepSectionLayoutData.UseSTExtraRealValue && + !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing && + MyItemInfo.IsHigh) + addExtraSpace = MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[2].StepLayoutData.STExtraSpace ?? 0; + // If CustomSpacing flag is true + // then use the STExtraSpace from the step type called "Default" (index number 25) + //if (YOffset != 0 && MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.CustomSpacing) + if (YOffset != 0 && MyItemInfo.IsSection && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CustomSpacing) + addExtraSpace = (float)MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[25].StepLayoutData.STExtraSpace; + if (YOffset != 0 && MyItemInfo.FormatStepData != null && + MyItemInfo.MyPrevious == null && MyItemInfo.FormatStepData.ThreeBlanksAbove && (!MyItemInfo.IsNote || MyItemInfo.MyParent.Cautions == null)) + addExtraSpace = 24; // already has one blank line above, added two more + // if this plant has the AlwaysUseExtraLines and there are notes/cautions above the hls, don't add in the + // extra space: + if (itemInfo.IsHigh && (itemInfo.Cautions != null || itemInfo.Notes != null)) + { + if ((itemInfo.Cautions != null && itemInfo.Cautions[0].FormatStepData.AlwaysUseExtraLines) || (itemInfo.Notes != null && itemInfo.Notes[0].FormatStepData.AlwaysUseExtraLines)) + addExtraSpace = 0; + // F2021-038: SHE/SHEA format - Less space after boxes + if (itemInfo.Cautions != null && itemInfo.Cautions[itemInfo.Cautions.Count - 1].FormatStepData.NoYBxAdjust) + addExtraSpace = 0; + if (itemInfo.Notes != null && itemInfo.Notes[itemInfo.Notes.Count - 1].FormatStepData.NoYBxAdjust) + addExtraSpace = 0; + } + // F2021-038: SHE/SHEA format - Less space after boxes. The following is for when a HLS has an RNO that has Cautions/Notes + if (itemInfo.IsHigh && itemInfo.RNOs != null) + { + if (itemInfo.RNOs[0].Notes != null && itemInfo.RNOs[0].Notes[0].FormatStepData.NoYBxAdjust) + addExtraSpace = 0; + if (itemInfo.RNOs[0].Cautions != null && itemInfo.RNOs[0].Cautions[0].FormatStepData.NoYBxAdjust) + addExtraSpace = 0; + } + if (addExtraSpace > 0 && MyItemInfo.FormatStepData != null) + { + // We need to strip out the underline style from the font before putting out + // the extra line. + VE_Font vf = MyItemInfo.FormatStepData.Font; + E_Style sty = (E_Style)vf.Style; + if ((sty & E_Style.Underline) != 0) + sty ^= E_Style.Underline; + vf = new VE_Font(vf.Family, (int)vf.Size, sty, (float)vf.CPI); + this.PartsAbove.Add(new vlnText(cb, this, " ", " ", 72, yoff, vf)); + } + + yoff += addExtraSpace; + + YTop = yoff; + YOffset = yoff; + if (mytab != null && mytab.SeparateBullet) + { + string identB = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.IdentB; + vlnText myBullet = new vlnText(cb, this, identB, identB, XOffset - 12, YOffset, MyItemInfo.FormatStepData.TabData.Bullet.Font); + myBullet.Rtf = myBullet.Rtf.Replace("\u25CF", @"\f1\u9679?\f0 "); + PartsLeft.Add(myBullet); + } + if (itemInfo.MyTab != null && itemInfo.MyTab.AsteriskOffset != 0) + { + + // the '-24' in x-direction & '+4' in y-direction was used for the SHE format to get the continuous + // HLS's asterisk to match 16bit. The font size was set at 16 to make it match also: + VE_Font astFont = new VE_Font(MyItemInfo.FormatStepData.TabData.Font.Family, 16, E_Style.Bold, 10); + vlnText myAsterisk = new vlnText(cb, this, "*", "*", mytab.XOffset - 24, YOffset + 4, astFont); + PartsLeft.Add(myAsterisk); + } + if (itemInfo.IsRNOPart && rnoLevel > maxRNO) + { + // the DoubleSpace & SpaceDouble flags seem redundant. The 2nd line was added for foldout + // line spacing for IP2 foldouts (one example can be found in E-1) + if (!itemInfo.FormatStepData.SpaceDouble && itemInfo.MyParent.IsHigh) + { + // but it we are in single column mode, don't remove the blank line. (Wolf Creek Admin Instructions - wcn1) + if (itemInfo.ActiveSection != null && (itemInfo.ActiveSection as SectionInfo).SectionConfig.Section_ColumnMode != SectionConfig.SectionColumnMode.One) // C2018-003 fixed use of getting the active section + yoff = YOffset = yoff - SixLinesPerInch; + } + else if (itemInfo.FormatStepData.NoSpaceMultipleRNOs) yoff = YOffset = yoff - SixLinesPerInch; + if (itemInfo.FormatStepData.DoubleSpace && itemInfo.FormatStepData.SpaceDouble) yoff = YOffset = yoff + SixLinesPerInch; + } + AddMacros(itemInfo, mytab); + if (mytab != null) + { + mytab.YOffset = yoff; + if (mytab.MyMacro != null) mytab.MyMacro.YOffset = yoff; + } + // For background formats, HLS's or Caution or any Notes have tab on line and then text + // on line below (with space in between) + if (itemInfo.IsBackgroundStep() && itemInfo.MyTab != null && itemInfo.MyTab.AltPrintTab != null && itemInfo.MyTab.AltPrintTab.Trim() != "") + yoff = YOffset = yoff + (2 * SixLinesPerInch); + CheckOff co = itemInfo.GetCheckOffStep(); + float yForCheckoff = yoff; //0; - default checkoff row is same as FIRST line of text + // if dropCheckoff is true, then the checkoff is place on the same of row as the LAST line of text + bool dropCheckoff = itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.DropCheckOff + || (co != null && co.DropCheckOff); + if (itemInfo.MyContent.MyGrid != null) + { + vlnCells.DefaultFont = itemInfo.FormatStepData.Font.WindowsFont;// Set the default text font based upon the format + int profileDepth1 = ProfileTimer.Push(">>>> Before vlnParagraph.Grid"); + //Use Static MyFlexGrid - BWD INST2 - FlexGrid Errors + MyFlexGrid.LoadGrid(itemInfo); + MyGrid = new vlnTable(MyFlexGrid, cb); + Height = MyGrid.Height; + Width = MyGrid.Width; + // Adjust the XOffset before determining if the table will overlap the RNO column RHM 20150529 + CalculateXOffsetGridOrFigure(itemInfo, formatInfo); + + yoff = AdjustLocIfLongerRNO(itemInfo, yoff, yoffRightParent); + // if the table does not have a border, only move down one line: + float yoffForBorder = 2 * SixLinesPerInch; + if (MyFlexGrid.BorderStyle == C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None && !MyFlexGrid.TopRowHasBorder()) + yoffForBorder -= SixLinesPerInch; + if (dropCheckoff) + yForCheckoff += Height - SixLinesPerInch; // place checkoff on last row of text + yoff += (Height + yoffForBorder); //(2 * SixLinesPerInch)); + yoff = (float)Math.Ceiling(yoff); + ProfileTimer.Pop(profileDepth1); + } + else if (itemInfo.IsRtfRaw) + { + CalculateXOffsetGridOrFigure(itemInfo, formatInfo); + YOffset = yoff; + yoff += Height * .6f; // .6 is used as a scale factor in RtfRawAt (rtf2pdf). Use it here too for moving down page after equation. + yoff = (float)Math.Ceiling(yoff); + yoff += AdjustForBlankLines(); + } + else if (itemInfo.IsFigure) // if a figure we've got to determine the size: + { + int profileDepth2 = ProfileTimer.Push(">>>> Before vlnParagraph.Figure"); + string erMsg = null; + if (itemInfo.MyContent.Text != null) // ro image + { + if (itemInfo.MyContent.Text != "") // also check for text, there is an RO image then: + { + ProcedureInfo proc = itemInfo.MyProcedure; + DocVersionInfo dvi = proc.MyDocVersion; + ROFstInfo rofst = dvi.DocVersionAssociations[0].MyROFst; + ROFSTLookup lookup = rofst.GetROFSTLookup(dvi); + string linkInfoText = itemInfo.MyContent.Text.Replace(@"\v ", ""); + Match m = Regex.Match(linkInfoText, @"(.*)[#]Link:([A-Za-z]*):(.*)"); + string val = null; + if (m.Length > 0) // if m.lengh is zero, then no match was found - no RO was entered in the figure substep + { + if (m.Groups.Count < 4) + { + //erMsg = "RO was not found during data migration."; + // added newlines in the RO number (shown in figure substep type with figure RO) + // if we are here, then there is no RO link information, use this number to find the RO image to print + val = string.Format("{0}\n{1}\n{2}\n{3}", + linkInfoText.Substring(0, linkInfoText.Length - 16), + linkInfoText.Substring(linkInfoText.Length - 16, 8), + linkInfoText.Substring(linkInfoText.Length - 8, 4), + linkInfoText.Substring(linkInfoText.Length - 4, 4)); + val = val.Replace(@"\u8209?", "-").Replace(@"\u9586?", @"\"); // replace dash and backslash symbols with dash and backslash characters + } + else + { + string[] subs = m.Groups[3].Value.Split(" ".ToCharArray()); + // B2022-088: Find Doc Ro button not working in Word Sections + val = lookup.GetRoChild(subs[1]).value; + if (val == null || val == "?") val = lookup.GetRoChild(subs[1].Substring(0, 12)).value; + if (val == "?") + { + erMsg = string.Format("Referenced Object does not exist."); + _MyLog.WarnFormat("\r\nMissing Referenced Object {0} in {1}", subs[1], itemInfo.ShortPath); + yoff += 2 * SixLinesPerInch; + } + } + } + GC.Collect(); // memory garbage collection (Regex memory bug) + if (val != null && val != "?") + { + string[] vals = val.Split("\n".ToCharArray()); + Width = Int32.Parse(vals[3], System.Globalization.NumberStyles.AllowHexSpecifier) * MyItemInfo.FormatStepData.Font.CharsToTwips; + int lines = Int32.Parse(vals[2], System.Globalization.NumberStyles.AllowHexSpecifier); + // Check that the Height of figure isn't too big to fit on the page, if it is + // set the Height to the printable part of page - Height of the HLS and an extra line + // for between HLS & figure. + float h1 = lines * SixLinesPerInch; + float h2 = RoughSizeOfPage - MyParent.Height - SixLinesPerInch; + Height = Math.Min(h1, h2); + if (h1 > h2) + { + Width *= (h2 / h1); + } + StepInfo si = (StepInfo)MyItemInfo; + StepConfig sc = new StepConfig(si.MyContent.Config); + if (sc != null && sc.Step_ImageWidth != 0) + { + Width = sc.Step_ImageWidth; + Height = sc.Step_ImageHeight; + } + yoff = AdjustLocIfLongerRNO(itemInfo, yoff, yoffRightParent); + if (dropCheckoff) + yForCheckoff += Height - SixLinesPerInch; // place checkoff on last row of text + bool noborder = MyItemInfo.FormatStepData.Type.ToUpper().Contains("BORDERLESS"); + yoff += (Height + ((noborder ? 1 : 2) * SixLinesPerInch)); // RHM 20120925 - Eliminate extra space after Figure } + try + { + ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(rofst.ROFstID, vals[0]); + if (roImage != null) + ImageText = val; + else + { + roImage = rofst.GetROImageByFilename(vals[0], MyItemInfo);// need code to go and get an ROImaage if it exists + if (roImage == null) + erMsg = string.Format("Image {0} does not exist.", vals[0]); + else + ImageText = val; + } + } + catch (Exception ex) + { + erMsg = string.Format("Image {0} does not exist, error = {1}.", vals[0], ex.Message); + } + } + if (erMsg != null) Rtf = GetRtf(erMsg, itemInfo.ActiveFormat.PlantFormat.FormatData.Font); + } + CalculateXOffsetGridOrFigure(itemInfo, formatInfo); + } + else + { + // figure + ImageText = "figure"; + } + if (ImageText == null && erMsg == null) + { + ImageText = "figure"; + ImageConfig ic = new ImageConfig(MyItemInfo.MyContent.MyImage); + // B2016-277: add a try catch in case of there being 'bad' data in the text field for an image/figure + try + { + byte[] idata = (ic != null && ic.Image_DataSize > 0) ? ROImageInfo.Decompress(MyItemInfo.MyContent.MyImage.Data, ic.Image_DataSize) : MyItemInfo.MyContent.MyImage.Data; + MemoryStream ms = new MemoryStream(idata); + System.Drawing.Image img = System.Drawing.Image.FromStream(ms); + Width = img.Width; + Height = img.Height; + if (ic != null && ic.Image_Height != 0) + { + Width = ic.Image_Width; + Height = ic.Image_Height; + + // B2022-041: extra whitespace after resized image. Make same adjustment here that gets made in ParagrphToPdf + // B2023-040: WCN pagination changed for And steps with large image after - add format flag for + // Barakah + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.AdjustLargeImage) + { + float mult = 1.0F; + if (Width > (vlnParagraph.wMax - 12)) mult = (vlnParagraph.wMax - 24) / Width; + if (Height > (vlnParagraph.hMax - 36)) mult = Math.Min(mult, (vlnParagraph.hMax - 36) / Height); + if (mult < 1.0F) + { + Width *= mult; + Height *= mult; + } + } + } + yoff = AdjustLocIfLongerRNO(itemInfo, yoff, yoffRightParent); + bool noborder = MyItemInfo.FormatStepData.Type.ToUpper().Contains("BORDERLESS"); + yoff += (Height + SixLinesPerInch); // B2019-059 only one extra line after a figure (does not matter if it has a border or not) + CalculateXOffsetGridOrFigure(itemInfo, formatInfo); + } + catch (Exception) + { + _MyLog.WarnFormat("Bad figure content data: item = {0}, {1}", MyItemInfo.ItemID, MyItemInfo.ShortPath); + } + } + ProfileTimer.Pop(profileDepth2); + } + else + { + // For Calvert Alarms, the 'CONDITION/RESPONSE' portion uses a macro to print + // the CONDITION and RESPONSE text with the lines around it. Add the macro here because + // there is no tab for the step & that's where the macro is usually stored: + if (HasCalvertMacro) PartsLeft.Add(new vlnMacro(xoff - 12f, yoff, "H4")); + + if (itemInfo.IsStep && itemInfo.MyHLS != null && itemInfo.MyHLS.FormatStepData.UseSmartTemplate) + { + if (itemInfo.FormatStepData.StepLayoutData.AlignWithParentTab + || (itemInfo.Steps != null && itemInfo.Steps.Count > 0 && itemInfo.Steps[0].FormatStepData.StepLayoutData.AlignWithParentTab)) + { + int stplevl = TheStepLevel(itemInfo); + if (stplevl >= 0 && MyItemInfo.MyHLS.FormatStepData.VertPos[stplevl] > 0) + { + if (MyItemInfo.FormatStepData.StepPrintData.Justify == "Center") + { + string[] vertPos = MyItemInfo.MyHLS.FormatStepData.VertPos.Split(",".ToCharArray()); + float hloc = (float.Parse(vertPos[stplevl]) + ((float.Parse(vertPos[stplevl + 1]) - float.Parse(vertPos[stplevl])) / 2)); + Chunk chk = (Chunk)IParagraph.Chunks[0]; + hloc -= (chk.GetWidthPoint() / 2); + XOffset = hloc + (float)itemInfo.MyDocStyle.Layout.LeftMargin; + } + else + XOffset = float.Parse(MyItemInfo.MyHLS.FormatStepData.VertPos.Split(",".ToCharArray())[stplevl]) + (float)itemInfo.MyDocStyle.Layout.LeftMargin; + } + } + } + if (itemInfo.IsTablePart) // Not for grid, this is for old-style tables. + { + Width = GetTableWidth(cb, IParagraph, MyItemInfo.MyDocStyle.Layout.PageWidth); + CalculateXOffsetGridOrFigure(itemInfo, formatInfo); + } + else + if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.StepPrintData != null && (itemInfo.IsHigh || (!itemInfo.IsHigh && itemInfo.MyContent.Type != itemInfo.MyParent.MyContent.Type))) XOffset += (float)(itemInfo.FormatStepData.StepPrintData.PosAdjust ?? 0); + + // point beach wpb subformats 20 & 22 were printing some text past right margin. Limit the width to the right margin, i.e. pagewid + if (itemInfo.ActiveFormat.MyStepSectionPrintData.LimitWidToPageWid) + { + float lim = (MyTab == null ? (XOffset - (float)itemInfo.MyDocStyle.Layout.LeftMargin) : MyTab.XOffset + MyTab.Width) + Width; + float docStyleLim = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin; + + if (lim > docStyleLim) + { + WidthNoLimit = Width; // Use this width to calculate childrens' width, without this, code was making children to narrow! + Width = docStyleLim - (MyTab == null ? (XOffset - (float)itemInfo.MyDocStyle.Layout.LeftMargin) : MyTab.XOffset + MyTab.Width); + } + } + if (itemInfo.IsSection && ShowSectionTitles + && !MyItemInfo.MyDocStyle.CancelSectTitle) + { + if (MyItemInfo.MyDocStyle.Layout.SectionMacro != null) + { + string macro = GetMacroName(MyItemInfo.MyDocStyle.Layout.SectionMacro); + PartsAbove.Add(new vlnMacro(xoff, yoff, macro)); + yoff += SixLinesPerInch; + YOffset = yoff; + } + } + + // if this step has a prefix but it's not checklist... do a partsleft for prefix + if (MyItemInfo.IsStep && !MyItemInfo.FormatStepData.UseSmartTemplate) + { + if (MyItemInfo.FormatStepData.Prefix != null && MyItemInfo.FormatStepData.Prefix != "") + { + string pref = MyItemInfo.FormatStepData.Prefix.Replace("{Backspace}", ""); + float xPref = XOffset - (pref.Length * (72 / (float)MyItemInfo.FormatStepData.Font.CPI)); + E_Style es = (E_Style)MyItemInfo.FormatStepData.Font.Style & E_Style.Bold; + VE_Font tmpFont = new VE_Font(MyItemInfo.FormatStepData.Font.Family, (int)MyItemInfo.FormatStepData.Font.Size, es, (float)MyItemInfo.FormatStepData.Font.CPI); + PartsLeft.Add(new vlnText(cb, this, pref, pref, xPref, yoff, tmpFont)); + } + } + // If checklists, the substeps are printed in a row, need to keep track of the 'longest' in + // y direction (bottommost) across the row. + if (itemInfo.IsStep && itemInfo.MyHLS != null && (itemInfo.MyHLS.FormatStepData.UseSmartTemplate || (itemInfo.MyHLS.FormatStepData.UseOldTemplate && itemInfo.MyDocStyle.ComponentList)) && (TheStepLevel(itemInfo) >= 0)) + savCheckListBottomMost = yoff + Height + (itemInfo.MyHLS.FormatStepData.UseSmartTemplate ? SixLinesPerInch : 0); + + // The following was added for BGE valve lists, this format (BGEVLV) used caution1 as + // a subheader within the valve list. To print correctly, a line needs to be added to + // where the bottom of this (subheader) is located and XOffset is set to the leftmargin. + if (itemInfo.IsStep && itemInfo.MyHLS != null && !itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.IsCaution1 && itemInfo.MyHLS.FormatStepData.UseOldTemplate && itemInfo.MyDocStyle.ComponentList) + { + savCheckListBottomMost += SixLinesPerInch; + yoff += Height; + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + } + + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.IsCaution1) savCheckListBottomMost = yoff + Height; + // Get Y offset for regular steps, or if section title is output or if not within row (not last column of + // text) for wcn checklist, i.e. + if ((!itemInfo.IsStepSection && itemInfo.MyHLS != null && !itemInfo.MyHLS.FormatStepData.UseSmartTemplate) // regular step + || (ShowSectionTitles + && !MyItemInfo.MyDocStyle.CancelSectTitle + && !MyItemInfo.MyDocStyle.SpecialStepsFoldout) + // In Checklist: I don't have children or if I have children the first child doesn't alignwithparent. + || (!itemInfo.IsStepSection && itemInfo.MyHLS != null && itemInfo.MyHLS.FormatStepData.UseSmartTemplate + && ((itemInfo.Steps == null || itemInfo.Steps.Count == 0) + || !itemInfo.Steps[0].FormatStepData.StepLayoutData.AlignWithParentTab)) + || ((MyItemInfo.IsNote || MyItemInfo.IsCaution) && MyItemInfo.MyParent.IsSection)) // B2016-222 check if is a caution or note and parent is a section + { + bool doprint = !(MyPageHelper.DidHLSText && MyItemInfo.ItemID == MyPageHelper.HasHLSTextId); + if (MyItemInfo.IsSection) + { + if (MyItemInfo.MyConfig is SectionConfig sch && sch.Section_PrintHdr != "Y") doprint = false; + } + //C2025-021 Add logic to PROMS to support a special High Level Step type that is not printed. + if (doprint && !UseTemplateKeepOnCurLine(itemInfo) && !itemInfo.IsType("InvisibleHigh")) + { + float tyoff = yoff; + if (itemInfo.Steps != null) + { + if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.Type == "TitleWithTextRight") + if (loadChildren) tyoff = ChildrenRight.Add(cb, itemInfo.Steps, XOffset + 72, yoff, yoff, rnoLevel, maxRNO, formatInfo); + } + yoff += Height; + yoff = Math.Max(yoff, tyoff); + yoff += AdjustForBlankLines(); + if (dropCheckoff) + yForCheckoff += Height - SixLinesPerInch; // place checkoff on last row of text + } + } + } + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + // For Calvert Alarms, the row has formatting that makes this template item have a header & box + // (CONDITION/RESPONSE), header with box around it is defined in genmac whereas the lines around + // substeps are drawn in pagehelper. Adjust some yoffsets around this box. + // Need to: + // 1) move the text down a bit for top line (1.5f * SixLinesPerInch) + // 2) move the substep down 2 lines (2 * SixLinesPerInch) for bottom of box + // and space before substep + // 3) if the previous item had this condition, add space for the + // line below. + if (HasCalvertMacro) + { + YOffset += (1.5f * vlnPrintObject.SixLinesPerInch); + yoff += (2 * vlnPrintObject.SixLinesPerInch); + } + if (itemInfo.MyPrevious != null && itemInfo.MyPrevious.TemplateIndex > 0) + { + if (itemInfo.MyPrevious.ActiveFormat.PlantFormat.FormatData.Templates[itemInfo.MyPrevious.TemplateIndex].hmacro > 0) + { + YOffset += (3 * vlnPrintObject.SixLinesPerInch); + yoff += (3 * vlnPrintObject.SixLinesPerInch); + } + } + } + if (co != null && !MyItemInfo.IsInSupInfo) // C2018-002: don't print checkboxes on supplemental infromation pages. + { + // if this item's content is empty, and the flag is set to 'notonempty', don't print out the + // checkoff - this was added for shearon harris: + if (!(co.NotOnEmpty && itemInfo.MyContent.Text.Replace(@"\u160?", " ").TrimEnd() == "")) + { + float xloc_co = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + // if the format has 'SkipSpaces', look at the tab, and back up the macros to the number of + // spaces in the tab. + if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.SkipSpaces) + { + if (mytab != null) + xloc_co = mytab.XOffset; + else + xloc_co = XOffset; //there's no tab - put checkoff at step's xoff. Macro should back up from step's x. + } + else + { + if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.XLocation != 0) + xloc_co += (float)formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.XLocation; + else if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.RelXLocation != 0) + { + float relX = (float)formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.RelXLocation; + xloc_co = XOffset + (relX > 0 ? Width : 0) + relX; + } + } + + // CheckOffXtraLines was introduced for the additional lines needed for the longer signoffs + // for VCBA (&WST1), for F2016-061. + float checkOffNumberOfLines = (co.CheckOffNumberOfLines ?? 0); + if (checkOffNumberOfLines > 0) + { + yForCheckoff += (2 * SixLinesPerInch); + PartsRight.Add(new vlnMacro(xloc_co, yForCheckoff/* + xtraCheckOffLines */, co.Macro)); + yoff += ((checkOffNumberOfLines *= SixLinesPerInch) + (2 * SixLinesPerInch)); + } + else + { + // if xtraCheckOffLines is a negative number, start the checkoff on the same line + // as text and adjust the y-offset after the checkoff by the amount of the absolute + // value of xtraCheckOffLines. + // if xtraCheckOffLines is a positive number, start the checkoff xtraCheckOffLines - 1 + // down from the text and adjust the y-offset after the checkoff by the amount + // of xtraCheckOffLines. + float xtraCheckOffLines = (co.CheckOffXtraLines ?? 0); + if (xtraCheckOffLines < 0) + { + xtraCheckOffLines = -xtraCheckOffLines; + xtraCheckOffLines *= SixLinesPerInch; + PartsRight.Add(new vlnMacro(xloc_co, yForCheckoff/* + xtraCheckOffLines */, co.Macro)); + yoff += xtraCheckOffLines; + } + else + { + xtraCheckOffLines *= SixLinesPerInch; + xtraCheckOffLines -= ((xtraCheckOffLines > 0) ? SixLinesPerInch : 0); + PartsRight.Add(new vlnMacro(xloc_co, yForCheckoff + xtraCheckOffLines, co.Macro)); + yoff += (xtraCheckOffLines != 0) ? xtraCheckOffLines + SixLinesPerInch : 0; + } + } + } + } + // for WCNTRN, do the responsibility: + if (formatInfo.PlantFormat.FormatData.PrintData.WCNTraining) DoResponsibility(cb, YOffset); + float yOffRight = yoff; + float RnoOffset = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); + if (DoSubs && rnoLevel < maxRNO && itemInfo.RNOs != null) + { + if (loadChildren) yOffRight = ChildrenRight.Add(cb, itemInfo.RNOs, XOffset + RnoOffset, YTop, YTop, rnoLevel + 1, maxRNO, formatInfo); + if (ChildrenRight[0].ChildrenAbove.Count > 0) + { + float adj = ChildrenRight[0].YOffset - YOffset; + YOffset = ChildrenRight[0].YOffset; + yoff += adj; + if (MyTab != null) MyTab.YOffset = ChildrenRight[0].YOffset; + if (PartsRight.Count > 0) PartsRight[0].YOffset = ChildrenRight[0].YOffset; + //B2020-160 use YTopMost instead of Yoffset if there are children above. + // Get the minimun value between the AER and RNO YtopMost. + // example. Calvert AOP-7E/XIII/Step A5.h Unit 2 Approved set + //B2021-027 use YOffset if there isn't any children above (AER). + // example: Catawba Unit 1 AP’s; AP/1/A/5500/050; Enclosure 8 step 1 + if (ChildrenAbove.Count == 0) + YTopMost = ChildrenRight[0].ChildrenAbove[0].YOffset; //B2021-027 + else + YTopMost = Math.Min(ChildrenAbove[0].YTopMost, ChildrenRight[0].ChildrenAbove[0].YTopMost); //B2020-160 + } + } + // if this hls had a box drawn, add a line for substeps. + if (itemInfo.IsHigh && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) yoff += vlnPrintObject.SixLinesPerInch; + + // Need code to determine if the table will overlap the Right Column if it does then + // use YOffRight rather than yoff + if (DoSubs && itemInfo.Tables != null) + { + bool aerTableOrFigure = itemInfo.Tables[0].FormatStepData.Type.Contains("AER"); + // get the first table & see if it is borderless. If borderless, 16bit code removed a + // line (yoffset) before printing it: + float yoffadj = 0; + if (itemInfo.Tables[0].IsTable) + { + MyFlexGrid.LoadGrid(itemInfo.Tables[0]); + // B2018-077 added check for caution and note parts in which case we want the blank line - fix for Calvert OI-27B 6.11.B and 6.12.B + if (MyFlexGrid.BorderStyle == C1.Win.C1FlexGrid.Util.BaseControls.BorderStyleEnum.None && !MyFlexGrid.TopRowHasBorder() && !MyItemInfo.IsCautionOrNotePart) + yoffadj = -SixLinesPerInch; + } + // B2023-008: when an equation is off a paragraph sub-step in single column mode, extra lines were added so + // when in single column mode & the substep has an equation (rtfraw), then don't reset yoffright to yverybottom + bool rtfRawInSingleCol = (itemInfo.ColumnMode == ((int)VEPROMS.CSLA.Library.SectionConfig.SectionColumnMode.One - 1)) && (itemInfo.Tables != null && itemInfo.Tables.Count > 0 && itemInfo.Tables[0].IsRtfRaw); + if (yOffRight < yoffRightParent) yOffRight = yoffRightParent; + // find the very bottom Yoffset (don't do this is in single column mode for cautions/notes: B2016-261) + vlnParagraph parentPar = parent; + if (!rtfRawInSingleCol && (!((MyItemInfo.IsCaution || MyItemInfo.IsNote) && itemInfo.RNOLevel == 0))) + { + while (parentPar != null && parentPar.MyItemInfo.IsStep) + { + float vb = parentPar.YVeryBottom; + if (yOffRight < vb) yOffRight = vb; + parentPar = parentPar.MyParent; + } + } + bool rightLonger = yOffRight > yoff; + if (!aerTableOrFigure && itemInfo.RNOLevel == 0) // Centered Table + { + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.Tables, XOffset, rightLonger ? yOffRight : yoff + yoffadj, yOffRight + yoffadj, rnoLevel, maxRNO, formatInfo); + } + else // AER or RNO Table + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.Tables, XOffset, yoff + yoffadj, yOffRight + yoffadj, rnoLevel, maxRNO, formatInfo); + } + yOffRight = Math.Max(yOffRight, yoffLeft); + // Look for the meta section case where the 'Editable' flag is set to 'N', which means that + // these steps should not be printed: + bool printsteps = true; + if (itemInfo.Steps != null && itemInfo.IsSection && itemInfo.Sections != null && itemInfo.Sections.Count > 0) + { + if (itemInfo.MyConfig is SectionConfig sc && sc.SubSection_Edit != "Y") printsteps = false; + } + bool rnoBefore = false; + bool rnoAfter = false; + if (rnoLevel >= maxRNO && itemInfo.RNOs != null && + !itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.WolfCreekBackgroundFormat && + !itemInfo.RNOs[0].FormatStepData.InPageList) + { + if ((itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString ?? "") != "" || + (itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString ?? "") != "") + rnoBefore = true; + else + rnoAfter = true; + } + if (rnoBefore) + { + if ((itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString ?? "") != "") + { + string tmpSepStr = itemInfo.ActiveFormat.MyStepSectionPrintData.HLStpSeparatorString; + float xsep = MyHighLevelParagraph.PartsLeft.Count > 0 ? MyHighLevelParagraph.PartsLeft[0].XOffset : MyHighLevelParagraph.XOffset; + vlnRNOSeparator mySep = new vlnRNOSeparator(this, cb, tmpSepStr, xsep, yoff, itemInfo.ActiveFormat, false); + PartsBelow.Add(mySep); + yoff += mySep.Height;// +SixLinesPerInch; + } + if (loadChildren) yoff = ChildrenBelow.Add(cb, itemInfo.RNOs, MyTab.XOffset, yoff, yoff, rnoLevel + 1, maxRNO, formatInfo); + if ((itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString ?? "") != "") + { + string tmpSepStr = itemInfo.ActiveFormat.MyStepSectionPrintData.HLRNOStpSeparatorString; + float xsep = MyHighLevelParagraph.PartsLeft.Count > 0 ? MyHighLevelParagraph.PartsLeft[0].XOffset : MyHighLevelParagraph.XOffset; + vlnRNOSeparator mySep = new vlnRNOSeparator(this, cb, tmpSepStr, xsep, yoff, itemInfo.ActiveFormat, false); + PartsBelow.Add(mySep); + yoff += mySep.Height;// +SixLinesPerInch; + } + } + // For Calvert Alarms, 'Caution1' was used to implement the Annunciator Window, i.e. is printed + // below the HLS and close to the right margin. + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.Cautions != null && itemInfo.Cautions[0].FormatStepData.Type == "Caution1") + { + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.Cautions, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); + savCheckListBottomMost = yoff; + } + if (DoSubs && itemInfo.Steps != null && printsteps) + { + if (itemInfo.FormatStepData == null || itemInfo.FormatStepData.Type != "TitleWithTextRight") + if (rnoBefore) + { + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.Steps, MyTab.XOffset, yoff, yOffRight, rnoLevel, maxRNO, formatInfo); + } + else + if (loadChildren) yoff = ChildrenBelow.Add(cb, itemInfo.Steps, XOffset, yoff, yOffRight, rnoLevel, maxRNO, formatInfo); + } + if (itemInfo.Sections != null) + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.Sections, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo, pp); + if (itemInfo.Procedures != null) + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.Procedures, xoff, yoff, yoff, rnoLevel, maxRNO, formatInfo); + // Don't add the RNO to print if doing backgrounds. That piece of data is part of the pagelist item. + if (rnoAfter) + if (loadChildren) + yoff = ChildrenBelow.Add(cb, itemInfo.RNOs, XOffset, yoff, yoff, rnoLevel + 1, maxRNO, formatInfo); + YBottomPagination = yoff;// B2019-111 Exclude Right for Pagination + yoff = Math.Max(yoff, yOffRight); + // TODO - use RNOSepAfterAER flag too: + string tmpRnoSepStr = formatInfo.MyStepSectionPrintData.RNOSepString; + float tmpRnoSepLen = formatInfo.MyStepSectionPrintData.RNOSepLineLength ?? 0; + if (rnoLevel < maxRNO && itemInfo.RNOs != null && (tmpRnoSepStr != null || tmpRnoSepLen != 0)) + { + vlnParagraph rno = ChildrenRight[0]; + vlnParagraph bottomChild = BottomChild; + float xsep = MyHighLevelParagraph.XOffset + RnoOffset; + + // ip3 has an rno separator and also has asterisk boxes around continous HLS. If + // the hls has RNOs off of it, then the rno separator line is outside of the box. If + // there are RNOs, but not off of HLS, then rno separator line is within the box (this is + // how 16bit proms did this). The following use of yadjSep and YBottomForBox handle that + float yadjSep = (MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex != null && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex >= 0 && + MyItemInfo.MyHLS.RNOs != null && MyItemInfo.MyHLS.RNOs.Count > 0) ? 2 * SixLinesPerInch : 0; + vlnRNOSeparator myRnoSep = new vlnRNOSeparator(this, cb, tmpRnoSepStr, xsep, yoff + yadjSep, formatInfo, bottomChild == null || bottomChild.MyItemInfo.HasChangeBar); + // TODO: May need to handle more than one RNO column for RNO Separator + if ((rno.LastRNO.MyItemInfo.HasChangeBar == false && bottomChild != null && bottomChild.MyItemInfo.HasChangeBar) + || (bottomChild != null && bottomChild.YBottom > rno.LastRNO.YBottomMost)) + bottomChild.PartsBelow.Add(myRnoSep); + else + rno.LastRNO.PartsBelow.Add(myRnoSep); + MyHighLevelParagraph.YBottomForBox = 0; + if (yadjSep > 0) + { + MyHighLevelParagraph.YBottomForBox = yoff; // if hlrno, box before sep + YBottomMostAdjust = SixLinesPerInch; // added for IP3 pagination, the RNO separator is outside asterisk box + } + yoff += (myRnoSep.Height + SixLinesPerInch); + } + // if in WCNTRN (Wolf Creek Training), need to consider the ysize of the Responsibility text when setting + // YBottomMost, i.e. if the Responsibilty has more height (y-direction) compared to the actual step text, + // need to move down on page the height of the responsibility. + if (formatInfo.PlantFormat.FormatData.PrintData.WCNTraining && MyItemInfo.IsHigh) + { + if (PartsLeft.Count > 0 && PartsLeft[0] is vlnText) + { + foreach (vlnText vt in PartsLeft.OfType()) + yoff = Math.Max(yoff, vt.YOffset + vt.Height); + } + } + YBottomMost = yoff; + + if ((MyItemInfo.IsHigh || MyItemInfo.IsCaution1) && MyItemInfo.MyDocStyle.LandscapePageList && MyItemInfo.MyDocStyle.ComponentList) + { + // put out line after step (for BGEVLV format) + float macroY = YBottomMost - (0.25f * SixLinesPerInch); + PartsLeft.Add(new vlnMacro((float)MyItemInfo.MyDocStyle.Layout.LeftMargin, macroY, "B9")); + } + + // For Checklist, the substeps are in rows of data. The YBottomMost is the bottom most for + // the row. + if (savCheckListBottomMost != 0) YBottomMost = Math.Max(savCheckListBottomMost, YBottomMost); + if (XOffsetCenter != null) XOffset = (float)XOffsetCenter; + ProfileTimer.Pop(profileDepth); + } + + private vlnTab GetSupInfoTab(PdfContentByte cb, ItemInfo itemInfo, float yoff, bool doSectTab, float localXOffset) + { + string strmytab; + if (itemInfo.MyParent.IsHigh) + strmytab = itemInfo.MyTab.CleanText; + else if (itemInfo.MyParent.IsCaution) + strmytab = "Caution"; + else if (itemInfo.MyParent.IsNote) + strmytab = "Note"; + else + { + // B2018-022: use flag to determine whether to pre-pend the parent's tab as part of the supplemental info tab + // (if the procedure tab is long, such as in Farley, the tab overwrites text in the supplemental info pages) + strmytab = itemInfo.ActiveSection.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoIncludeParTab + ? ItemInfo.GetCombinedTab(itemInfo.MyParent, itemInfo.MyParent.MyParent.CombinedTab) + : itemInfo.MyTab.CleanText; + } + strmytab = strmytab.Trim(); + return new vlnTab(cb, this, strmytab, strmytab, localXOffset, yoff, itemInfo.MyTab.MyFont, doSectTab, StepRTB.MySymbolFontName, itemInfo.MyTab.RemovedStyleUnderline); + } + + public static VE_Font AnnotationFont { get; set; } + + // Check to see if the procedure has any printable text in the annotations + private bool? _CanDoPrintableText = null; + public bool CanDoPrintableText + { + get + { + if (_CanDoPrintableText == null) + { + _CanDoPrintableText = false; + AnnotationTypeInfoList atil = AnnotationTypeInfoList.Get(); + foreach (AnnotationTypeInfo ati in atil) + { + AnnotationTypeConfig atc = new AnnotationTypeConfig(ati.Config); + if (atc.PrintableText_XLocation != 0) + { + _CanDoPrintableText = true; + break; + } + } + } + return (bool)_CanDoPrintableText; + } + } + private void DoAnnotationPrintableText(PdfContentByte cb, ItemInfo itemInfo, float yoff) + { + // check to see if this procedure has any printable annotations. + // if it does not, then there is no need to spin through checking for the given itemInfo + if (!CanDoPrintableText) return; + + // if this step has an Annotation and it has config data to define location, parse out '[xx]' and print it at the location + // this was added for VC Summer (unit 2 & 3) but is available for any data that has defined the location in the config (from the folder properties + // at the top node - annotationtype tab. + if (itemInfo.ItemAnnotationCount > 0) + { + foreach (AnnotationInfo ai in itemInfo.ItemAnnotations) + { + // get the annotation type from the annotation, and see if it has a print location: + AnnotationTypeInfo at = ai.MyAnnotationType; + AnnotationTypeConfig atc = new AnnotationTypeConfig(at.Config); + if (atc.PrintableText_XLocation != 0) + { + int st = ai.SearchText.IndexOf("["); + int end = ai.SearchText.IndexOf("]"); + if (st != -1 && end != -1 && end > st) + { + string pref = ai.SearchText.Substring(st + 1, end - st - 1); // annotation - parse out [xx] + pref = Regex.Replace(pref, "{Up}", @"\u8593?", RegexOptions.IgnoreCase); + pref = Regex.Replace(pref, "{Down}", @"\u8595?", RegexOptions.IgnoreCase); + float xPref = atc.PrintableText_XLocation; + if (AnnotationFont == null) + AnnotationFont = new VE_Font(MyItemInfo.FormatStepData.Font.Family, 6, (E_Style)MyItemInfo.FormatStepData.Font.Style, 20F); + PartsLeft.Add(new vlnText(cb, this, pref, pref, xPref, yoff, AnnotationFont)); + break; + } + } + } + } + } + + private float AdjustLocIfLongerRNO(ItemInfo itemInfo, float yoff, float yoffRightParent) + { + if (!itemInfo.IsInRNO && yoffRightParent > yoff && itemInfo.FormatStepData.Type.Contains("AER")) + { + // is the width of this table going to cause the table to overlap the RNO + vlnParagraph parRno = FindParentRNO(); + float xMinRno = FindMinXOffsetRno(parRno); + if (XOffset + Width > xMinRno - 12) // 12 = 2 characters, so that tables don't almost touch & look like an overlap + { + if ((float)MyItemInfo.MyDocStyle.Layout.LeftMargin + Width > xMinRno) + { + yoff = yoffRightParent; + YOffset = yoff; + } + else + XOffset = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin; + } + } + return yoff; + } + private float FindMinXOffsetRno(vlnParagraph parRno) + { + // Find the minimum xoffset in the rno column that overlaps in the y direction with + // the table that is currently being processed. This is necessary in order to fix the + // case where the AER table overlaps an RNO table (or tab/text) + float xcur = 0; + // YOffset/Height is for the current table, check it against the rno's yoffset & height + // if aer & rno are within y range of each other + if (YOffset <= (parRno.YOffset + parRno.Height) && (YOffset + Height) >= parRno.YOffset) + { + xcur = parRno.XOffset; + if (parRno.MyTab != null) xcur = parRno.MyTab.XOffset; + } + // recursively look at steps in the rno column to get the smallest xoffset which will + // then be used to compare to table's xoffset/width to see if there is an overlap + if (parRno.ChildrenBelow != null) + { + foreach (vlnParagraph vp in parRno.ChildrenBelow) + { + // yoffset is past where the table is, so don't consider it: + if (vp.YOffset > (YOffset + Height)) return xcur; + + float xchild = FindMinXOffsetRno(vp); + if (xchild > 0 && (xcur == 0 || xchild < xcur)) + xcur = xchild; + } + } + return xcur; + } + private void DoResponsibility(PdfContentByte cb, float yoff) // WCNTRN's text in 1st column (saved in config for HLS) + { + if (MyItemInfo.MyConfig is StepConfig sc2) + { + string resp = sc2.Step_Responsibility; + + if (resp != null && resp != "") // lines are separated by "\r\n" + { + resp = DelimitResponse((int)MyItemInfo.MyDocStyle.SectTop.MaxLen, resp); + if (!resp.EndsWith("\r\n")) resp += "\r\n"; // parsing needs this. + int indx = resp.IndexOf("\r\n"); + int stindx = 0; + float y = yoff; + while (indx > -1) + { + string subresp = resp.Substring(stindx, indx - stindx); + float respWidth = subresp.Length * 6; + float ctr = (float)MyItemInfo.MyDocStyle.SectTop.Margin; + float respcntrX = (float)MyItemInfo.MyDocStyle.Layout.LeftMargin + ctr - (respWidth / 2); + vlnText myResp = new vlnText(cb, this, subresp, subresp, respcntrX, y, MyItemInfo.FormatStepData.Font); + PartsLeft.Add(myResp); + y += SixLinesPerInch; + stindx = indx + 2; + indx = stindx < resp.Length ? resp.IndexOf("\r\n", stindx) : -1; + } + } + } + } + private string DelimitResponse(int maxLen, string responsStr) + { + // This code handles whether user enters \r\n to separate lines or not. The + // max width that a line can be in the Responsibility column is a format flag (passed in) + List results = new List(); + int width = 0; // keep track of current width of current 'line' while looking for space to break + int start = 0; // start of line (index into string 'text') + int lastspace = 0; // location of lastspace (index into string) + for (int indx = 0; indx < responsStr.Length; indx++) + { + if ((indx + 1) < responsStr.Length && responsStr.Substring(indx, 2) == "\r\n") + { + results.Add($"{responsStr.Substring(start, indx - start).Trim(" ".ToCharArray())}\r\n"); + start = indx + 2; + width = 0; + } + else + { + if (responsStr[indx] == ' ') lastspace = indx; + width++; + if (width > maxLen) + { + // what should be done if lastspace == 0 + // cannot find space char to split on, so break the word + bool spFound = true; + if (lastspace == 0) + { + lastspace = indx; + spFound = false; + } + results.Add($"{responsStr.Substring(start, lastspace - start).Trim(" ".ToCharArray())}\r\n"); + start = lastspace + (spFound ? 1 : 0); // increment start based on whether a space is found, i.e. if no space keep at 'indx' + // width either is equal to width of text after the last space, or is zero if at the maxlen of width: + width = (indx - lastspace - 1) > 0 ? indx - lastspace - 1 : 0; + lastspace = 0; + } + } + } + if (width > 0 || start < responsStr.Length) results.Add(responsStr.Substring(start).Trim(" ".ToCharArray())); + string retval = null; + foreach (string st in results) retval += st; + return retval; + } + public override string Rtf + { + get + { + if (_Rtf == null) BuildRtf(); + return _Rtf; + } + set { _Rtf = value; } + } + private void BuildRtf() + { + int profileDepth = ProfileTimer.Push(">>>> BuildRtf"); + if (_Rtf == null) + { + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && MyItemInfo.IsCaution1 && + MyItemInfo.MyContent.Text.StartsWith(@"\u") && !MyItemInfo.MyContent.Text.StartsWith(@"\u160?")) + { + Rtf = GetRtf(MyItemInfo, " " + (Prefix ?? ""), Suffix); + PrefixSpecialCharacter = true; + } + else + { + Rtf = GetRtf(MyItemInfo, Prefix, Suffix); + } + // Need the following with some modifications for WCNCKL format: + if (Rtf.Contains("{Backspace}")) + { + XOffset -= 25; + Width += 24; + Rtf = Rtf.Replace("{Backspace}", ""); + } + } + Rtf = FixRTFToPrint(MyItemInfo, Rtf); + ProfileTimer.Pop(profileDepth); + } + // C2018-024 I in Arial font changed to I in TimesNewRoman + private static System.Drawing.Font _TNR; + // F2018-013 Changed to static and public so that it can be used with step identifiers for bullets + public static string FixRTFToPrint(ItemInfo myItemInfo, string rtf) + { + // Only do this if the text contains symbols. + if ((rtf.Contains("VESymbFix") || rtf.Contains(Volian.Base.Library.vlnFont.ProportionalSymbolFont))) // C2017-036 get best available proportional font for symbols + { + // bug fix: B2017-117 was getting an out of window handles error when doing a print all for Bryon + // add the using statment to free up window handle that is created doing a New RichTextBox() + using (System.Windows.Forms.RichTextBox rtb = new System.Windows.Forms.RichTextBox()) + { + rtb.Rtf = rtf.Replace(@"\\", ""); // rename backslash character to avoid RTF confusion + //string showRTF = rtf; + bool changed = false; + // C2018-024 I in Arial font changed to I in TimesNewRoman + if (myItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ChangeFontUpperCaseIinArial) + { + bool lastWasNumber = false; + for (int i = 0; i < rtb.TextLength - 1; i++) + { + rtb.Select(i, 2); + if (rtb.SelectionLength == 2) + { + if ((rtb.SelectedText == ".I") && rtb.SelectionFont.FontFamily.Name == "Arial") + { + if (_TNR == null) + _TNR = new System.Drawing.Font("Times New Roman", rtb.SelectionFont.Size, rtb.SelectionFont.Style); + if (lastWasNumber) + { + rtb.SelectionFont = _TNR; + changed = true; + lastWasNumber = false; + } + } + else + lastWasNumber = Regex.IsMatch(rtb.SelectedText, @"[0-9]\."); + } + } + } + // C2017-008 - WCN wants the box symbol to look like their checkoff/signoff box + // Check for a list of replacement character for symbols in the format file + // ReplaceSymbolChars lets you do one or more of the following with a symbol character: + // - change the point size + // - change the style + // - change the font family + // - change the symbol character + // + // below is taken from the BaseAll format file - is currently commentout and there for reference + // Wolf Creek (WCN) currently uses this to increase the size of the box symbol + // + // + // + // + // get the list of symbol replacements + FormatData fmtdata = (myItemInfo.ActiveFormat != null) ? myItemInfo.ActiveFormat.PlantFormat.FormatData : FormatInfo.PROMSBaseFormat.FormatData; + ReplaceSymbolCharList SymReplaceList = (fmtdata != null && fmtdata.SectData.ReplaceSymbolCharList != null) ? fmtdata.SectData.ReplaceSymbolCharList : null; + // Look at one character at a time + for (int i = 0; i < rtb.TextLength; i++) + { + rtb.Select(i, 1); + if ((rtb.SelectedRtf.Contains("VESymbFix") || rtb.SelectedRtf.Contains(Volian.Base.Library.vlnFont.ProportionalSymbolFont)) && rtb.SelectedText.Length > 0) // C2017-036 get best available proportional font for symbols + { + for (int j = 0; j < SymReplaceList.MaxIndex; j++) + { + ReplaceChar rc = SymReplaceList[j]; + if (rc.Unicode != null && (rc.Family != null || rc.Size != null || rc.Style != null)) + { + char rc_uchar = Convert.ToChar(Convert.ToInt32(rc.Unicode)); + if (rc_uchar == rtb.SelectedText[0]) + { + //use bolding underline italics from local font + System.Drawing.Font fnt = rtb.SelectionFont; + // follow through in fixing an Out of Window Handles bug, use new function to see if + // we can retrieve the font from a dictionary instead a doing a New and using another + // window handle B2017-117 + //System.Drawing.Font fntw = new System.Drawing.Font((rc.Family != null) ? rc.Family : fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); + System.Drawing.Font fntw = VE_Font.GetWinSysFont(rc.Family ?? fnt.FontFamily.Name, (rc.Size != null) ? (float)rc.Size : fnt.Size, (rc.Style != null) ? (System.Drawing.FontStyle)rc.Style : fnt.Style); + rtb.SelectionFont = fntw; + if (rc.Replace != null) + { + char rc_RplChar = Convert.ToChar(Convert.ToInt32(rc.Replace)); + rtb.SelectedText = rc_RplChar.ToString(); + } + changed = true; + break; // break out of foreach loop since we changed the character + } + } + } + } + } + if (changed) + { + if (rtb.Rtf.EndsWith(" \\par\r\n}\r\n") && rtf.EndsWith(" }")) //B2018-060 rtb.RTF added extra new line characters and commands to the end. so remove it. + rtf = rtb.Rtf.Replace(" \\par\r\n}\r\n", " }"); + else + rtf = rtb.Rtf; + return rtf.Replace("", @"\\"); // put back the backslash character + } + } + } + return rtf; + } + + // for Calvert (BGE) alarms, some step text is kept on the same line as its parent. This + // is flagged by the -1 row in the template definition. + private bool KeepOnParentLine(ItemInfo itemInfo) + { + int tindx = itemInfo.TemplateIndex; + if (tindx < 0) return false; + if (itemInfo.ActiveFormat.PlantFormat.FormatData.Templates[tindx].row == -1) return true; + return false; + } + + private void AdjustYOffset(float yDelta) + { + YOffset -= yDelta; + foreach (vlnPrintObject vpo in PartsAbove) + vpo.YOffset -= yDelta; + foreach (vlnParagraph vp in ChildrenBelow) + vp.AdjustYOffset(yDelta); + } + + private void BuildPlacekeeper(vlnParagraph parent, ItemInfo itemInfo) + { + if (itemInfo is SectionInfo && (itemInfo as SectionInfo).SectionConfig.Section_Placekeeper.ToUpper() != "N") // if is a section type and the section is marked to create placekeeper + { + MyPlaceKeeper = new pkParagraph(this); + if (parent != null && parent.MyItemInfo.IsSection) + parent.MyPlaceKeeper = MyPlaceKeeper; + } + else if (parent != null && parent.MyPlaceKeeper != null && itemInfo is StepInfo)//InList(parent.MyItemInfo.ItemID, 513, 514, 519, 520, 525)) + { + if (itemInfo.MyConfig is StepConfig sc && sc.Step_Placekeeper.ToUpper() != "N") + { + if (itemInfo.IsCautionPart || itemInfo.IsNotePart) + MyPlaceKeeper = parent.MyPlaceKeeper.AddCautionsAndNotes(this); + else + MyPlaceKeeper = parent.MyPlaceKeeper.AddChild(this); + } + } + } + + private void BuildContinuousActionSummary(vlnParagraph parent, ItemInfo itemInfo) + { + if (itemInfo is SectionInfo) + { + MyContAct = new pkParagraph(this); + if (parent != null && parent.MyItemInfo.IsSection) + parent.MyContAct = MyContAct; + } + else if (itemInfo is StepInfo) + { + StepConfig sc = itemInfo.MyConfig as StepConfig; + if ((sc != null && sc.Step_CAS == "True") || ((sc == null || sc.Step_CAS == null) && itemInfo.IncludeOnContActSum)) + { + // save this step info for use on the Continuous Action Summary + vlnParagraph tparent = parent; + while (tparent != null && tparent.MyContAct == null) + tparent = tparent.MyParent; + if (parent.MyContAct != null) + { + if (itemInfo.IsCautionPart || itemInfo.IsNotePart) + MyContAct = parent.MyContAct.AddCautionsAndNotes(this); + else + MyContAct = parent.MyContAct.AddChild(this); + } + else + MyContAct = tparent.MyContAct.AddChild(this); + } + } + } + private void BuildTimeCriticalActionSummary(vlnParagraph parent, ItemInfo itemInfo) + { + if (itemInfo is SectionInfo) + { + MyTimeCriticalAction = new pkParagraph(this); + if (parent != null && parent.MyItemInfo.IsSection) + parent.MyTimeCriticalAction = MyTimeCriticalAction; + } + else if (itemInfo is StepInfo) + { + StepConfig sc = itemInfo.MyConfig as StepConfig; + if ((sc != null && sc.Step_TCAS == "True") || ((sc == null || sc.Step_TCAS == null) && itemInfo.IncludeOnTimeCriticalActionSum)) + { + // save this step info for use on the Continuous Action Summary + vlnParagraph tparent = parent; + while (tparent != null && tparent.MyTimeCriticalAction == null) + tparent = tparent.MyParent; + if (parent.MyTimeCriticalAction != null) + { + if (itemInfo.IsCautionPart || itemInfo.IsNotePart) + MyTimeCriticalAction = parent.MyTimeCriticalAction.AddCautionsAndNotes(this); + else + MyTimeCriticalAction = parent.MyTimeCriticalAction.AddChild(this); + } + else + MyTimeCriticalAction = tparent.MyTimeCriticalAction.AddChild(this); + } + } + } + + private vlnParagraph FindParentRNO() => ChildrenRight != null && ChildrenRight.Count > 0 ? ChildrenRight[0] : MyParent.FindParentRNO(); + + private string GetMacroName(string str) => str.Substring(str.IndexOf(@"{!") + 2, str.Length - 3); + + private int TheStepLevel(ItemInfo itemInfo) + { + if (itemInfo.IsHigh) return -1; + int lev = 0; + ItemInfo ii = itemInfo; + while (!ii.MyParent.IsHigh) + { + lev++; + ii = ii.MyParent; + } + return lev; + } + + private void DoCheckOffHeader(PdfContentByte cb, ItemInfo itemInfo, float yLocation, float yTopMargin, float yPageStart) + { + // CheckOffHeaders are handled in two different ways: + // 1) Where the pagelist item puts them - this is at the 'top' of the page, when the current section on the + // page has a checkoff header defined. Support for this is here AND in the VlnSvgPageHelper pagelist code. + // 2) If a continuous section, and it doesn't start at 'top' of the page, then the checkoff header is + // printed on the same line as the continuous section. Support for this is here, the check off header is added + // to the 'PartRight' off of the section's VlnParagraph. + + // First see if there is any checkoff data in the format file and that there + // is a pagelist item for the checkoff header. + int maxindx = itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffList.MaxIndexNoInherit; + if (maxindx <= 0) return; + if (MyPageHelper.PageListCheckOffHeader == null) return; + ItemInfo mySectionInfo = itemInfo.ActiveSection; // C2018-003 fixed use of getting the active section + ItemInfo mySubSectionInfo = itemInfo; + + // If the passed in itemInfo is not a section, get it's parent section. This may be a subsection, so + // it will be found here, versus using 'MyActiveSection' which is the topmost section. The passed in + // item may be a regular step, i.e. if a page break had occurred. + if (!itemInfo.IsSection) + { + while (!mySubSectionInfo.IsSection) + { + mySubSectionInfo = mySubSectionInfo.MyParent; + } + } + else + mySubSectionInfo = (mySectionInfo == null || mySectionInfo.Sections == null) ? null : mySectionInfo.Sections[0]; + + if (mySectionInfo == mySubSectionInfo) mySubSectionInfo = null; + + // The following duplicates the 16bit logic. The 16bit logic only put out a header if: + // there is no subsection and section has a header (from config); + // OR there is a subsection and the first subsection has a header. + // For locating the header in 16bit logic: + // If no subsections, output with section + // If subsections and continuous section, put out on same line as subsection. (done here) + // If subsections and starts at top of page, (on top of page, use pagelist code in VlnSvgPageHelper) + + // Get SectionInfos to access specific section config items... + SectionInfo si = mySectionInfo?.GetSectionInfo(); + int sindx = si.CheckOffHeadingIndex(); + SectionInfo subi = mySubSectionInfo?.GetSectionInfo(); + int subindx = (subi == null) ? -1 : subi.CheckOffHeadingIndex(); + + // if there is no subsections & the main section doesn't use a header OR + // if there is a subsection, & it does not use a header... Return. + if ((subi == null && sindx < 1) || (subi != null && subindx < 1)) return; + + // figure out location now: + // if step, it uses pagelist logic to locate it (this is a page break condition). + // if continuous, put out with subsection if there is one, otherwise section. + // otherwise, use pagelist logic. + bool usePageListCOHdr = false; + + // B2022-129: Barakah - Adjust the INITIAL header location, i.e. make it a pagelist item + if (itemInfo.IsStep || itemInfo.MyDocStyle.AdjSectTitleLoc) + { + usePageListCOHdr = true; + } + // This checks to see if the section is starting at the top of the page. + // If it is, then we want to use PageList to print the checkoff/sighoff header + // else the checkoff/signoff header will be printed across from the section title where ever it is on the page (i.e. section pagination set to continuous) + else if (subi == null) //no subsection + { + // B2021-106 added check if the section has a note or caution + if ((yPageStart - YOffset) == yTopMargin || mySectionInfo.HasCautionOrNote) usePageListCOHdr = true; + } + else // there is a sub-section + { + // B2021-106 added check if the section has a note or caution + if (mySectionInfo == itemInfo && ((yPageStart - YOffset) == yTopMargin) || mySectionInfo.HasCautionOrNote) usePageListCOHdr = true; + if (!usePageListCOHdr && mySubSectionInfo != itemInfo) return; + } + + // grab the string from the format, depending on whether it should get it from the section or subsection. + string cohead = (mySubSectionInfo != null) ? mySubSectionInfo.SectionCheckOffHeader : mySectionInfo?.SectionCheckOffHeader; + if (cohead == "" || cohead == null) return; + + // PageListCheckOffHeader is an svgtext - but really we only need the x/y location for this (pagelist support) + // The actual text is from the checkoff header selection in the section config. + if (cohead != MyPageHelper.PageListLastCheckOffHeader) + { + VE_Font font = mySectionInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList[sindx].Font; + float chkOffY = CalculateYLocation(YTop, yTopMargin); + if (MyPageHelper.YMultiplier != 1) + { + chkOffY = -1 + yTopMargin - (yTopMargin - yLocation) * MyPageHelper.YMultiplier; + if (Rtf != null) + IParagraph.Leading = _SevenLinesPerInch; + } + if (!usePageListCOHdr) + { + vlnText myCOHead = new vlnText(cb, this, cohead, cohead, MyPageHelper.PageListCheckOffHeader.X.Value + (float)MyItemInfo.MyDocStyle.Layout.LeftMargin, chkOffY, font); + PartsRight.Add(myCOHead); + } + else + MyPageHelper.PageListTopCheckOffHeader = cohead; + MyPageHelper.PageListLastCheckOffHeader = cohead; + } + } + internal vlnParagraph BottomChild + { + get + { + float bottomChildYBottomText = YBottomText; + vlnParagraph bottomChild = this; + foreach (vlnParagraph child in ChildrenRight) + { + vlnParagraph grandChild = child.BottomChild; + if (grandChild != null && grandChild.YBottomText > bottomChildYBottomText) bottomChild = grandChild; + if (grandChild != null && grandChild.YBottomText == bottomChildYBottomText && grandChild.MyItemInfo.HasChangeBar) bottomChild = grandChild; + bottomChildYBottomText = bottomChild.YBottomText; + } + foreach (vlnParagraph child in ChildrenBelow) + { + vlnParagraph grandChild = child.BottomChild; + if (grandChild != null && grandChild.YBottomText > bottomChildYBottomText) bottomChild = grandChild; + if (grandChild != null && grandChild.YBottomText == bottomChildYBottomText && grandChild.MyItemInfo.HasChangeBar) bottomChild = grandChild; + bottomChildYBottomText = bottomChild.YBottomText; + } + return bottomChild; + } + } + private void CalculateXOffsetGridOrFigure(ItemInfo itemInfo, FormatInfo formatInfo) + { + float scale = itemInfo.IsRtfRaw ? 0.6f : 1.0f; + bool aerTableOrFigure = itemInfo.FormatStepData.Type.Contains("AER"); + vlnParagraph hls1 = MyParent; + if (!formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && !itemInfo.IsInSupInfo) + while (hls1.MyParent != null && !hls1.MyItemInfo.IsHigh) hls1 = hls1.MyParent; + else if (itemInfo.IsInSupInfo) + while (hls1.MyParent != null && !hls1.MyItemInfo.IsSupInfoPart) hls1 = hls1.MyParent; + float colR = float.Parse(formatInfo.MyStepSectionLayoutData.ColRTable.Split(",".ToCharArray())[itemInfo.ColumnMode]); + float xLowerLimit = (aerTableOrFigure && hls1.PartsLeft != null && hls1.PartsLeft.Count > 0) ? hls1.PartsLeft[0].XOffset : hls1.XOffset; + float pageWidth = ((float)itemInfo.ActiveSection.MyDocStyle.Layout.PageWidth); // C2018-003 fixed use of getting the active section + float leftMargin = ((float)itemInfo.ActiveSection.MyDocStyle.Layout.LeftMargin); // C2018-003 fixed use of getting the active section + float xUpperLimit; + if (itemInfo.IsInRNO) + // if in rno column, the upper limit is width of the page (right margin). Subtract off size of a character + xUpperLimit = pageWidth - (72 / (float)MyItemInfo.FormatStepData.Font.CPI); + else + // in the following calculation, the hls width (hls1.Width) == rno column width, so xUpperLimit is + // the around the right margin, i.e. 'hls xoffset' + 'location of rno (colR) * columnmode' + 'width of rno' + xUpperLimit = hls1.XOffset + hls1.Width + hls1.CheckOffWidth + colR * itemInfo.ColumnMode; + + // If a table is within the alarm section and its parent is a template item is single column + // adjust the xoffset so that the table is centered around center of page + bool ctrCalvertAlarmTbl = false; + if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + ctrCalvertAlarmTbl = MyItemInfo.IsWithInSingleColumnTemplate(); + // B2019-049 added check for table being in a Caution or Note - if so, use the single column setting for the format variable TableCenterPos + float TableCenterPos = float.Parse(formatInfo.MyStepSectionLayoutData.TableCenterPos.Split(",".ToCharArray())[(itemInfo.IsInCautionOrNote) ? 0 : itemInfo.ColumnMode]); + if (ctrCalvertAlarmTbl || formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TieTabToLevel) + XOffset = leftMargin + (pageWidth - leftMargin - (scale * Width)) / 2; + else + { + if (!aerTableOrFigure && itemInfo.RNOLevel == 0 && TableCenterPos != 0) // Only adjust TableCenterPos for Non-RNO Cenetered Tables + { + XOffset = TableCenterPos; + XOffset = XOffset - (this.Width / 2) + (float)itemInfo.MyDocStyle.Layout.LeftMargin; + } + else if (itemInfo.RNOLevel != 0) // RNO + XOffset = MyParent.XOffset + (MyParent.Width / 2) - ((scale * Width) / 2); + else if (aerTableOrFigure) + { + // if in the BGE alarm format and the hls is a Window (upper right corner when it prints), use the parent of the table + // to print in aer column (B2014-105) + if (MyItemInfo.IsInCalvertConditionResponse) + XOffset = hls1.XOffset + hls1.Width / 2 - Width / 2; + else + XOffset = MyHighLevelParagraph.XOffset + MyHighLevelParagraph.Width / 2 - Width / 2; + } + else // Centered Table or Figure + { + // Determine center of hls + XOffset = hls1.XOffset + hls1.Width / 2; + // Determine left edge of the table by subtracting 1/2 of its width. + XOffset -= Width / 2; + // Add in 1/2 of the width of all RNO columns + XOffset += (colR * itemInfo.ColumnMode) / 2; + + if (!aerTableOrFigure && !MyItemInfo.IsRtfRaw) + { + // 05/14/12 - 16bit code adjusts the center depending upon the CPI of the table font. + // Start with XOffset of table, then calculate the XOffset adjusted for the table font, + // based on the default CPI of 12. Adjust the XOffset by the difference of these + // two numbers. + XOffset -= (XOffset - (XOffset * (float)MyItemInfo.FormatStepData.Font.CPI / 12)); + } + XOffset -= 12; // This makes the 16bit & 32bit align very closely. + // if outside of the page margins then center within the page margins + float xOffset2 = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + float xWidth2 = (float)itemInfo.MyDocStyle.Layout.PageWidth; + if (XOffset + Width > xOffset2 + xWidth2) + XOffset = xOffset2 / 2 + xWidth2 / 2 - Width / 2; + + } + // 05/14/12 - The PosAdjust is a format flag from 16bit. For WCN2, it appears that this amount equals + // the amount of difference from a 10 CPI to a 12 CPI font. See comment above. + float posAdjust = (float)(itemInfo.FormatStepData.StepPrintData.PosAdjust ?? 0); + if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.StepPrintData != null && + posAdjust > 0) + { + if (Width < hls1.Width - posAdjust) + XOffset += posAdjust; + else if (Width < hls1.Width) + XOffset = hls1.XOffset + hls1.Width - Width; // align with the right edge of hls text + } + } + if (itemInfo.MyDocStyle.Layout.CenterToStepThenPage) + { + if (Width > hls1.Width) + { + float XOffsetPage = leftMargin + ((pageWidth - leftMargin) - Width) / 2; + float fraction = (Width - hls1.Width) / ((pageWidth - leftMargin) - hls1.Width); + float XOffsetNew = (1 - fraction) * XOffset + fraction * XOffsetPage; + _MyLog.WarnFormat("***XOffsetAdjust-CenterToStepThenPage*** ItemID, XOffset, XOffsetPage, XOffsetNew ={0},{1},{2},{3}", itemInfo.ItemID, XOffset, XOffsetPage, XOffsetNew); + XOffset = XOffsetNew; + } + } + else + { + // if the XOffset < High Level Step Text's XOffset , then align with the High Level Step Text' + // B2020-161 - needed to substract the checkoff width when deterniming the XOffset + // fixes centered tables in Calvert Unit 2 STP O-90-2 step 6.3.A + if (XOffset < xLowerLimit && Width < (xUpperLimit - xLowerLimit - hls1.CheckOffWidth)) + XOffset = xLowerLimit; + + // if the right margin exceeds the right edge of the rightmost RNO, then adjust right edge to match. + // In lines below, the 12 was used for Wolf Creek 2 column format, the pagewidth goes beyond the right border line so that + // the tables, figures & equations were beyond the border. -12 takes it enough so that if boxed, it won't print out of border + // We know this is not ideal. + if (MyItemInfo.IsRtfRaw && (XOffset + (scale * Width) > xUpperLimit - 12)) + XOffset = xUpperLimit - (scale * Width) - 12; + if (!MyItemInfo.IsRtfRaw && XOffset + Width > xUpperLimit) + XOffset = xUpperLimit - Width; + // because of the above, if it pushes beyond the left margin, use the left margin. + if (XOffset < (float)itemInfo.MyDocStyle.Layout.LeftMargin) + XOffset = XOffsetBox = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + } + } + private float AdjustForBlankLines() + { + if (MyParent != null && MyParent.MyItemInfo.FormatStepData != null && MyParent.MyItemInfo.FormatStepData.Type == "TitleWithTextRight") return 0; + // F2022-121 added SpecialStepsFoldoutKeepWhiteSpace flag to allow for all of the other special foldout formatting, but + // not compress the page + if (MyItemInfo.MyDocStyle.SpecialStepsFoldout && !MyItemInfo.MyDocStyle.SpecialStepsFoldoutKeepWhiteSpace) return 0; + if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.Prefix != null && MyItemInfo.FormatStepData.Suffix != null && MyItemInfo.FormatStepData.UseSmartTemplate) return 0; + int everyNLines = MyItemInfo.FormatStepData == null ? 1 : MyItemInfo.FormatStepData.StepLayoutData.EveryNLines ?? 1; + if (everyNLines == -99) return 0; + if (everyNLines == -1) return -SixLinesPerInch; + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || + (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert && MyItemInfo.IsStep && MyItemInfo.FormatStepData.StepLayoutData.STBoxindex != null)) + { + if ((MyItemInfo.IsCaution || MyItemInfo.IsNote || MyItemInfo.MyParent.IsCaution || MyItemInfo.MyParent.IsNote) && !MyItemInfo.FormatStepData.SpaceIn + && (MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) + && (MyItemInfo.NextItem == null || MyItemInfo.MyContent.Type != MyItemInfo.NextItem.MyContent.Type)) + { + // C2014-009: Don't add another blank line - print the calvert Condition/Response RNO Caution/Notes without it. + if (!(MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && MyItemInfo.IsInRNO)) + return 0; + } + //B2020-117 for multiple Calvert Condition/Response Cautions,Note, and Warnings, do add an extra blank line + // between them + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && + MyItemInfo.IsInRNO && (MyItemInfo.IsCaution || MyItemInfo.IsNote) && + MyItemInfo != MyItemInfo.LastSibling) + return 0; + if (everyNLines == 99 && MyItemInfo.NextItem == null) + { + if (MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0 && MyItemInfo.Steps[0].MyContent.Type == MyItemInfo.MyContent.Type) return 0; + if (MyItemInfo.MyParent.NextItem != null && MyItemInfo.MyParent.NextItem.MyContent.Type == MyItemInfo.MyContent.Type) return 0; + } + } + // B2015-005: if there isn't a blank line after this step && it has children, see if there shouldn't be + // a blank line, i.e. if the first substep child's type is the same as this. + if (!MyItemInfo.IsHigh && everyNLines == 99 && MyItemInfo.NextItem == null && MyItemInfo.HasChildren) + { + ItemInfo chld = MyItemInfo.FirstChild(E_FromType.Step); + if (chld != null && chld.MyContent.Type == MyItemInfo.MyContent.Type) return 0; + } + // F2021-033: No blank line between hls and its first substep: + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoBlankHlsAndFirstSub && MyItemInfo.IsHigh) + { + // F2021-060 Do not remove blank line between step and Caution, Note or Warning below it (Caution, Note, Warning are off 1st sub step) + if (MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0 && !MyItemInfo.Steps[0].HasCautionOrNote) return 0; + } + // F2021-025: Barakah single column no blank line between last Note/Caution/Warning text and bottom line of box + // C2021-049: Barakah no blank line between last Note/Caution/Warning text, include sub-step text by using 'IsInCautionOrNote' + // B2022-017: Barakah within note/caution, if note has substeps, there should be a blank line between note & 1st substep + // B2022-027: Barakah blank line not printing after list within another list. Rewrote code for all of these issues so that + // code looks up parents to see if they have next before returning a 0 (no blank line) + // B2022-042: double Caution followed by Critical Step missing bullet + // F2022-010: substeps in multiple notes, cautions, warning print differently + if (MyItemInfo.IsInCautionOrNote) + { + float adjLastBlankLineInNoteCautionWarning = 0; + // Get the box information for the Note, Caution, or Warning + ItemInfo tifo = (MyItemInfo.IsCaution || MyItemInfo.IsNote) ? MyItemInfo : MyItemInfo.ParentNoteOrCaution; + int typ = ((int)tifo.MyContent.Type) % 10000; + int? bxIndx = tifo.ActiveFormat.PlantFormat.FormatData.StepDataList[typ].StepLayoutData.STBoxindex; + if (bxIndx != null) + { + Box bx = tifo.ActiveFormat.PlantFormat.FormatData.BoxList[(int)bxIndx]; + // F2024-078 save the adjustment of the last blank line - this value will be added to the SixLinesPerInch value (a blank line) + adjLastBlankLineInNoteCautionWarning = (float)(bx.AdjLastBlnkLn ?? 0); + } + // F2024-078 added check for adjustment of the last blank line in the Note/Caution box + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.NoBlankLastNoteCautionWarn || adjLastBlankLineInNoteCautionWarning != 0) + { + if ((MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) && (MyItemInfo.NextItem == null)) // there are no sub-steps, see if any parents have next + { + ItemInfo par = MyItemInfo.MyParent; + while (par.IsInCautionOrNote) // while in the caution or note, see if there is anything below this item + { + // if there is no next item, or content types are different, go up to see if the parent has any next item. If note + // keep going up tree, otherwise there is a next so don't return 0, i.e. continue on with code to determine + // whether there is a blank line + if ((par.NextItem == null) || (par.MyContent.Type != par.NextItem.MyContent.Type)) par = par.MyParent; + else break; + } + if (!par.IsInCautionOrNote || (par != null && par.MyContent.Type != par.NextItem.MyContent.Type)) + { + if (adjLastBlankLineInNoteCautionWarning != 0) + return SixLinesPerInch + adjLastBlankLineInNoteCautionWarning; // F2024-078 adjust the size of the last blank line of Note/Caution box + else + return 0; // no blank line after last text line of Note/Caution/Warning + } + } + if ((MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) && MyItemInfo.NextItem != null && MyItemInfo.MyContent.Type != MyItemInfo.NextItem.MyContent.Type) + { + if (adjLastBlankLineInNoteCautionWarning != 0) + return SixLinesPerInch + adjLastBlankLineInNoteCautionWarning; + else + return 0; // no blank line after last text line of Note/Caution/Warning + } + } + } + if (MyItemInfo.Ordinal % everyNLines == 0 || MyItemInfo.NextItem == null) return SixLinesPerInch; + // B2022-003: BNPP Alarms (BNPPalr) - incorrect line spacing for substeps off substeps. Added a format flag so as not to affect other plants. + if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.StepPrintData != null && MyItemInfo.FormatStepData.StepPrintData.BlankAfterSubWithSub && MyItemInfo.NextItem != null && MyItemInfo.HasChildren && MyItemInfo.Steps != null && MyItemInfo.Steps.Count > 0) return SixLinesPerInch; + + // If the next table child is a figure, equation or a visio drawing add a blank line + if (MyItemInfo.Tables != null && MyItemInfo.Tables.Count > 0 && MyItemInfo.Tables[0].MyContent.MyGrid == null) return SixLinesPerInch; + return 0; + } + private void AddMacros(ItemInfo itemInfo, vlnTab mytab) + { + float y = YOffset; + float x = mytab == null ? XOffset : mytab.XOffset + mytab.TabOffset; + List myMacros = itemInfo.MyMacros; + if (myMacros != null) + { + int colMode = (MyItemInfo.ActiveSection != null) ? MyItemInfo.ActiveSection.ColumnMode : 0; // C2018-003 fixed use of getting the active section + foreach (Macro myMacro in myMacros) + { + // if the format has the 'LocWithXOff' locate the macro along with the tab's offset. + // however, if the tab is more than 2 characters long, adjust so that it aligns with the + // last two characters, not the first 2. + string tabText = mytab?.Text.Trim(" .".ToCharArray()); + int tablen = (tabText == null) ? 0 : (tabText.Length <= 2) ? 0 : tabText.Length - 2; + if (myMacro.LocWithXOff ?? false) x = mytab == null ? XOffset : ((float)mytab.XOffset + (tablen * (float)mytab.MyFont.CharsToTwips)); + if (colMode == 0 && myMacro.SingleColMacroDef != null && myMacro.SingleColMacroDef.Length > 0) + { + float macroXOffset = myMacro.MacroXOffSet ?? 0; + float widthAdj = myMacro.SingleColWidthAdjust ?? 0; // set as negative number in format + float rightTextEdge = (itemInfo.IsHigh) ? XOffset + Width + mytab.XOffset : this.MyHighLevelParagraph.XOffset + this.MyHighLevelParagraph.Width; + x = (macroXOffset > 0) ? macroXOffset : rightTextEdge; + if (rightTextEdge > x) + Width += widthAdj; + PartsRight.Add(new vlnMacro(x, y, myMacro.SingleColMacroDef)); + } + else + PartsLeft.Add(new vlnMacro(x, y, myMacro.MacroDef)); + } + } + } + // HLP Change bar flags in format file: + // Locations: With Text, Outside Box, AER on Left RNO on Right, To The Left of Text + // Text: Date & Change ID, Revision Number, Change ID, None, Custom (use input data) + // Flag AERChgBarMsgRNOChgBarNoMsg and AERMsgRNONoMsg are NOT Used in 16-bit. + private string cbMess = null; + private vlnChangeBar DoChangeBar(PdfContentByte cb, ItemInfo itemInfo, VlnSvgPageHelper myPageHelper, float xoff, float yoff, int maxRNO, FormatInfo formatInfo) //, vlnChangeBar myCB) + { + ChangeBarData cbd = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData; + float cols = formatInfo.MyStepSectionLayoutData.ColS ?? 0; + float colr = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); + // FixedChangeColumn + - Column location for change bars + // 0 - Separate AER and RNO change bars to the right of the text + // -10 to -1 - Change bars on left (specify # of columns from the text) + // <-10 - AER change bars on the left and RNO change bars on the right. + // FixedAERChangeColumn overrides the -5 default setting in chgbar.c, value is converted to a negative by the code + + float col = (cbd.AbsoluteFixedChangeColumn) ? + ((cbd.FixedAERChangeColumn ?? 0) > 0) ? + (xoff > (cols + colr + COL_WID_ADJ)) ? + cbd.FixedChangeColumn ?? 0 : AERLeftChangeBarLocation(formatInfo) : + cbd.FixedChangeColumn ?? 0 : ChangeBarLocation(xoff, this, formatInfo, maxRNO); + string chgIdTxt = null; + if (itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds) + { + chgIdTxt = !(itemInfo.MyConfig is StepConfig sc) ? null : sc.Step_ChangeID; + } + if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.ChgID) + cbMess = chgIdTxt ?? itemInfo.MyContent.UserID; + else if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.DateChgID) + { + string fmtDate = itemInfo.MyContent.DTS.ToShortDateString(); + if (fmtDate.Length != 10) // need to add zeros + { + if (fmtDate.IndexOf("/") == 1) + fmtDate = "0" + fmtDate; + if (fmtDate.IndexOf("/", 3) == 1) + fmtDate = $"{fmtDate.Substring(0, 3)}0{fmtDate.Substring(3, fmtDate.Length - 3)}"; + } + cbMess = $@"{chgIdTxt ?? itemInfo.MyContent.UserID}\n{fmtDate}"; + } + else if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.RevNum) + { + + string lRev = myPageHelper.Rev; + // Now check the format flags to determine if/how the Rev string should be parsed. + if ((itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate && lRev.Contains("/")) + || (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.RevDateWithForwardSlash && lRev.Contains("\\"))) + { + int indx = lRev.IndexOf(itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.DoRevDate ? '/' : '\\'); + cbMess = lRev.Substring(0, indx > -1 ? indx : lRev.Length); + } + else + cbMess = lRev; + } + else if (myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.UserDef) + cbMess = myPageHelper.ChangeBarDefinition.MyChangeBarMessage; + + int msgAlign = Element.ALIGN_LEFT; + if (myPageHelper.ChangeBarDefinition.MyChangeBarLoc == PrintChangeBarLoc.LeftOfText || + (myPageHelper.ChangeBarDefinition.MyChangeBarLoc == PrintChangeBarLoc.AERleftRNOright && + !itemInfo.IsInRNO)) msgAlign = Element.ALIGN_RIGHT; + float coltotwips = col * itemInfo.FormatStepData.Font.CharsToTwips; + if (cbd.AbsoluteFixedChangeColumn) coltotwips = col * itemInfo.ActiveFormat.PlantFormat.FormatData.Font.CharsToTwips; + // B2023-052: Beaver Valley - Inconsistent change bar location - used AbsoluteFixedChangeColumn flag, but the LeftMargin + // was still added in, thus sections had different locations for change bar if sections had different left margin. Use + // adjustment, 'AbsChgBarAdj' + coltotwips += itemInfo.MyDocStyle.Layout.AbsChgBarAdj ?? 0; + if (itemInfo.IsFigure) coltotwips = col * itemInfo.ActiveFormat.PlantFormat.FormatData.Font.CharsToTwips; + return new vlnChangeBar(cb, this, (float)itemInfo.MyDocStyle.Layout.LeftMargin + coltotwips, yoff, msgAlign, + myPageHelper.ChangeBarDefinition.MyChangeBarText == PrintChangeBarText.RevNum, + itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeIds); + } + + // changed this function to return a float instead of an int to correct a rounding error which cause change bars + // to inconsistantly position next to changed text. Bug B2015-033 + private float ChangeBarLocation(float c, vlnParagraph paragraph, FormatInfo formatInfo, int maxRNO) + { + int fixedChgCol = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData.FixedChangeColumn ?? 0; + float cols = formatInfo.MyStepSectionLayoutData.ColS ?? 0; + int colr = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); + float tmpc = c; + Box bxCautNote = null; // used for notes and cautions in the Prairie Island Alarms format + if (MyItemInfo.IsCaution || MyItemInfo.IsNote) + { + // Temporary fix for change bars on Notes and Cautions where the FixedChgCol < -10 + tmpc = (float)formatInfo.MyStepSectionLayoutData.ColT + (float)formatInfo.MyStepSectionLayoutData.WidT; // end position of Caution / Note + int typ = (int)(MyItemInfo.MyContent.Type % 10000); + int? bxIndx = formatInfo.PlantFormat.FormatData.StepDataList[typ].StepLayoutData.STBoxindex; + if (bxIndx != null) + { + bxCautNote = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; + if (bxCautNote != null) + tmpc = (float)bxCautNote.Start + (float)bxCautNote.End; // end position of a boxed Caution / Note + } + } + // if this is a caution or note, put the change bar to the right of the text: + if ((fixedChgCol == 0)) + { + float rightEdge = (paragraph.XOffset + paragraph.Width + 5); + rightEdge -= (float)paragraph.MyItemInfo.MyDocStyle.Layout.LeftMargin; + if (bxCautNote != null) + rightEdge = (float)bxCautNote.End + 10; // used for notes and cautions in the Prairie Island Alarms format + rightEdge /= paragraph.MyItemInfo.FormatStepData.Font.CharsToTwips; + return MyItemInfo.IsFigure ? rightEdge + 1 : rightEdge; // B2017-111: Add a little more space between figure & change bar + } + if (fixedChgCol < -10 || fixedChgCol >= 0) + return ((fixedChgCol > 0) ? fixedChgCol : + (fixedChgCol == 0) ? (int)c + 1 : + (tmpc > (cols + colr + COL_WID_ADJ)) ? -fixedChgCol : + AERLeftChangeBarLocation(formatInfo)); + else + return (fixedChgCol + (((c < cols + Width + colr) + || MyItemInfo.IsCaution || MyItemInfo.IsNote) ? 0 : cols + colr)); + /* Change bars to left of text -- ColS+WidS+ColR is the end of RNO col*/ + } + /* + ** Centered tables whose width exceeds the end of the RNO column should + ** still have their change bars printed on the left. + */ + private float GetBottomYoff(float bottomY) + { + foreach (vlnParagraph child in ChildrenBelow) + { + if (child.YOffset > bottomY) bottomY = child.YOffset; + bottomY = child.GetBottomYoff(bottomY); + } + return bottomY; + } + private int AERLeftChangeBarLocation(FormatInfo formatInfo) + { + // use -5 default unless it is format specified + int fixedAERChgCol = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData.FixedAERChangeColumn ?? 0; + return (fixedAERChgCol != 0) ? + (fixedAERChgCol > 100) ? + (fixedAERChgCol % 100) : -fixedAERChgCol : -5; + } + private StringBuilder _RtfSB = null; + public string GetRtf(ItemInfo itemInfo, string prefix, string suffix) + { + int profileDepth = ProfileTimer.Push(">>>> GetRtf"); + _RtfSB = new StringBuilder(); + DisplayText vlntxt = new DisplayText(itemInfo, E_EditPrintMode.Print, E_ViewMode.View, true, E_FieldToEdit.StepText, false, prefix, suffix, MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndSpaces != null); + + //C2025-021 Add logic to PROMS to support a special High Level Step type that is not printed. + if (itemInfo.IsType("InvisibleHigh")) + { + System.Drawing.Font myHighFont = vlntxt.TextFont.WindowsFont; + _RtfSB.Append(AddFontTable(myHighFont)); + _RtfSB.Append("}"); + string rtfHigh = _RtfSB.ToString(); + ProfileTimer.Pop(profileDepth); + return rtfHigh; + } + + // C2021-010: Remove trailing returns/spaces & manual page breaks & allow save. + if (DisplayText.RemoveTrailingBlankID > 0 && !MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndSpaces.Contains(itemInfo.ItemID)) MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndSpaces.Add(DisplayText.RemoveTrailingBlankID); + System.Drawing.Font myFont = vlntxt.TextFont.WindowsFont; + if (!itemInfo.IsTable && StepRTB.MyFontFamily != null) + // follow through in fixing an Out of Window Handles bug, use new function to see if + // we can retrieve the font from a dictionary instead a doing a New and using another + // window handle B2017-117 + //myFont = new System.Drawing.Font(StepRTB.MyFontFamily, myFont.Size, myFont.Style); + myFont = VE_Font.GetWinSysFont(StepRTB.MyFontFamily, myFont.Size, myFont.Style); + + string stText; // if Calvert (BGE) Alarms, the text is included in the macro, so save text as a blank: + if (HasCalvertMacro) + { + stText = " "; + // turn underline off + // follow through in fixing an Out of Window Handles bug, use new function to see if + // we can retrieve the font from a dictionary instead a doing a New and using another + // window handle B2017-117 + myFont = VE_Font.GetWinSysFont(myFont.FontFamily, myFont.Size, System.Drawing.FontStyle.Regular); //myFont.Style. | FontStyle.Underline); + } + else + stText = vlntxt.StartText; + + if (itemInfo.IsHigh && itemInfo.MyDocStyle.UndSpecialStepsFoldout) + { + // follow through in fixing an Out of Window Handles bug, use new function to see if + // we can retrieve the font from a dictionary instead a doing a New and using another + // window handle B2017-117 + myFont = VE_Font.GetWinSysFont(myFont.FontFamily, myFont.Size, myFont.Style | System.Drawing.FontStyle.Underline); + stText = stText.Replace(@"\ulnone ", ""); + stText = stText.Replace(@"\ulnone", ""); + } + if (stText.Contains("{IND}")) stText = stText.Replace("{IND}", "\x5"); + if (itemInfo.IsSection && itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.SectionNumber.Level0Big && itemInfo.MyParent.IsProcedure) + // follow through in fixing an Out of Window Handles bug, use new function to see if + // we can retrieve the font from a dictionary instead a doing a New and using another + // window handle B2017-117 + myFont = VE_Font.GetWinSysFont(myFont.FontFamily, 14, myFont.Style | System.Drawing.FontStyle.Bold); + _RtfSB.Append(AddFontTable(myFont)); + _RtfSB.Append(stText); + if (MyItemInfo.IsStep && !itemInfo.FormatStepData.UseSmartTemplate && MyItemInfo.FormatStepData.Suffix != null && MyItemInfo.FormatStepData.Suffix != "") + _RtfSB.Append(MyItemInfo.FormatStepData.Suffix.Replace("{ulnone}", @"\ulnone ")); + _RtfSB.Append("}"); + string rtf = _RtfSB.ToString(); + UnderlineTerminateList utl = MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.UnderlineTerminateList; + if (utl != null && myFont.Underline) + { + foreach (UnderlineTerminate ut in utl) + { + MatchCollection mc = Regex.Matches(rtf, "(? 0) + { + Match m = mc[mc.Count - 1]; + rtf = rtf.Substring(0, m.Index) + @"\ulnone " + rtf.Substring(m.Index); + } + } + } + ProfileTimer.Pop(profileDepth); + return rtf; + } + + public float XOffsetBox { get; set; } = 0; + private readonly float _MyBoxLeftAdj = 0; + private float SetHeader(vlnParagraph para, PdfContentByte cb, ItemInfo itemInfo, FormatInfo formatInfo) + { + float xoff = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + // The '6' below is really converting from characters to Twips. But instead of considering the CPI, 16bit assumed + // it was 12 to center the header. That's where the 6 comes from. + float hdrWidth = (itemInfo.MyHeader.CleanText == null) ? 0 : itemInfo.MyHeader.CleanText.Length * 6; + int typ = ((int)itemInfo.MyContent.Type) % 10000; + int? bxIndx = formatInfo.PlantFormat.FormatData.StepDataList[typ].StepLayoutData.STBoxindex; + float adjmentAfterBoxedNoteCautionTab = 0; // F2024-078 used to save the adjustment of the space after the Note/Caution tab + + if (itemInfo.MyHeader.Justify == System.Drawing.ContentAlignment.MiddleCenter) + { + if (bxIndx != null) + { + Box bx = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; + if (bx.TabPos > 0) + xoff += (float)bx.TabPos; // xoff starts as left margin + else + xoff += (float)((bx.TxtStart + _MyBoxLeftAdj + XOffsetBox + (bx.TxtWidth / 2)) - (hdrWidth / 2)); // xoff starts as left margin + adjmentAfterBoxedNoteCautionTab = (float)(bx.AdjSpAftTab ?? 0); // F2024-078 save the adjustment of the space (line) after the Note/Caution tab + } + else if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && itemInfo.IsInRNO && (itemInfo.IsCaution || itemInfo.IsNote)) // C2014-009 + xoff = XOffset + (para.Width / 2) - (hdrWidth / 2); + else if (formatInfo.MyStepSectionLayoutData.Separator.Location > 0) + xoff = XOffset + AdjustToCharPosition((float)((para.Width - hdrWidth) / formatInfo.MyStepSectionLayoutData.Separator.Location), itemInfo.MyHeader.MyFont.CPI); + else if (itemInfo.IsInRNO && itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].NumberWithLevel) + xoff = XOffset + (para.Width / 2) - (hdrWidth / 2); + else if (itemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].NumberWithLevel) + xoff = XOffset + (para.Width / 2) - (hdrWidth / 2); + else + xoff = XOffset + (para.Width / 2) + (hdrWidth / 2); // XOffset has left margin included + } + else + xoff = XOffset; // XOffset has left margin included + // KEEP: This may be needed in the future to fix location of 'OR's when Separator location="0" + // the following code would place the 'OR' at the location of the tab rather than text. This + // is how 16bit was. However, a number of plants had been sent out with the xoffset at the xlocation + // of text (does not match 16bit) when this was found for BGE OI3/OI-1B/6.1.B.4. Previous releases + // went to CAT, MCG, FPL, NSP. + //{ + // if (this.MyTab != null) + // xoff = this.MyTab.XOffset; + // else + // xoff = XOffset; + //} + // B2018-096 AEP 082.002CD Note Box overlapping Step Box + vlnHeader myHeader = new vlnHeader(this, cb, itemInfo.MyHeader.Text, itemInfo.MyHeader.CleanText.TrimStart(" ".ToCharArray()), xoff + AdjustHeader + _MyBoxLeftAdj, YOffset, itemInfo.MyHeader.MyFont); + PartsAbove.Add(myHeader); + // Only use SpaceIn property for Cautions or Notes + bool bSpaceIn = !MyItemInfo.IsCaution && !MyItemInfo.IsNote || MyItemInfo.FormatStepData.SpaceIn; + // F2022-121 added SpecialStepsFoldoutKeepWhiteSpace flag to allow for all of the other special foldout formatting, but + // not compress the page - this need to handle explicit OR and AND sub-steps to ensure there are blank lines before and after + // the separator text. + return myHeader.Height + (!MyItemInfo.MyDocStyle.SpecialStepsFoldout || (MyItemInfo.MyDocStyle.SpecialStepsFoldout && MyItemInfo.MyDocStyle.SpecialStepsFoldoutKeepWhiteSpace) || (MyItemInfo.MyDocStyle.ExtraLineHeader && (MyItemInfo.IsCaution || MyItemInfo.IsNote)) ? bSpaceIn ? SixLinesPerInch : 0 : 0) + adjmentAfterBoxedNoteCautionTab; // F2024-078 add adjustment to the space after the Note/Caution tab + } + private float AdjustToCharPosition(float position, float? CPI) + { + int iPosition = (int)position; + int charsToTwips = (int)(72 / (CPI ?? 12)); + iPosition = (iPosition / charsToTwips) * charsToTwips; + return (float)iPosition; + } + + public bool SectionPageBreak { get; set; } = false; + public bool Processed { get; set; } = false; + public vlnParagraph LastRNO { get; set; } + public vlnParagraph MyTopRNO { get; set; } + public static string PathPrefix { get; set; } = ""; + protected float _YBottomMost; // Bottom of the paragraph including the children + public float YBottomMost + { + get + { + return _YBottomMost; + } + set + { + _YBottomMost = value; + } + } + + protected float YBottomPagination { get; set; } + protected float _YBottomMostAdjust = 0; // the RNO separator is outside asterisk box, account for additional Y space + public float YBottomMostAdjust + { + get { return _YBottomMostAdjust; } + set { _YBottomMostAdjust = value; } + } + protected float _YTopMost; // Top of the paragraph including the children + public float YTopMost + { + get { return _YTopMost; } + set { _YTopMost = value; } + } + protected float _YTop; // Top of the paragraph including parts + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "vp kept due to possible side effect code")] + public float YTop + { + get { return _YTop; } + set + { + vlnParagraph vp = this as vlnParagraph; + _YTop = value; + + } + } + // If we're in a smart template (WCNCKL checklists) then account for the bottom line in the + // table. + public float SmartTemplateAdjust => (MyItemInfo.IsHigh && MyItemInfo.FormatStepData.UseSmartTemplate) ? SixLinesPerInch : 0; + public float YSize // How big this paragraph is with all of its children + { + get + { + float ysize = SmartTemplateAdjust + _YBottomMost - _YTopMost; + if (MyItemInfo.IsHigh && ((MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DoubleBoxHLS) == E_DocStructStyle.DoubleBoxHLS)) + ysize += SixLinesPerInch; + return ysize; + } + } + + public ItemInfo MyItemInfo { get; set; } + private vlnParagraph _MyHighLevelParagraph; + + public vlnParagraph MyHighLevelParagraph + { + get + { + if (_MyHighLevelParagraph == null) + { + _MyHighLevelParagraph = GetHighLevelParagraph(); + } + return _MyHighLevelParagraph; + } + } + private vlnParagraph GetHighLevelParagraph() => MyItemInfo.IsHigh ? this : MyParent.GetHighLevelParagraph(); + private vlnParagraph _SupInfoSection; + public vlnParagraph SupInfoSection + { + get + { + if (_SupInfoSection == null) + { + _SupInfoSection = GetSupInfoSectionParagraph(); + } + return _SupInfoSection; + } + } + private vlnParagraph GetSupInfoSectionParagraph() => MyItemInfo.IsSection ? this._SupInfoSection : MyParent.GetSupInfoSectionParagraph(); + // Tab, Separator, ChangeBar, Box, Circle, Checkoff + private vlnTab _MyTab; + public vlnTab MyTab + { + get + { + if (_MyTab == null) + { + foreach (vlnPrintObject po in PartsLeft) + { + if (po is vlnTab) + { + _MyTab = po as vlnTab; + break; + } + } + } + return _MyTab; + } + } + private vlnPrintObjects _PartsAbove; + public vlnPrintObjects PartsAbove + { + get + { + if (_PartsAbove == null) _PartsAbove = new vlnPrintObjects(); + return _PartsAbove; + } + } + private vlnPrintObjects _PartsBelow; + public vlnPrintObjects PartsBelow + { + get + { + if (_PartsBelow == null) _PartsBelow = new vlnPrintObjects(); + return _PartsBelow; + } + } + private vlnPrintObjects _PartsRight; + public vlnPrintObjects PartsRight + { + get + { + if (_PartsRight == null) _PartsRight = new vlnPrintObjects(); + return _PartsRight; + } + } + private vlnPrintObjects _PartsLeft; + public vlnPrintObjects PartsLeft + { + get + { + if (_PartsLeft == null) _PartsLeft = new vlnPrintObjects(); + return _PartsLeft; + } + } + private vlnPrintObjects _PartsContainer; + public vlnPrintObjects PartsContainer + { + get + { + if (_PartsContainer == null) _PartsContainer = new vlnPrintObjects(); + return _PartsContainer; + } + } + private vlnParagraphs _ChildrenAbove; + public vlnParagraphs ChildrenAbove + { + get + { + if (_ChildrenAbove == null) _ChildrenAbove = new vlnParagraphs(this); + return _ChildrenAbove; + } + } + private vlnParagraphs _ChildrenBelow; + public vlnParagraphs ChildrenBelow + { + get + { + if (_ChildrenBelow == null) _ChildrenBelow = new vlnParagraphs(this); + return _ChildrenBelow; + } + } + private vlnParagraphs _ChildrenRight; + public vlnParagraphs ChildrenRight + { + get + { + if (_ChildrenRight == null) _ChildrenRight = new vlnParagraphs(this); + return _ChildrenRight; + } + } + private vlnParagraphs _ChildrenLeft; + public vlnParagraphs ChildrenLeft + { + get + { + if (_ChildrenLeft == null) _ChildrenLeft = new vlnParagraphs(this); + return _ChildrenLeft; + } + } + + public float? XOffsetCenter { get; set; } = null; + + public bool IsEnhancedBackgroundFormat(ItemInfo itminfo) => ((itminfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds); + + public void AdjustXOffsetForTab(ItemInfo itemInfo, int maxRNO, FormatInfo formatInfo, vlnTab myTab, float xMetaAdj) + { + if (itemInfo.IsSupInfoPart) + { + // The SupInfoTabOff was added to the base format during initial development to shift the tab over by 3/4 inch (54) to allow for enough space for Note/Caution tab + int sitabloc = itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoTabOff == null ? 0 : (int)itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoTabOff; + // B2023-069 allow for the adjustment of the Supplemental Information tab at the section level (SecOvrideSupInfoTabOff). + // this will also override the SupInoTabOff setting which is for the entire format + int secOvrSupInfoTab = itemInfo.MyDocStyle.SecOvrideSupInfoTabOff == null ? 0 : (int)itemInfo.MyDocStyle.SecOvrideSupInfoTabOff; + if (secOvrSupInfoTab != 0) sitabloc = secOvrSupInfoTab; + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + sitabloc; + if (myTab != null) + { + myTab.XOffset = XOffset - ((myTab == null) ? 0 : myTab.Width) - 12; + // B2017-253 - Limit the tab offset to 2 points inside the left margin + myTab.XOffset = Math.Max(myTab.XOffset, itemInfo.MyDocStyle.Layout.LeftMargin ?? 72) + 2; + float mytbwidth = myTab.Width; + myTab.Width = 2.5f * myTab.Width; + // C2018-022: adjust xoffset of text by 12 if the tab would overwrite the text and the format flag is on: + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SupInfoAdjustXOffForLongTab && ((myTab.XOffset + mytbwidth + 12) > XOffset)) + XOffset = 12F + myTab.XOffset + mytbwidth; + } + // B2017-102: need to set width here since using Xoffset because AdjustWidth is called before this adjustment. + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - (sitabloc / 2); + return; + } + // F2019-069: Hold Point designator for Barakah, use parent's tab for xoffset + if (itemInfo.IsStep && itemInfo.FormatStepData.ColUseParentTab && (myTab == null || myTab.Text == "")) + { + if (MyParent != null) + { + XOffset = (MyParent.MyTab == null || MyParent.MyTab.Text == null || MyParent.MyTab.Text.Trim() == "") ? MyParent.XOffset : MyParent.MyTab.XOffset; + return; + } + } + float tabWidth = (myTab == null) ? 0 : myTab.Width; + if (itemInfo.IsStepSection) + { + if (formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Just == "PSLeft") + { + int level = 0; + ItemInfo iilvl = itemInfo; + while (!iilvl.IsProcedure) + { + level++; + iilvl = iilvl.MyParent; + } + if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + { + XOffset = (myTab == null ? 0 : myTab.XOffset) + ((float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos); + } + else + { + level = level <= 2 ? 1 : level - 1; + if (level == 1) + { + // Use the section number position for the section title when the section number is blank + if (formatInfo.PlantFormat.FormatData.SectData.SectionHeader.UseNumPosWhenNumBlank && MyTab != null && MyTab.Text.Trim().Length == 0) + { + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + ((float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos); + } + else + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (level * (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos); + } + else if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + XOffset = (myTab == null ? 0 : myTab.XOffset) + ((float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos); + else + { + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[level].ColSByLevel; + XOffset += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[level].SecTitlePositionAdj; + XOffset -= xMetaAdj; + } + + if (itemInfo.MyDocStyle.SectTitleOffsetOverride != null) + { + XOffset += (float)itemInfo.MyDocStyle.SectTitleOffsetOverride; + } + + } + } + else if (formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Just == "PSCenter") + { + float hdrWidth = itemInfo.MyContent.Text.Length * 6; + float ctr = (((float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin)) / 2; + XOffsetCenter = (float)itemInfo.MyDocStyle.Layout.LeftMargin + ctr - (hdrWidth / 2); + } + return; + } + // B2021-091 added a null reference check - itemInfo was a section and didn't have FormatStepData so just return + if (itemInfo.FormatStepData == null) return; + + int? bxIndx = itemInfo.FormatStepData.StepLayoutData.STBoxindex; + float? colOvrd = itemInfo.FormatStepData.ColOverride; + if (itemInfo.IsBackgroundStep())//WolfCreekBackgroundFormat && IsHigh||IsNote||IsCaution or ImplicitOR + { + int adj = 2; + if (myTab != null) + { + //B2018-139 use XOffset when processing HLS, Caution, or Note background text and tab + if (itemInfo.IsHigh || (itemInfo.IsNote && (itemInfo.MyParent.IsHigh || itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote)) || (itemInfo.IsCaution && (itemInfo.MyParent.IsHigh || itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote))) + myTab.XOffset = XOffset; + else + { + // F2018-041 seq tabs off of TitleWithTextBelow were running into the step text + myTab.XOffset = XOffset + (itemInfo.FormatStepData.Font.CharsToTwips * adj); // F2018-041 move tab over 2 chars so it positions like paragraphs under TitleWithTextBelow + adj += myTab.Text.Length; // F2018-041 add the length of the tab to the adjustment of the XOffset + } + } + XOffset += (itemInfo.FormatStepData.Font.CharsToTwips * adj); // indent 2 characters for background steps + // B2018-146 Adjust the width to match the HLS Right Margin. + + Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; + return; + } + else if (itemInfo.FormatStepData.UseOldTemplate && itemInfo.IsInTemplate() && + (MyItemInfo.ActiveSection != null && (MyItemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd)) // C2018-003 fixed use of getting the active section + { + if (myTab != null) myTab.XOffset = XOffset; + XOffset += myTab.Width; + return; + } + else if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.Type == "TitleWithTextBelow") + { + if ((colOvrd ?? 0) != 0) + XOffset = (float)colOvrd; + else + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + // B2018-146 Adjust the width to match the HLS Right Margin. + if (itemInfo.IsPartOfBackgroundStep()) + Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; + return; + } + else if (itemInfo.IsParagraph && + (((itemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds) || + ((itemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations)) && + itemInfo.FormatStepData != null && PreviousIsTitleWithTextBelow(itemInfo)) + { + // This code was needed for fix for B2015-183 && + // IP2 backgrounds so that any 'paragraph's that were at the same + // level as the 'TitleWithTextBelow's would have same left margin (xoffset) as the 'TitleWithTextBelow'. + // an example of this can be found in IP2 Backgrounds, 2-E-0, Step Description Table, Step 22, PLANT-SPECIFIC INFORMATION. + // (NOTE that the IP2 exaxmple was no longer in the data when the work on B2015-183 was done) + if ((colOvrd ?? 0) != 0) + XOffset = (float)colOvrd; + else + { + //Adjuust Indent for Wolf Creek Background format flag + float indentBG1 = itemInfo.IsPartOfBackgroundStep() ? itemInfo.FormatStepData.Font.CharsToTwips * 2 : 0; + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + indentBG1; + // B2018-146 Adjust the width to match the HLS Right Margin. + if (itemInfo.IsPartOfBackgroundStep()) + Width = this.MyHighLevelParagraph.XOffset + this.MyHighLevelParagraph.Width - XOffset; + else + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin - indentBG1; + } + return; + } + else if (itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextBelow" && (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || (!itemInfo.IsCaution && !itemInfo.IsNote))) + { + float childindent = itemInfo.MyParent.FormatStepData.ChildIndent ?? 0; + if (myTab != null) + { + float delta = childindent + MyParent.XOffset - myTab.XOffset; + myTab.XOffset += delta; + XOffset += delta; + // B2018-036: set the width of (background/deviation/alarms/etc) steps that have a tab + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || !UseTemplateWidthOrXOff(itemInfo.MyParent)) + { + // B2018-146 Adjust the width to match the HLS Right Margin. + // F2023-112 added format flag for Vogtle Units 3 & 4 backgrounds. This allows use of override width on AND and List sub-step types + if (itemInfo.IsBackgroundStepOrChild() || itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.Vogtle3and4BackgroundFormat) + Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; + else + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin - delta; + } + } + else + { + //Adjust Indent for Wolf Creek Background format flag + float indentBG2 = itemInfo.IsPartOfBackgroundStep() ? itemInfo.FormatStepData.Font.CharsToTwips * 2 : 0; + XOffset = childindent + MyParent.XOffset + indentBG2; + // B2016-164: Added the following 'if' so that the width is not recalculated if in the alarm format & the parent has a template + // B2016-168: The fix for 164 broke deviation document printing. The if statement was fixed for both: + // B2019-057 Added a check to see if there is a width override for this step element (Robinson AOP Backgrounds - paragraphs) + float wdthovrd = (itemInfo.FormatStepData.WidthOverride == null) ? 0 : (float)ToInt(itemInfo.FormatStepData.WidthOverride, maxRNO); + if ((!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || !UseTemplateWidthOrXOff(itemInfo.MyParent)) && wdthovrd == 0) + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin - indentBG2; + } + return; + } + else if (itemInfo.FormatStepData != null && itemInfo.FormatStepData.Type == "TitleWithTextRight") + { + if ((colOvrd ?? 0) != 0) + XOffset = (float)colOvrd; + else + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin; + return; + } + else if (itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight") + { + XOffset = MyParent.MyParent.XOffset; + // if the step text has a tab, then we need to position the tab to the XOffset and then ajust the text XOffset + // by the length of the tab. - fix for IP2 backgrounds (ex. 2-ECA-3.3, step 6) + if (myTab != null) + { + myTab.XOffset = XOffset; + XOffset += (myTab.Text.Length * myTab.MyFont.CharsToTwips);//myTab.Width - myTab.XOffset; + } + return; + } + if (itemInfo.IsHigh) + { + if (formatInfo.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm || + ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_SameXOffSubsections) == E_DocStructStyle.DSS_SameXOffSubsections)) + { + // the HLS in the template prints the tab/step on the right edge of page. Don't + // do the other calculations to relocate it. + if (itemInfo.FormatStepData.UseOldTemplate && itemInfo.IsInTemplate()) + { + MyTab.XOffset = XOffset - MyTab.Width; + return; + } + // the following code handles the xoffsets of tabs/HLS in the non-alarm sections for + // the Calvert Alarm format. + if (itemInfo.MyDocStyle.UseColSByLevel) + { + if (myTab != null) + { + myTab.Rtf = myTab.Rtf.Replace(myTab.Text, myTab.Text.TrimStart(" ".ToCharArray())); + // B2022-129: don't indent HLS when flag is on (Barakah - single column step attachment with meta sect) + if (itemInfo.MyDocStyle.AdjSectTitleLoc) + { + myTab.XOffset = MyParent.MyTab.XOffset; + XOffset = MyParent.XOffset; + } + else + { + myTab.XOffset = MyParent.XOffset; + XOffset = myTab.XOffset + MyTab.Width; + } + } + else + XOffset = MyParent.XOffset; // unnumbered hls + return; + } + } + float x; + if ((colOvrd ?? 0) != 0) + x = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)colOvrd; + else + x = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS; + + float xoff = x - XOffset; + // ColSByLevel will specify the column in which the High Level Step starts with + // respect to the overall level calculation based on sections & meta-sections. + // Only a few of the single column formats use this: WCN1, CAL1, RGEBCK + if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TieTabToLevel + && !(itemInfo.MyDocStyle.SpecialStepsFoldout && itemInfo.MyDocStyle.UseColSByLevel)) + { + int indxLevel = itemInfo.PrintLevel + itemInfo.CurrentSectionLevel(); + // B2021-113: BNPP1new - subsection & HLS should be same level (xoffset of tab & text) + if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) indxLevel++; + float colsbylevel = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[indxLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].ColSByLevel; + float seclvlindent = colsbylevel - (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS; + float adjCols = (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS + seclvlindent; + float xtabcol = adjCols - ((myTab == null || myTab.Text == null) ? 0 : (myTab.Text.Length * 7.2f)); + if (indxLevel > 1 && myTab != null) myTab.XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + xtabcol; + else if (myTab != null) myTab.XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + colsbylevel; + if (myTab != null) + { + myTab.Rtf = myTab.Rtf.Replace(myTab.Text, myTab.Text.TrimStart(" ".ToCharArray())); + if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList != null && + formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList.Count > 0) + // B2021-113: BNPP1new - subsection & HLS should be same level (xoffset of tab & text) + if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) + XOffset += tabWidth; + else + XOffset = myTab.XOffset + GetLeftJustify(formatInfo, indxLevel); // 2.1.1 goes here xoffset = 136 + else + XOffset = myTab.XOffset + (myTab.Text.Length * (float)itemInfo.FormatStepData.Font.CPI) - colsbylevel; + } + } + else + { + XOffset += xoff; + // For Calvert, adjust from the left margin and current section's tab. This is used + // in BGEEOP (see EOP-0/Purpose ). However, it caused BGESTP's to print LossOfAC steps (unnumbered HLS) too + // far to the left. The ForceAlignNullTabWSectHead was introduced so that for that step type (LossOfAC) in STP/OI format, + // the SectData.SectionHeader.Pos was used rather than SectData.SectionNumber.Pos + if (myTab == null && !itemInfo.FormatStepData.ForceAlignNullTabWSectHead && itemInfo.FormatStepData.AlignNullTabWSectHead && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + else if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead) + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; + if (myTab != null) + { + if (itemInfo.MyDocStyle.AlignHLSTabWithSect || itemInfo.FormatStepData.AlignHLSTabWithSectOvride) + { + float orgXOffset = MyTab.XOffset; + myTab.XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; + XOffset = myTab.XOffset + myTab.Width; + // F2025-040 Adjust the Cont Act box position around HLS number + if (myTab.MyMacro != null) myTab.MyMacro.XOffset += (MyTab.XOffset - orgXOffset); + } + else + { + myTab.XOffset += xoff; + if (myTab.MyMacro != null) myTab.MyMacro.XOffset += xoff; + } + } + else + { + if (itemInfo.MyDocStyle.AlignHLSTabWithSect) + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; + } + } + } + else if (((colOvrd ?? 0) != 0) && (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.NullBox)) + { + float tabOffset = (myTab == null ? 0 : myTab.XOffset) - XOffset; + XOffset = (float)colOvrd; + if (myTab != null) myTab.XOffset = XOffset + tabOffset; + return; + } + else if (((colOvrd ?? 0) != 0) && (IsEnhancedBackgroundFormat(itemInfo) && (itemInfo.IsNote || itemInfo.IsCaution))) + { + float tabOffset = (myTab == null ? 0 : myTab.XOffset); + // Adjust the position of the Note/Caution text by the difference of the colOverride and the tab xoffset + XOffset += ((float)colOvrd - tabOffset); + if (myTab != null) myTab.XOffset = (float)colOvrd; // set the note/caution tab offset to the colOverride + return; + } + // put in for Point Beach (wep2) we don't want to do this if we are processing a boxed substep (cont. action substep) + else if (bxIndx != null && (itemInfo.IsCaution || itemInfo.IsNote || + !itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.ContActBoxOnSubSteps)) + { + Box bx = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; + if (bx == null) + { + if ((colOvrd ?? 0) != 0) + { + float tabOffset = (myTab == null ? 0 : myTab.XOffset) - XOffset; + + XOffset = (float)colOvrd; + if (myTab != null) myTab.XOffset = XOffset + tabOffset; + return; + } + else + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + tabWidth + XOffsetBox; + } + else + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)bx.TxtStart + _MyBoxLeftAdj + tabWidth + XOffsetBox; + if (myTab != null) myTab.XOffset = XOffset - tabWidth; + } + else if (itemInfo.IsRNOPart && itemInfo.MyParent != null && itemInfo.MyParent.IsRNOPart && itemInfo.FormatStepData.NumberWithLevel) + { + // xoffset is same as parent RNO (this is a BGE format flag). Instead of RNO's being siblings, + // they had a parent/child relationship. So want the child to have same xoffset as parent, i.e. + // the same xoffset. + XOffset = MyParent.XOffset; + myTab.XOffset = MyParent.MyTab.XOffset; + return; + } + else if (itemInfo.IsRNOPart && (colOvrd > 0 || !((ItemInfo)itemInfo.ActiveParent).IsHigh) && itemInfo.FormatStepData.OffsetTab) + { + if (colOvrd > 0) + { + XOffset = (int)colOvrd; + if (!((ItemInfo)itemInfo.MyParent).IsHigh) + { + ItemInfo hls = itemInfo.MyHLS; + XOffset -= (itemInfo.MyTab.Offset - hls.MyTab.Offset); + } + } + // if this format has the centerline & numberwithlevel (special tabbing for rno) then + // position rno xoffset of the tab to be close to centerline & text indented from there (only BGE) + if (itemInfo.MyDocStyle.CenterLineX != null && itemInfo.FormatStepData.NumberWithLevel) + { + // if the tab is 3 char or smaller, make the indent amount for the rno text 4 characters. + // if bigger, make it the additional tab size. + int len = myTab.Text.Trim().Length; + int adj = len <= 3 ? 4 : (len - 3) + 4; + float rnoOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)itemInfo.MyDocStyle.CenterLineX + 5; + float tPtPerChar = itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TabPtsPerChar ?? 6; + XOffset = rnoOffset + tPtPerChar * adj; + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - 11; // 11 is about size of char, so don't touch right line. + if (myTab != null) myTab.XOffset = rnoOffset; + } + // if the step is within the rno and we're numbering the high level rno, we've got to account for the + // indenting (increased x offset) for the top level rno's tab, if there is no top level rno: + else if (itemInfo.FormatStepData.NumberHighLevel && (itemInfo.MyHLS.RNOs == null || itemInfo.MyHLS.RNOs.Count <= 0)) + { + // add in the size that an RNO off HLS would take. + tabWidth += itemInfo.MyTab.RNOTabWidthAdjust; + XOffset += tabWidth; + if (myTab != null) myTab.XOffset += tabWidth; + } + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) + { + MyTab.XOffset = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset); + XOffset = MyTab.XOffset + tabWidth - MyTab.TabAlign; + } + } + else if (MyParent != null) + { + if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + XOffset = (float)itemInfo.MyDocStyle.Layout.LeftMargin + (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + else if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) + { + if (MyTab != null) + { + MyTab.XOffset = float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset); + XOffset = MyTab.XOffset + tabWidth - MyTab.TabAlign; + if (myTab.MyMacro != null && myTab.MyMacro.XOffset != 0) myTab.MyMacro.XOffset += tabWidth - myTab.TabAlign; + } + } + else if (itemInfo.IsSequential && itemInfo.MyParent.IsHigh && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.Align1StLevSubWHLS) == E_DocStructStyle.Align1StLevSubWHLS)) + { + XOffset = MyParent.XOffset; + if (myTab != null) myTab.XOffset = (MyParent.MyTab != null ? MyParent.MyTab.XOffset : XOffset); + } + else if (itemInfo.IsSequential && itemInfo.MyHLS.FormatStepData.AppendDotZero)// F2018-025 shift first level substep to column position of high level step Westinghouse wst1 step type 50 + { + if (itemInfo.MyParent.IsHigh) + { + XOffset = MyParent.XOffset; + if (myTab != null) myTab.XOffset = (MyParent.MyTab != null ? MyParent.MyTab.XOffset : XOffset); + } + else + { + myTab.XOffset = MyParent.XOffset; + XOffset = myTab.XOffset + MyTab.Width; + } + } + else if (myTab != null && itemInfo.IsSequential && formatInfo.PlantFormat.FormatData.SectData.UseMetaSections && formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList.Count > 0) + { + int indxLevels = itemInfo.PrintLevel + itemInfo.CurrentSectionLevel(); + // B2021-113: BNPP1new - subsection & HLS should be same level (xoffset of tab & text) + if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) indxLevels++; + float tableftadj = GetLeftJustify(formatInfo, indxLevels); + if (tableftadj != 0) + { + // the order of this is important. First adjust the tab's xoffset for the width of + // the tab. The offset of text needs to be adjusted by the 'leftjustify' format variable + // if it existed for this level. + myTab.XOffset += tabWidth; + if (tableftadj != 0 && myTab.Width < tableftadj) + tabWidth = myTab.Width = tableftadj; + XOffset += tabWidth; + myTab.Rtf = myTab.Rtf.Replace(myTab.Text, myTab.Text.TrimStart(" ".ToCharArray())); + Width = MyParent.Width - myTab.Width; + } + else // if no left justify, right align the tab + { + XOffset += tabWidth - (myTab == null ? 0 : myTab.TabAlign); + if (myTab != null) + { + myTab.XOffset += tabWidth - myTab.TabAlign; + if (myTab.MyMacro != null && myTab.MyMacro.XOffset != 0) myTab.MyMacro.XOffset += tabWidth - myTab.TabAlign; + } + } + } + else // if no left justify, right align the tab + { + // The following fixes F2016-033: Print the Verification Point at left margin. + if (itemInfo.ActiveFormat.Name.ToUpper().StartsWith("VCB") && (itemInfo.FormatStepData.ColOverride ?? 0) > 0) + { + XOffset = (float)itemInfo.FormatStepData.ColOverride; + } + else + { + XOffset += tabWidth - (myTab == null ? 0 : myTab.TabAlign); + if (myTab != null) + { + myTab.XOffset += tabWidth - myTab.TabAlign; + if (myTab.MyMacro != null && myTab.MyMacro.XOffset != 0) myTab.MyMacro.XOffset += tabWidth - myTab.TabAlign; + } + // B2018-146 Adjust the width to match the HLS Right Margin. + if (itemInfo.IsBackgroundStepOrChild()) + Width = this.MyHighLevelParagraph.Width + this.MyHighLevelParagraph.XOffset - this.XOffset; + } + } + } + // if format had a tab adjustment for step type, use it. MyTab.Offset is only set for FNP formats + // to get the correct xoffset for their tabs/text. The issue is that they use very large tabs + // because levels of substeps include the parent tab. This code will only be run for FNP. + if (itemInfo.MyTab != null && itemInfo.MyTab.Offset != 0) + { + float xOffTabNew = (MyParent.MyTab != null ? MyParent.MyTab.XOffset : MyParent.XOffset) + itemInfo.MyTab.Offset; + xOffTabNew += MyParent.MyTab == null ? 0 : MyParent.MyTab.TabOffset; + float xIncrement = xOffTabNew - MyTab.XOffset; + myTab.XOffset += xIncrement; + XOffset += xIncrement; + Width -= xIncrement; + } + } + private bool PreviousIsTitleWithTextBelow(ItemInfo itemInfo) + { + while (itemInfo.MyPrevious != null) + { + if (itemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow") return true; + itemInfo = itemInfo.MyPrevious; + } + return false; + } + + private static float GetLeftJustify(FormatInfo formatInfo, int indxLevels) + { + LeftJustifyList jstlst = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.LeftJustifyList; + float tableftadj = 0; + foreach (LeftJustify lj in jstlst) + { + if (lj.Index == indxLevels) + { + tableftadj = lj.Size ?? 0; + break; + } + } + return tableftadj; + } + + public float CheckOffWidth { get; set; } = 0; + public float AdjustHeader { get; set; } = 0; + public void AdjustWidth(ItemInfo itemInfo, int maxRNO, FormatInfo formatInfo, vlnTab myTab) + { + int? bxIndx = itemInfo.IsStep ? itemInfo.FormatStepData.StepLayoutData.STBoxindex : null; + float xwid; + float? widOvrd; + if (itemInfo.IsStep && itemInfo.MyHLS != null && UseTemplateWidthOrXOff(itemInfo) && (xwid = GetWidthOrStartFromTemplate(itemInfo, formatInfo, true)) > 0) + widOvrd = xwid; + else + widOvrd = itemInfo.FormatStepData == null ? null : itemInfo.FormatStepData.WidthOverride == null ? null : + (float?)ToInt(itemInfo.FormatStepData.WidthOverride, maxRNO); + // Calvert subheaders in valve lists - the text gets centered, so the width is the width + // of the page (also, don't do this for alarms, thus the !SpecialCaseCalvert Alarms, since + // alarms use Caution1 as the annunciator): + if (itemInfo.IsStep && itemInfo.MyHLS != null && !itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && + itemInfo.MyHLS.FormatStepData.UseOldTemplate && itemInfo.MyDocStyle.ComponentList && itemInfo.IsCaution1) + { + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - (float)itemInfo.MyDocStyle.Layout.LeftMargin; + return; + } + + // Calvert Alarms had a case where the Title With Text Below (type 42) did not match + // any of the template items, but needed the width from the template. The previous step (of + // same type) was in the template. Check for this case. The issue can be found in + // Unit 1 Alarms/1c06/Alarm E-48/'General Information' section. + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm && widOvrd == 0) + { + if (itemInfo.MyPrevious != null && itemInfo.MyPrevious.TemplateIndex > 1) widOvrd = GetWidthOrStartFromTemplate(itemInfo.MyPrevious, itemInfo.MyPrevious.ActiveFormat, true); + } + + // for IP2 backgrounds, set widths appropriately for template items: + if (itemInfo.IsStep && (itemInfo.ActiveSection != null && (itemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd)) // C2018-003 fixed use of getting the active section + { + if (itemInfo.FormatStepData.Type.ToUpper() == "TITLEWITHTEXTBELOW") + { + Width = MyParent.Width; + return; + } + if (itemInfo.MyPrevious != null && itemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow") + { + Width = MyParent.MyParent.Width; + return; + } + if (widOvrd == 0 && itemInfo.MyParent.IsStep && + (itemInfo.MyParent.FormatStepData.Type.ToUpper() == "TITLEWITHTEXTBELOW" || + (((itemInfo.ActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) && + itemInfo.FormatStepData != null && MyParent.MyItemInfo.MyPrevious != null && MyParent.MyItemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow"))) + { + Width = MyParent.MyParent.Width + (MyParent.MyParent.MyTab != null ? MyParent.MyParent.MyTab.Width : 0); + Width -= (MyTab != null ? MyTab.Width : 0); + return; + } + } + + //widOvrd = itemInfo.FormatStepData == null ? null : itemInfo.FormatStepData.WidthOverride; + // Don't adjust the RNO width if in single column mode: + if (itemInfo.IsRNOPart && itemInfo.MyParent.IsHigh && itemInfo.ActiveSection != null && itemInfo.ActiveSection.ColumnMode != 0 && itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAlt != null) // C2018-003 fixed use of getting the active section + { + string[] splitRNOWidthAlt = itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAlt.Split(','); + float ovrd = (itemInfo.RNOLevel < splitRNOWidthAlt.Length) ? float.Parse(splitRNOWidthAlt[itemInfo.RNOLevel]) : 0; + if (ovrd > 0) + widOvrd = ovrd; // + 6; // Change bars on RNO column (signoff line) would not line up with 16-bit without this - NSP Alarms + } + if ((widOvrd ?? 0) != 0) + { + //F2023-112 Vogtle Units 3 & 4 Backgrounds. Don't use override width of paragraph when it's off of TitleWithTextRight + // We need to allow the code to calculate the width of that paragraph for this case (later in this function) + if (!(itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.Vogtle3and4BackgroundFormat && itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight")) + { + Width = (float)widOvrd; + // if there's a box, we may need to do an adjustment on the width, if the tab data was changed + // so don't return. + if (bxIndx == null) return; + } + } + float tabWidth = (myTab == null) ? 0 : myTab.Width; + if (itemInfo.IsHigh) + { + float CheckOffAdj = 0; + bool ChkOff = itemInfo.MyDocStyle.UseCheckOffs; + // C2019-040 use format flag to see if any of the steps in this section have a checkoff set - previously we check if the format file name starts with VCB (VCB no longer a customer) + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert || itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckoffsWithoutHeader) + { + SectionInfo si = itemInfo.ActiveSection.GetSectionInfo(); + ChkOff = si.HasInitials; // this determines if any steps within the section have checkoffs. + } + bool FmtHasAdj = false; + if (ChkOff) + { + if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffAdjustment != null) + { + FmtHasAdj = true; + CheckOffAdj = -(float)formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffAdjustment; + } + // C2019-040 use format flag to not readjust the CheckOffAdj value - previously we check if the format file name starts with VCB (VCB no longer a customer) + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckoffsWithoutHeader) // Don't do the following if in a vcb format (part of fix F2016-039) + { + if (!HasCheckOffHeading(itemInfo, formatInfo) && CheckOffAdj < 0) + CheckOffAdj += (float)(9 * 7.2); // 9 is the size of the SIGNOFF adjustment + else if (!FmtHasAdj && HasCheckOffHeading(itemInfo, formatInfo)) + // For Robinson, tried using font's CharsToTwips but it made it too narrow, so used hardcoded 6: + CheckOffAdj = -((float)9 * 6); + } + } + float adjwidth = CheckOffAdj; + CheckOffWidth = -CheckOffAdj; + adjwidth = AdjustMetaWidth(itemInfo, formatInfo, adjwidth, FmtHasAdj); + Width = ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, maxRNO); + Width += _WidthAdjust; + Width += adjwidth; + + // if AlignHLSTabWithSect is set, we moved the starting x location of the HLS, and following steps + // to be under section header. Adjust the width accordingly, or the text may go out of the margin. + if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert) + Width = Width + (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos - (float)formatInfo.PlantFormat.FormatData.SectData.SectionNumber.Pos; + else if (myTab == null && itemInfo.FormatStepData.AlignNullTabWSectHead) + Width += (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; + else if (itemInfo.MyDocStyle.AlignHLSTabWithSect) + Width -= (float)formatInfo.PlantFormat.FormatData.SectData.SectionHeader.Pos; + + // B2022-002: Section text is printing into the INITIAL column (BNPP1new). If this flag is set adjust the width of the + // section text to that of the first hls (child) text and its tab. This is to prevent the very long section titles (that should have + // been steps) from extending into the INITIAL (checkoff) column. + if (formatInfo.PlantFormat.FormatData.SectData.AdjWidthForCheckOff && MyParent != null && MyParent.MyItemInfo.IsSection && ChkOff && CheckOffWidth != 0 && itemInfo.ItemID == itemInfo.FirstSibling.ItemID) + { + SectionInfo si = MyParent.MyItemInfo.GetSectionInfo(); + if (si.HasInitials) MyParent.Width = Width + ((myTab == null) ? 0 : myTab.Width); + } + } + else if (bxIndx != null) + { + Box bx = formatInfo.PlantFormat.FormatData.BoxList[(int)bxIndx]; + if (bx == null) + { + if (widOvrd != 0) + Width = (float)widOvrd - tabWidth; + else + Width = (float)formatInfo.MyStepSectionLayoutData.WidT - tabWidth; + } + else + { + float oldWidth = _WidthAdjustBox + (float)bx.TxtWidth - tabWidth; // add 1 to get it to wrap like 16Bit + // B2018-096 AEP 082.002CD Note Box overlapping Step Box + if (MyParent.MyItemInfo.FormatStepData != null && MyParent.MyItemInfo.FormatStepData.BoxIt) // B2018-100 not for parents that are sections // B2018-098 only adjust width if parent has Boxit turned on + { + Width = Math.Min(MyParent.Width + MyParent.XOffset - XOffset, oldWidth); + AdjustHeader = (Width - oldWidth) / 2; + } + else + Width = oldWidth; + } + } + else if ((itemInfo.IsCaution || itemInfo.IsNote) && !itemInfo.FormatStepData.UseOldTemplate) + { + float mycolT = (float)formatInfo.MyStepSectionLayoutData.ColT; + if (formatInfo.MyStepSectionLayoutData.Dev_Format) + Width = (float)formatInfo.MyStepSectionLayoutData.WidT + 1; + else if (itemInfo.IsInRNO) + { + // C2014-009: Condition/Response adjust xoffset & width + // B2020-117 add a check that there is only one Caution/Note/Warning + if (MyItemInfo.FormatStepData.CenterOneLineAdjust && MyItemInfo.FirstSibling == MyItemInfo.LastSibling) + { + int rnoOff = ToInt(formatInfo.MyStepSectionLayoutData.ColRTable, maxRNO); + if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + XOffset = MyTopRNO.MyTab.XOffset + 7.2f; + Width = MyParent.Width + (MyParent.XOffset - XOffset); + } + else + { + XOffset = rnoOff + MyHighLevelParagraph.XOffset; + Width = MyParent.Width; + } + } + // B2020-117 There are muliple Cautions, Notes, or Warnings in the Calvert Alarm Contition/Response + // Need to adjust the starting positon of the bulleted tab, text and width + else if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + XOffset = MyTopRNO.MyTab.XOffset + 7.2f; + this.MyTab.XOffset = XOffset; + XOffset += this.MyTab.Width; + Width = MyParent.Width + (MyParent.XOffset - XOffset); + } + else + Width = (MyParent.XOffset + MyParent.Width) - (XOffset + mycolT); + } + else + { + // B2016-269: if caution/note & not boxed, with tab adjust width based on xoffset of tab + // so text doesn't print out of right border. + // B2017-027: Added a check for column mode - we only want to do this if in single column mode + if (!MyItemInfo.MyParent.IsHigh && MyTab != null && MyTab.YOffset == YOffset && MyItemInfo.ActiveSection != null && MyItemInfo.ActiveSection.ColumnMode == 0) // C2018-003 fixed use of getting the active section + { + // B2017-xxx if this is a caution/note off of a substep in the supinfo column, need to look up for its supinfo part, not + // its HLS. + if (MyItemInfo.IsInSupInfo) + { + vlnParagraph supinfopart = this; + while (supinfopart.MyParent != null && !supinfopart.MyItemInfo.IsSupInfoPart) supinfopart = supinfopart.MyParent; + XOffset = supinfopart.XOffset; + MyTab.XOffset = XOffset - MyTab.Width - 10; + Width = supinfopart.Width; + } + else + Width = MyHighLevelParagraph.Width - MyTab.Width - (MyTab.XOffset - MyHighLevelParagraph.XOffset) - 6; + } + else + Width = (float)formatInfo.MyStepSectionLayoutData.WidT - 6 - mycolT; + } + XOffset += mycolT; // adjust caution/note text position + if (PartsLeft != null && PartsLeft.Count > 0)// adjust tab position + { + if (myTab != null && (itemInfo.IsNote || itemInfo.IsCaution)) + Width -= myTab.Width; + foreach (vlnPrintObject vpo in PartsLeft) + vpo.XOffset += mycolT; + } + } + else if (itemInfo.IsSection) + { + // B2023-074 The itemInfo we are processing is a section (number and title). Change maxRNO to zero to getting the width. + // The Width is used when printing the section number and title (when the check box on the properties page is checked) + // and is assumemed the section is a single column section (maxRNO = 0) and uses the format variable WidSTablePrint + // which holds the widths for then the section has one column, two column, or three column. + // For printing section numbers and titles like this, we always want to accomodate for lone section title text. + // So the initial width should always be set to the one column width value so that it can spane across the page. + Width = ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, 0); + float adjwidths = 0; + adjwidths = AdjustMetaWidth(itemInfo, formatInfo, adjwidths, false); + Width += (adjwidths + _WidthAdjust); + } + else if (MyParent == null) + { + // 72 points / inch - 7 inches (about width of page) + Width = 72 * 7; + } + else if (itemInfo.IsRNOPart && itemInfo.ActiveSection != null && itemInfo.ActiveSection.ColumnMode != 0 && itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAltAll != null) // C2018-003 fixed use of getting the active section + { + // This code was added for AEP. Other code that adjusted RNO widths was only adjusting the RNO widths + // off of the HLS. AEP needed adjusting for all RNOs. + float ovrd = (float)itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAltAll; + if (ovrd > 0) + Width = ovrd - tabWidth; + if (XOffset + Width > (float)itemInfo.MyDocStyle.Layout.PageWidth) + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset - 5; + } + else if (itemInfo.IsRNOPart && !((ItemInfo)itemInfo.ActiveParent).IsHigh) + { + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAdj != null && !((ItemInfo)itemInfo.ActiveParent).IsInRNO) + Width = MyParent.Width + float.Parse(itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthAdj); + else + Width = MyParent.Width; + } + else if (itemInfo.IsRtfRaw) // this needs to be before the check for 'IsTablePart' - the rtfraw may be a table part, but the size is defined by raw rtf + { + System.Drawing.Size sz = RtfRawItem.GetRtfRawSize(MyItemInfo.MyContent.Text); + Height = sz.Height; + Width = sz.Width; + Rtf = MyItemInfo.MyContent.Text; + } + else if (itemInfo.IsTablePart) + { + Width = 72 * 7; // TODO: Need to determine the Width of the Table based upon the contents + } + else if (itemInfo.MyParent.FormatStepData != null && itemInfo.MyParent.FormatStepData.Type == "TitleWithTextRight") // B2019-141: Background steps width too small + { + Width = (float)itemInfo.MyDocStyle.Layout.PageWidth - XOffset; + } + else if (itemInfo.MyParent.IsCaution || itemInfo.MyParent.IsNote) + { + if (itemInfo.ActiveFormat.MyStepSectionLayoutData.DevNoteOrCautionTabOffset != null) + Width = MyParent.MyParent.Width - tabWidth + (myTab == null ? 0 : myTab.TabAlign); + else + Width = MyParent.Width - tabWidth + (myTab == null ? 0 : myTab.TabAlign); + Width -= 72 * (itemInfo.FormatStepData.CautionOrNoteSubstepIndent == null ? 0 : (float)itemInfo.FormatStepData.CautionOrNoteSubstepIndent / (float)itemInfo.FormatStepData.Font.CPI); + } + else + { + float adjwidth = 0; + if (itemInfo.IsRNOPart && itemInfo.ActiveFormat.MyStepSectionLayoutData.RNOWidthSameAsHighParent && itemInfo.MyParent.IsHigh) + Width = adjwidth + MyParent.Width; + else if (itemInfo.MyTab != null && itemInfo.MyTab.Position != 0) + Width = adjwidth + MyParent.Width; + else if (MyParent.WidthNoLimit != 0) + Width = adjwidth + MyParent.WidthNoLimit - tabWidth + (myTab == null ? 0 : myTab.TabAlign); + else if ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) + Width = adjwidth + MyParent.Width - (MyTab != null ? MyTab.Width : 0); + else + Width = adjwidth + MyParent.Width - tabWidth + (myTab == null ? 0 : myTab.TabAlign); + } + if (itemInfo.IsSequential && itemInfo.MyParent.IsHigh && ((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.Align1StLevSubWHLS) == E_DocStructStyle.Align1StLevSubWHLS)) + Width += 10; + } + + private float AdjustMetaWidth(ItemInfo itemInfo, FormatInfo formatInfo, float adjwidth, bool coadj) + { + SectData sd = formatInfo.PlantFormat.FormatData.SectData; + if (((itemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_SameXOffSubsections) == E_DocStructStyle.DSS_SameXOffSubsections)) + { + // don't adjust the width if there already was an adjustment for checkoffs - for VCB only (F2016-039) - VCB no longer a customer + // C2019-040 use format flag to adjust the width (was already don for checkoffs) - previously we check if the format file name starts with VCB (VCB no longer a customer) + if (!(itemInfo.ActiveFormat.PlantFormat.FormatData.ProcData.CheckOffData.CheckoffsWithoutHeader && coadj)) + adjwidth = MyTab != null ? -MyTab.Width : 0; + } + else if (sd.UseMetaSections) + { + if (sd.StepSectionData.StepSectionLayoutData.TieTabToLevel) + { + if (ShowSectionTitles + && !itemInfo.MyDocStyle.CancelSectTitle + && !(itemInfo.MyDocStyle.SpecialStepsFoldout && itemInfo.MyDocStyle.UseColSByLevel)) + { + int indxLevel = itemInfo.PrintLevel + itemInfo.CurrentSectionLevel(); + //F2022-023 Used the SubSectAndHighSameLevel (BNPP1New format) flag to get the proper level if we have sub-sections so that we get the proper WidSAdjByLevel value + if (formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.SubSectAndHighSameLevel && !MyItemInfo.MyActiveSection.MyParent.IsProcedure) indxLevel++; + adjwidth += formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[indxLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].WidSAdjByLevel ?? 0; ; + float colsbylevel = (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[indxLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].ColSByLevel; + float seclvlindent = colsbylevel - (float)formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.ColS; + adjwidth -= seclvlindent; + if (itemInfo.IsStep) adjwidth -= AdjustForSectionLevelTab(); + if (itemInfo.IsSection && itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining) + adjwidth -= (float)((itemInfo.MyTab.CleanText.Trim().Length * 72) / itemInfo.ActiveFormat.PlantFormat.FormatData.SectData.SectionHeader.Font.CPI); + } + } + else + { + if (formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex > 0) + adjwidth += (float)formatInfo.PlantFormat.FormatData.SectData.MetaSectionList[itemInfo.PrintLevel % formatInfo.PlantFormat.FormatData.SectData.MetaSectionList.MaxIndex].ColSByLevel; + } + } + return adjwidth; + } + + // for Component Table, don't increment yoff unless last item in table that HAS data associated + // with it (there may be empty cells at end). + public bool UseTemplateKeepOnCurLine(ItemInfo itemInfo) + { + if (!itemInfo.IsStep || !itemInfo.MyDocStyle.ComponentList) return false; + if (!itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert + && itemInfo.MyHLS.FormatStepData.UseOldTemplate) return true; + return false; + } + private bool UseTemplateWidthOrXOff(ItemInfo itemInfo) + { + if (!itemInfo.IsStep) return false; + if (itemInfo.MyHLS == null) return false; + if (itemInfo.MyHLS.FormatStepData.UseSmartTemplate || (itemInfo.MyDocStyle.ComponentList && itemInfo.MyHLS.FormatStepData.UseOldTemplate)) + { + ItemInfo useForTemplate = itemInfo.IsHigh ? itemInfo : itemInfo.MyParent; + int topIndx = useForTemplate.GetSmartTemplateTopLevelIndx(); + int tpIndx; + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + if (itemInfo.IsCaution1) return false; + else tpIndx = useForTemplate.GetSmartTemplateIndex(topIndx, itemInfo.MyContent.Text); + } + else + tpIndx = useForTemplate.GetSmartTemplateIndex(topIndx, (int)useForTemplate.MyContent.Type); + if (tpIndx > -1) return true; + } + return false; + } + private float GetWidthOrStartFromTemplate(ItemInfo itemInfo, FormatInfo formatInfo, bool bGetWidth) + { + int topIndx = itemInfo.GetSmartTemplateTopLevelIndx(); + int tmplIndx; + if (itemInfo.MyDocStyle.ComponentList && !itemInfo.IsHigh) + { + // The following was added so that the Calvert Alarms sequentials under the CONDITION/RESPONSE would be + // printed as 2 column (data within the template definition set the columns to 2) + if (itemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) + { + if (itemInfo.IsSequential && itemInfo.MyParent.TemplateIndex > 0) + { + if (bGetWidth && itemInfo.MyParent.ColumnMode == 1) // 2 columns + return (ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, itemInfo.ColumnMode) - MyTab.Width); + } + tmplIndx = itemInfo.TemplateIndex; + if (tmplIndx == -1) return 0; + } + else + { + // The ComponentTable format (FNP component table as one example), uses a template + // where the items in the template below the HLS are all paragraphs (the intermediate steps + // are TitleWithTextRight). Find the ordinal of in this list to get the index. Use the ordinal + // as an offset from the HLS's index into the template. + tmplIndx = itemInfo.MyParent.Ordinal + topIndx; + if (tmplIndx < 0 || tmplIndx > formatInfo.PlantFormat.FormatData.Templates.Count - 1) return 0; + } + } + else + { + tmplIndx = itemInfo.GetSmartTemplateIndex(topIndx, (int)itemInfo.MyContent.Type); + if (tmplIndx == -1) return 0; + } + // Calvert Alarms' template defines number of columns & their width. + if (bGetWidth && formatInfo.PlantFormat.FormatData.Templates[tmplIndx].width == 0) + { + int nocol = formatInfo.PlantFormat.FormatData.Templates[tmplIndx].nocolm == 0 ? 0 : formatInfo.PlantFormat.FormatData.Templates[tmplIndx].nocolm - 1; + return ToInt(formatInfo.MyStepSectionLayoutData.WidSTablePrint, nocol); + } + int ncol = bGetWidth ? formatInfo.PlantFormat.FormatData.Templates[tmplIndx].width : formatInfo.PlantFormat.FormatData.Templates[tmplIndx].start; + // now convert to the units for this format. The template width data is in number of columns. + return (ncol * itemInfo.FormatStepData.Font.CharsToTwips) + (bGetWidth ? 1 : 0); // + 1 is slight adjustment so column doesn't wrap + } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0059:Unnecessary assignment of a value", Justification = "myTab Kept For Debugging")] + private float AdjustForSectionLevelTab() + { + string sectTab = MyItemInfo.ActiveSection.MyTab.CleanText.TrimEnd(); + if (sectTab.EndsWith(".0")) return 0; + string myTab = MyItemInfo.MyTab.CleanText; + // -1 below code, +1 for '.' and -2 for standard wid of tab + // standard wid of this tab is 2 (ex: '1.') + // so adjust width if longer than normal + return (float)(sectTab.Length - 1) * 72 / (float)MyItemInfo.FormatStepData.Font.CPI; + } + private bool HasCheckOffHeading(ItemInfo itemInfo, FormatInfo formatInfo) + { + if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderList.MaxIndex != 0) + { + // does this section have a check off heading? + SectionConfig sc = (itemInfo.ActiveSection != null) ? itemInfo.MyActiveSection.MyConfig as SectionConfig : null; // C2018-003 fixed use of getting the active section + if (sc != null && sc.Section_CheckoffHeaderSelection > 0) return true; + } + if (formatInfo.PlantFormat.FormatData.ProcData.CheckOffData.CheckOffHeaderInPagelist) return true; + return false; + } + } + + /// + /// First order by stepLevel, then within a stepLevel, order by descending yLocation on page. + /// Want to find maximum y value that fits on page, i.e. put the most on page that can + /// fit which is defined by the largest yLocation + /// + public class StepLevelList : SortedDictionary> + { + public StepLevelList() + : base() + { + } + public void Add(int stepLevel, float yLocation, vlnParagraph para) + { + if (stepLevel == 0) return; + if (!this.ContainsKey(stepLevel)) + this.Add(stepLevel, new SortedDictionary()); + // using a negative for yLocation so that its in descending order: + // B2020-112: Make various adjustments to location if there are format flags used + // B2020-116: Only make the 112 change for Calvert + // B2020-151: check for SpecialCaseCalvertPagination flag instead of SpecialCase Calvert flag so only EOPs/AOPs are affected + float adjust = 0; + if (para.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination) + adjust = para.YVeryTop - para.YTop; + if (!this[stepLevel].ContainsKey(-(yLocation + adjust))) + this[stepLevel].Add(-(yLocation + adjust), para); + } + } + public class ParagraphLocations : List + { + public ParagraphLocations() + : base() + { + } + public void Add(vlnParagraph myParagraph, float yTopMost) + { + ParagraphLocation foundOverlap = FindOverlap(myParagraph); + if (foundOverlap == null) + { + this.Add(new ParagraphLocation(yTopMost, myParagraph)); + return; + } + ParagraphLocation doubleOverlap = FindOverlap(foundOverlap); + while (doubleOverlap != null) + { + doubleOverlap.Merge(foundOverlap); + this.Remove(foundOverlap); + foundOverlap = doubleOverlap; + doubleOverlap = FindOverlap(foundOverlap); + } + } + + private ParagraphLocation FindOverlap(vlnParagraph myParagraph) + { + foreach (ParagraphLocation paraLoc in this) + if (paraLoc.Overlap(myParagraph)) + return paraLoc; + return null; + } + private ParagraphLocation FindOverlap(ParagraphLocation myParaLoc) + { + foreach (ParagraphLocation paraLoc in this) + if (paraLoc != myParaLoc && paraLoc.Overlap(myParaLoc)) + return paraLoc; + return null; + } + internal StepLevelList BuildStepLevelList(bool KeepStepsOnPage) + { + StepLevelList myList = new StepLevelList(); + foreach (ParagraphLocation paraLoc in this) + { + int level = paraLoc.StepLevel; + if (KeepStepsOnPage) + { + // B2020-116: change from checking for type 20001 to looking for a non-high sequential since some + // step types were sequential but not 20001 + if (!paraLoc.MyParagraph.MyItemInfo.IsHigh) + { + bool AlarmPagination = paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.AlarmPagination; + if (paraLoc.MyParagraph.MyItemInfo.IsSequential) + { + if (DontBreakHere(paraLoc)) + level = 0; + else + level = 1; // AlarmPagination?3:1; // B2023-091: backout B2023-088 make it easier to break on a sequential for alarms + } + else if (AlarmPagination && paraLoc.MyParagraph.MyItemInfo.IsSubStep) + { + // make it harder to break on first caution or note & within a list if doing Alarm Pagination: + vlnParagraph myPara = paraLoc.MyParagraph; + if ((myPara.MyItemInfo.IsCaution || myPara.MyItemInfo.IsNote) && myPara.MyItemInfo.MyPrevious == null) level = 1; + else if (myPara.MyItemInfo.MyPrevious != null || myPara.MyItemInfo.NextItem != null) level = 2; + } + } + } + // For B2015-014, some migrated data for background documents had the TitleWithTextBelow with associated paragraphs + // as siblings rather than children. Pagination was sometimes putting the TitleWithTextBelow on one page and the + // paragraphs on next. The following code checks thse types, if in enhanced documents but not the Short Form Deviations. + if (paraLoc.MyParagraph.MyItemInfo.ActiveFormat != null + && ((paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedBackgrounds) == E_PurchaseOptions.EnhancedBackgrounds) + || (((paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PurchaseOptions.Value & E_PurchaseOptions.EnhancedDeviations) == E_PurchaseOptions.EnhancedDeviations) + && paraLoc.MyParagraph.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.EnhancedShortFormDev)) + { + if (!paraLoc.MyParagraph.MyItemInfo.IsTitle && paraLoc.MyParagraph.MyItemInfo.MyPrevious != null && paraLoc.MyParagraph.MyItemInfo.MyPrevious.FormatStepData.Type == "TitleWithTextBelow") level = 0; + } + paraLoc.MyParagraph.levelForPagination = level; + myList.Add(level, paraLoc.YTop, paraLoc.MyParagraph); + } + return myList; + } + private bool DontBreakHere(ParagraphLocation paraLoc) + { + if (paraLoc.MyParagraph.MyItemInfo.MyPrevious == null) // First substep + return true; + vlnParagraph myPara = paraLoc.MyParagraph; + while (!myPara.MyItemInfo.IsHigh) + { + if (myPara.MyItemInfo.IsCaution) return true; + if (myPara.MyItemInfo.IsNote) return true; + myPara = myPara.MyParent; + } + return false; + } + } + public class ParagraphLocation + { + public override string ToString() => string.Format("{0} {1} - {2} - '{3}'", this.MyParagraph.MyItemInfo.ItemID, this.StepLevel, this.YTop, this.MyParagraph.MyItemInfo.ShortPath); + + public float YTop { get; set; } + public float YBottom { get; set; } + public int StepLevel { get; set; } + public vlnParagraph MyParagraph { get; set; } + public ParagraphLocation(float yTopMost, vlnParagraph myParagraph) + { + MyParagraph = myParagraph; + YTop = myParagraph.YVeryTop - yTopMost; + YBottom = myParagraph.YBottom - yTopMost; + StepLevel = myParagraph.MyItemInfo.StepLevel; + // B2020-115 Set a very large figure's Step Level so that pagination will happen prior to the figure. + if (myParagraph.MyItemInfo.IsFigure && myParagraph.MyParent.Height + myParagraph.Height > vlnParagraph.hMax) + { + StepLevel = 1;// Set figure as a guaranteed break location + } + } + public bool Overlap(vlnParagraph otherParagraph) + { + if (Between(otherParagraph.YTop, YTop, YBottom)) return true; + if (Between(otherParagraph.YBottom, YTop, YBottom)) return true; + if (Between(YTop, otherParagraph.YVeryTop, otherParagraph.YBottom)) return true; + if (Between(YBottom, otherParagraph.YVeryTop, otherParagraph.YBottom)) return true; + return false; + } + public static bool Between(float x, float lower, float higher) => x > lower && x < higher; + public bool Overlap(ParagraphLocation otherParagraphLocation) + { + if (Between(otherParagraphLocation.YTop, YTop, YBottom)) return true; // The top is within the other + if (Between(otherParagraphLocation.YBottom, YTop, YBottom)) return true; // The bottom is within the other + if (Between(YTop, otherParagraphLocation.YTop, otherParagraphLocation.YBottom)) return true; // the other top is within this one + if (Between(YBottom, otherParagraphLocation.YTop, otherParagraphLocation.YBottom)) return true;// I believe this is unnecessary + return false; + } + public void Merge(vlnParagraph otherParagraph) + { + if (StepLevel < otherParagraph.MyItemInfo.StepLevel) MyParagraph = otherParagraph; + YTop = Math.Min(YTop, otherParagraph.YVeryTop); + YBottom = Math.Max(YBottom, otherParagraph.YBottom); + StepLevel = Math.Max(StepLevel, otherParagraph.MyItemInfo.StepLevel); + } + public void Merge(ParagraphLocation otherParagraphLocation) + { + if (StepLevel < otherParagraphLocation.StepLevel) MyParagraph = otherParagraphLocation.MyParagraph; + YTop = Math.Min(YTop, otherParagraphLocation.YTop); + YBottom = Math.Max(YBottom, otherParagraphLocation.YBottom); + StepLevel = Math.Max(StepLevel, otherParagraphLocation.StepLevel); + } + } } diff --git a/PROMS/Volian.Print.Library/vlnPrintObject.cs b/PROMS/Volian.Print.Library/vlnPrintObject.cs index b09edea2..84bc658b 100644 --- a/PROMS/Volian.Print.Library/vlnPrintObject.cs +++ b/PROMS/Volian.Print.Library/vlnPrintObject.cs @@ -1,14 +1,10 @@ using System; using System.Collections.Generic; using System.Text; -using System.Drawing; using iTextSharp.text.pdf; using iTextSharp.text; using Itenso.Rtf; -using Itenso.Rtf.Parser; -using Itenso.Rtf.Interpreter; using Itenso.Rtf.Support; -using Volian.Controls.Library; using VEPROMS.CSLA.Library; using Volian.Base.Library; using System.Text.RegularExpressions; @@ -24,22 +20,14 @@ namespace Volian.Print.Library get { return _UniqueDebugId++; } set { _UniqueDebugId = value; } } - private int _DebugId = UniqueDebugId; - public int DebugId - { - get { return _DebugId; } - set { _DebugId = value; } - } - protected static float _WidthAdjust = 1; // 1 Point - adjusted to match 16-bit line wrapping. For editting it's 3. + public int DebugId { get; set; } = UniqueDebugId; + + protected static float _WidthAdjust = 1; // 1 Point - adjusted to match 16-bit line wrapping. For editting it's 3. protected static float _WidthAdjustBox = 6; - private static float _SixLinesPerInch = 12; // twips - public static float SixLinesPerInch - { - get { return vlnPrintObject._SixLinesPerInch; } - set { vlnPrintObject._SixLinesPerInch = value; } - } - protected static float _SevenLinesPerInch = 10.1F;//72F / 7F; + + public static float SixLinesPerInch { get; set; } = 12; + protected static float _SevenLinesPerInch = 10.1F;//72F / 7F; protected float _XOffset; public float XOffset @@ -64,31 +52,13 @@ namespace Volian.Print.Library set { _MyParent = value; - if (_MyParent != null) - { - - } } } - private bool _HasIndent = false; - public bool HasIndent - { - get { return _HasIndent; } - set { _HasIndent = value; } - } - private bool _IsCompressed = false; - public bool IsCompressed - { - get { return _IsCompressed; } - set { _IsCompressed = value; } - } - private string _ImageText; // ro definition, value part of #Link in case of image/figure - public string ImageText - { - get { return _ImageText; } - set { _ImageText = value; } - } - protected string _Rtf; // may become iTextSharp paragraph + + public bool HasIndent { get; set; } = false; + public bool IsCompressed { get; set; } = false; + public string ImageText { get; set; } + protected string _Rtf; // may become iTextSharp paragraph public virtual string Rtf { get { return _Rtf; } @@ -96,15 +66,9 @@ namespace Volian.Print.Library } public class VlnSplitCharacter : ISplitCharacter { - public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) - { - return (cc[current] == ' '); - } - public bool IsSplitCharacter(char c) - { - return (c == ' '); - } - } + public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) => (cc[current] == ' '); + public bool IsSplitCharacter(char c) => (c == ' '); + } public static VlnSplitCharacter mySplitter = new VlnSplitCharacter(); // B2018-034 Attributes were being lost when the IsCompressed flag was true. // The following variable was changed to a public so that it could be used @@ -114,6 +78,7 @@ namespace Volian.Print.Library { get { + //For Debugging: // If the paragraph iscompressed, it may have been created as not compressed since compression // is not set when paragraph is initially created, it is set during pagination tests. //if (_IParagraph == null || IsCompressed) @@ -186,49 +151,10 @@ namespace Volian.Print.Library } set { _Height = value; } } - public float GetParagraphHeight(PdfContentByte cb, Paragraph iParagraph, string suffix, float width) - { - return GetParagraphHeight(cb, iParagraph, suffix, width, true); - } - public float GetParagraphHeight(PdfContentByte cb, Paragraph iParagraph, string suffix, float width, bool throwException) - { - float heightAll = GetHeight(cb, iParagraph, suffix, width, throwException); - return heightAll; - } - private static void RestoreLastCharacter(Paragraph iParagraph, Chunk chk) - { - iParagraph.RemoveAt(iParagraph.Count - 1); - iParagraph.Add(chk); - } - private static Chunk RemoveLastCharacter(Paragraph iParagraph) - { - if (iParagraph.Count == 0) - return null; - object obj = iParagraph[iParagraph.Count-1]; - Chunk chk = obj as Chunk; - if (chk == null) - return null; - string s = chk.Content; - if (s.Length > 1 || iParagraph.Count > 1) // don't remove last character if it's the only one - { - iParagraph.RemoveAt(iParagraph.Count - 1); - if (s.Length > 0) - { - if (s == "\xA0") // If this is a space at the end put it back - { - iParagraph.Add(chk); - return null; - } - else - { - s = s.Substring(0, s.Length - 1); - iParagraph.Add(new Chunk(s, chk.Font)); - } - } - } - return chk; - } - public static float GetHeight(PdfContentByte cb, Paragraph iParagraph, string suffix, float width, bool throwException) + public float GetParagraphHeight(PdfContentByte cb, Paragraph iParagraph, string suffix, float width) => GetParagraphHeight(cb, iParagraph, suffix, width, true); + public float GetParagraphHeight(PdfContentByte cb, Paragraph iParagraph, string suffix, float width, bool throwException) => (float)GetHeight(cb, iParagraph, suffix, width, throwException); + + public static float GetHeight(PdfContentByte cb, Paragraph iParagraph, string suffix, float width, bool throwException) { ColumnText myColumnText = new ColumnText(cb); float pgHeight = cb.PdfDocument.PageSize.Height; // C2020-002 paper size is now set in the format files @@ -243,7 +169,6 @@ namespace Volian.Print.Library { myColumnText.AddElement(iParagraph); } - //myColumnText.UseAscender = true;// Adjusts to the top of the text box. int status = myColumnText.Go(true); // Check to see if it will fit on the page. if (ColumnText.HasMoreText(status) && throwException) { @@ -255,7 +180,6 @@ namespace Volian.Print.Library iParagraph.IndentationLeft = 0; return GetHeight(cb, iParagraph, suffix, width, throwException); } - //throw (new Exception("Paragraph longer than a page")); Console.WriteLine("Paragraph longer than a page"); } return pgHeight - myColumnText.YLine; // This gives the height of the Paragraph // C2020-002 paper size is now set in the format files @@ -266,23 +190,19 @@ namespace Volian.Print.Library float h = GetParagraphHeight(cb, iParagraph, string.Empty, iWidth); int iWidthMax = iWidth; // maximum width in Characters int iDelta = iWidth / 2; - iWidth = iWidth / 2; + iWidth /= 2; while (iDelta > 0) { float h2 = GetParagraphHeight(cb, iParagraph, string.Empty, iWidth,false); - iDelta = iDelta / 2; + iDelta /= 2; if (h2 == h) iWidthMax = iWidth; iWidth += (h2>h ? 1: -1) * iDelta; } return (float) iWidthMax; } - private PdfContentByte _MyContentByte; - public PdfContentByte MyContentByte - { - get { return _MyContentByte; } - set { _MyContentByte = value; } - } - private VlnSvgPageHelper _MyPageHelper; + + public PdfContentByte MyContentByte { get; set; } + private VlnSvgPageHelper _MyPageHelper; public VlnSvgPageHelper MyPageHelper { get @@ -296,50 +216,34 @@ namespace Volian.Print.Library public vlnPrintObject() { } - /// - /// No conversion necessary: twips -> twips - /// - /// - /// - public static int ToInt(int value) - { - return value; - } - /// - /// No conversion necessary: int? twips -> int twips - /// - /// - /// - public static int ToInt(int? value) - { - return ToInt((int)value); - } - /// - /// No conversion necessary: string twips -> int twips - /// - /// - /// - public static int ToInt(string value) - { - return ToInt((int)Convert.ToSingle(value)); - } - /// - /// No conversion necessary: value from a list in a string, twips -> int twips - /// - /// - /// - public static int ToInt(string value, int i) - { - string s = (value.Contains(",")) ? value.Split(",".ToCharArray())[i] : value; - return ToInt(s); - } - public static string GetRtf(string text, VE_Font vFont) + /// + /// No conversion necessary: twips -> twips + /// + /// + /// + public static int ToInt(int value) => value; + /// + /// No conversion necessary: int? twips -> int twips + /// + /// + /// + public static int ToInt(int? value) => ToInt((int)value); + /// + /// No conversion necessary: string twips -> int twips + /// + /// + /// + public static int ToInt(string value) => ToInt((int)Convert.ToSingle(value)); + /// + /// No conversion necessary: value from a list in a string, twips -> int twips + /// + /// + /// + public static int ToInt(string value, int i) => ToInt((value.Contains(",")) ? value.Split(",".ToCharArray())[i] : value); + public static string GetRtf(string text, VE_Font vFont) { StringBuilder rtfSB = new StringBuilder(); - //DisplayText vlntxt = new DisplayText(text.TrimStart(" ".ToCharArray()), vFont, false); DisplayText vlntxt = new DisplayText(text, vFont, false); - //rtfSB.Append(AddFontTable(vlntxt.TextFont.WindowsFont)); - //rtfSB.Append(AddFontTable(vFont.WindowsFont)); rtfSB.Append(AddFontTable(vFont)); rtfSB.Append(vlntxt.StartText); rtfSB.Append("}"); @@ -413,11 +317,8 @@ namespace Volian.Print.Library float fE = iFont.BaseFont.GetWidthPointKerned("!", 12); return fW == fE; } - public static iTextSharp.text.Paragraph RtfToParagraph(string rtf) - { - return RtfToParagraph(rtf, false, false); - } - public static iTextSharp.text.Paragraph RtfToParagraph(string rtf, bool hasIndent, bool doPdfLinks) + public static iTextSharp.text.Paragraph RtfToParagraph(string rtf) => RtfToParagraph(rtf, false, false); + public static iTextSharp.text.Paragraph RtfToParagraph(string rtf, bool hasIndent, bool doPdfLinks) { if (hasIndent) { @@ -427,11 +328,13 @@ namespace Volian.Print.Library } IRtfDocument rtfDoc = RtfInterpreterTool.BuildDoc(rtf); - Rtf2iTextSharp rtf2IText = new Rtf2iTextSharp(rtfDoc); - rtf2IText.DoPdfLinks = doPdfLinks; - rtf2IText.HasIndent = hasIndent; - iTextSharp.text.Paragraph para = rtf2IText.Convert(); - para.SetLeading(_SixLinesPerInch, 0); + Rtf2iTextSharp rtf2IText = new Rtf2iTextSharp(rtfDoc) + { + DoPdfLinks = doPdfLinks, + HasIndent = hasIndent + }; + iTextSharp.text.Paragraph para = rtf2IText.Convert(); + para.SetLeading(SixLinesPerInch, 0); if (rtf.Contains("\x05")) // note that this is for existing customer data as of August 2015. { // if there is a hanging indent, the iTextSharp paragraph properties must be set @@ -459,22 +362,17 @@ namespace Volian.Print.Library // Change the chunks to only split on spaces rather than spaces and hyphens foreach (object obj in para)//Fix the code to check for chunks before assuming chunks { - Chunk chk = obj as Chunk; - if (chk != null && (chk.Attributes==null || !chk.Attributes.ContainsKey("NoSplit"))) - { - if (chk.Attributes == null) chk.Attributes = new System.Collections.Hashtable(); - chk.SetSplitCharacter(mySplitter); - chk.Attributes.Add("NoSplit", false); - } - } + if (obj is Chunk chk && (chk.Attributes == null || !chk.Attributes.ContainsKey("NoSplit"))) + { + if (chk.Attributes == null) chk.Attributes = new System.Collections.Hashtable(); + chk.SetSplitCharacter(mySplitter); + chk.Attributes.Add("NoSplit", false); + } + } return para; } - private static string FixNumber(string num) - { - if (num == "") return ("0"); - return num; - } - public static float CalculateHangingIndent(string rtf) + private static string FixNumber(string num) => num == "" ? "0" : num; + public static float CalculateHangingIndent(string rtf) { float chkW=0; IRtfDocument rtfDoc2 = RtfInterpreterTool.BuildDoc(rtf.Replace("\x05", @"\f1 \u9999? \f0 ")); @@ -515,9 +413,8 @@ namespace Volian.Print.Library } public void DebugPdf(PdfContentByte cb, float left, float top) { - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer debugLayer = _MyPageHelper == null ? null : _MyPageHelper.DebugLayer; - if (debugLayer == null) return; + PdfLayer debugLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.DebugLayer; + if (debugLayer == null) return; cb.SaveState(); cb.BeginLayer(debugLayer); ColumnText ct = new ColumnText(cb); @@ -531,9 +428,8 @@ namespace Volian.Print.Library cb.EndLayer(); cb.RestoreState(); } - public virtual float YBottom - { get { return YOffset + Height;} } - } + public virtual float YBottom => YOffset + Height; + } public partial class vlnPrintObjects : List { public float ToPdf(PdfContentByte cb, float yPageStart, ref float yTopMargin, ref float yBottomMargin) diff --git a/PROMS/Volian.Print.Library/vlnRNOSeparator.cs b/PROMS/Volian.Print.Library/vlnRNOSeparator.cs index db4ff3c9..ad2f3976 100644 --- a/PROMS/Volian.Print.Library/vlnRNOSeparator.cs +++ b/PROMS/Volian.Print.Library/vlnRNOSeparator.cs @@ -1,40 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text; using VEPROMS.CSLA.Library; namespace Volian.Print.Library { public partial class vlnRNOSeparator : vlnPrintObject { - private VE_Font _MyFont; - public VE_Font MyFont - { - get { return _MyFont; } - set { _MyFont = value; } - } - private bool _ExtendChangeBar; - public bool ExtendChangeBar - { - get { return _ExtendChangeBar; } - set { _ExtendChangeBar = value; } - } - private float _XLength = 0; - public float XLength - { - get { return _XLength; } - set { _XLength = value; } - } + public VE_Font MyFont { get; set; } + public bool ExtendChangeBar { get; set; } + public float XLength { get; set; } = 0; - /* if flag set and separator defined then output separator */ - /*if separator is a control-A use RNOSepLine*/ - public vlnRNOSeparator(vlnParagraph parent, PdfContentByte cb, string sepStr, float xoffset, float yoffset, FormatInfo formatInfo, bool extendChangeBar) + /* if flag set and separator defined then output separator */ + /*if separator is a control-A use RNOSepLine*/ + public vlnRNOSeparator(vlnParagraph parent, PdfContentByte cb, string sepStr, float xoffset, float yoffset, FormatInfo formatInfo, bool extendChangeBar) { MyContentByte = cb; // B2019-091: crash when printing (note moved from the 'ToPdf' method) - ExtendChangeBar = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeBarToRNOSep ? extendChangeBar : false; + ExtendChangeBar = formatInfo.PlantFormat.FormatData.ProcData.ChangeBarData.ChangeBarToRNOSep && extendChangeBar; YOffset = yoffset; XOffset = xoffset; XLength = formatInfo.PlantFormat.FormatData.SectData.StepSectionData.StepSectionPrintData.RNOSepLineLength??0; @@ -60,9 +40,8 @@ namespace Volian.Print.Library if (XLength != 0) { cb.SaveState(); - VlnSvgPageHelper _MyPageHelper = cb.PdfWriter.PageEvent as VlnSvgPageHelper; - PdfLayer textLayer = _MyPageHelper == null ? null : _MyPageHelper.TextLayer; - if (textLayer != null) cb.BeginLayer(textLayer); + PdfLayer textLayer = !(cb.PdfWriter.PageEvent is VlnSvgPageHelper _MyPageHelper) ? null : _MyPageHelper.TextLayer; + if (textLayer != null) cb.BeginLayer(textLayer); iTextSharp.text.Color lineColor = new iTextSharp.text.Color(PrintOverride.OverrideChangeBarColor(System.Drawing.Color.Black)); cb.SetColorStroke(lineColor); cb.SetLineWidth(.5F); diff --git a/PROMS/Volian.Print.Library/vlnTab.cs b/PROMS/Volian.Print.Library/vlnTab.cs index da93d9df..2fa431d2 100644 --- a/PROMS/Volian.Print.Library/vlnTab.cs +++ b/PROMS/Volian.Print.Library/vlnTab.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text; using VEPROMS.CSLA.Library; namespace Volian.Print.Library @@ -59,35 +55,21 @@ namespace Volian.Print.Library return (float)_TabOffset * MyFont.CharsToTwips; } } - private vlnMacro _MyMacro; - public vlnMacro MyMacro - { - get { return _MyMacro; } - set { _MyMacro = value; } - } - private string symblsStr = "\u25CF\u0394"; // string of possible symbol character in a tab - // add symbol characters as needed - // "\u25CF" - solid bullet - // \u0394 - delta + public vlnMacro MyMacro { get; set; } - private System.Drawing.FontStyle GetSysFontStyle(VE_Font f) - { - if (f.Style == E_Style.Italics) - return System.Drawing.FontStyle.Italic; - return FontStyle.Regular; - } - public float GetTextWidth(VE_Font vefont, string txt) - { - return GetTextWidth(vefont, txt, SymbolFontName); - } - private float GetTextWidth(VE_Font vefont, string txt, string symblFontName) + private readonly string symblsStr = "\u25CF\u0394"; // string of possible symbol character in a tab + // add symbol characters as needed + // "\u25CF" - solid bullet + // \u0394 - delta + + private System.Drawing.FontStyle GetSysFontStyle(VE_Font f) => f.Style == E_Style.Italics ? System.Drawing.FontStyle.Italic : FontStyle.Regular; + public float GetTextWidth(VE_Font vefont, string txt) => GetTextWidth(vefont, txt, SymbolFontName); + private float GetTextWidth(VE_Font vefont, string txt, string symblFontName) { // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 - //System.Drawing.Font font = new System.Drawing.Font(vefont.Family, (float)vefont.Size, GetSysFontStyle(vefont)); - //System.Drawing.Font symbFont = new System.Drawing.Font(symblFontName, (float)vefont.Size); System.Drawing.Font font = VE_Font.GetWinSysFont(vefont.Family, (float)vefont.Size, GetSysFontStyle(vefont)); System.Drawing.Font symbFont = VE_Font.GetWinSysFont(symblFontName, (float)vefont.Size); iTextSharp.text.Font iFont = Volian.Svg.Library.VolianPdf.GetFont(font); @@ -101,30 +83,14 @@ namespace Volian.Print.Library else w += iFont.BaseFont.GetWidthPointKerned(c.ToString(), (float)vefont.Size); } - //float w = iFont.BaseFont.GetWidthPointKerned(Text.Replace("\u25CF","@"), (float)vefont.Size); return w; } - bool _ScriptCaution = false; - public bool ScriptCaution - { - get { return _ScriptCaution; } - set { _ScriptCaution = value; } - } - bool _SeparateBullet = false; + public bool ScriptCaution { get; set; } = false; - public bool SeparateBullet - { - get { return _SeparateBullet; } - set { _SeparateBullet = value; } - } - private string _SymbolFontName; - public string SymbolFontName - { - get { return _SymbolFontName; } - set { _SymbolFontName = value; } - } - public vlnTab(PdfContentByte cb, vlnParagraph myparent, string origTab, string cleanTab, float xoffset, float yoffset, VE_Font vFont, bool doSectTab, string symblFontName, bool removedUnderline) + public bool SeparateBullet { get; set; } = false; + public string SymbolFontName { get; set; } + public vlnTab(PdfContentByte cb, vlnParagraph myparent, string origTab, string cleanTab, float xoffset, float yoffset, VE_Font vFont, bool doSectTab, string symblFontName, bool removedUnderline) { SymbolFontName = symblFontName; bool alignAsIfBulleted = false; @@ -149,20 +115,14 @@ namespace Volian.Print.Library Width = 90; } else if ((myparent.MyItemInfo.FormatStepData != null) && (myparent.MyItemInfo.FormatStepData.TabData.IdentWidth ?? 0) > 0) - //if ((myparent.MyItemInfo.FormatStepData != null) && (myparent.MyItemInfo.FormatStepData.TabData.IdentWidth ?? 0) > 0) Width = (float)myparent.MyItemInfo.FormatStepData.TabData.IdentWidth; else if (CCCs != IIIs) { float tPtPerChar = myparent.MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.TabPtsPerChar ?? 6; Width = (tPtPerChar == 0 ? 6 : tPtPerChar) * origTab.Length; - // Check the following, it may be needed for FPL: - //origTab1 = origTab1.TrimStart(" ".ToCharArray()); - // 6 = number of points per character. 4 characters between end of tab and beginning of text - // origTab1.Trim... is number of non-space characters of the tab string. - //Width = 6 * (4 + origTab1.Trim(" ".ToCharArray()).Length); } else - Width = GetTextWidth(MyFont, (Text != null ? Text : origTab), symblFontName); + Width = GetTextWidth(MyFont, (Text ?? origTab), symblFontName); // Pairie Island (NSP) Caution and Note tabs use a larger font // When using a bullet, we need to use the font size of the Caution/Note text instead of the tab. @@ -202,7 +162,7 @@ namespace Volian.Print.Library Width = (float)myparent.MyItemInfo.FormatStepData.TabData.IdentWidth; else { - origTab = origTab + " "; + origTab += " "; origTab = origTab.TrimStart(" ".ToCharArray()); if (mindx > 2) // ouch! Width = 6f * (origTab.Length - 1); // FPL (macro is after {numeric}) FPL is good with genmac output! @@ -211,7 +171,7 @@ namespace Volian.Print.Library } } else - Width = GetTextWidth(MyFont, (cleanTab != null ? cleanTab : origTab), symblFontName);//MyFont.CharsToTwips * (cleanTab != null ? cleanTab.Length : origTab.Length); + Width = GetTextWidth(MyFont, (cleanTab ?? origTab), symblFontName);//MyFont.CharsToTwips * (cleanTab != null ? cleanTab.Length : origTab.Length); } else { @@ -226,8 +186,6 @@ namespace Volian.Print.Library int sep = origTab.IndexOfAny(". ".ToCharArray()); string prefix = ((vFont.Style & E_Style.Bold) > 0) ? @"\b\ul " : @"\ul "; string suffix = ((vFont.Style & E_Style.Bold) > 0) ? @"\b0\ulnone " : @"\ulnone "; - //origTab = @"\ul " + origTab.Substring(0, sep-1) + @"\ulnone" + origTab.Substring(sep-1); - //origTab = @"\ul " + origTab.Substring(0, sep) + @"\ulnone" + origTab.Substring(sep); origTab = prefix + origTab.Substring(0, sep) + suffix + origTab.Substring(sep); } @@ -245,7 +203,6 @@ namespace Volian.Print.Library // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 - //vFont.WindowsFont = new System.Drawing.Font(vFont.Family, (float)vFont.Size, style); vFont.WindowsFont = VE_Font.GetWinSysFont(vFont.Family, (float)vFont.Size, style); int indxC = origTab.IndexOf(":"); origTab = @"\ul " + origTab.Substring(0, indxC) + @"\ulnone" + origTab.Substring(indxC); @@ -262,7 +219,6 @@ namespace Volian.Print.Library // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 - //vFont.WindowsFont = new System.Drawing.Font(vFont.Family, (float)vFont.Size, style); vFont.WindowsFont = VE_Font.GetWinSysFont(vFont.Family, (float)vFont.Size, style); int indxC = origTab.IndexOf(ut.Text); string prefix = ((vFont.Style & E_Style.Bold) > 0) ? @"\b\ul " : @"\ul "; @@ -301,7 +257,6 @@ namespace Volian.Print.Library (myparent.MyItemInfo.MyPrevious.MyContent.Type == myparent.MyItemInfo.MyContent.Type))) { //if (scriptCaution) - // Rtf = Rtf.Replace("CAUTION ", @"\u61472?\u61472?\u61472?\u61472?\u61472?\u61472?\u61472?\u61472?\u61472?"); Rtf = Rtf.Replace("Caution:", " "); Rtf = Rtf.Replace("Note:", " "); Rtf = Rtf.Replace("CAUTION:", " "); @@ -312,19 +267,6 @@ namespace Volian.Print.Library Rtf = Rtf.Replace("NOTE", " "); } } - //if (ScriptCaution && Rtf.Contains("Caution")) - //{ - // // NSP script caution - // iTextSharp.text.Font myfont = pdf.GetFont(vFont.Family, 28, 0, iTextSharp.text.Color.BLACK); - // if (!myfont.BaseFont.CharExists(0x43)) // Capital 'C' exists as text - // { - // //VE_Font vf = new VE_Font("VolianScript", 28, E_Style.Italics, 12); - // // Capital 'C' exists as Symbol - // Rtf = Rtf.Replace("Caution ", @"\u61507?\u61537?\u61557?\u61556?\u61545?\u61551?\u61550?\u61472?\u61472?"); - // } - - //} - // do positioning based on whether format has locations for section 'header'. If it's not centered, treat // it's location more like a 'tab'. @@ -350,7 +292,6 @@ namespace Volian.Print.Library // follow through in fixing an Out of Window Handles bug, use new function to see if // we can retrieve the font from a dictionary instead a doing a New and using another // window handle B2017-117 - //System.Drawing.Font font = new System.Drawing.Font(MyFont.Family, (float)MyFont.Size); System.Drawing.Font font = VE_Font.GetWinSysFont(MyFont.Family, (float)MyFont.Size); iTextSharp.text.Font iFont = Volian.Svg.Library.VolianPdf.GetFont(font); float w = iFont.BaseFont.GetWidthPointKerned(txt, (float)MyFont.Size); diff --git a/PROMS/Volian.Print.Library/vlnText.cs b/PROMS/Volian.Print.Library/vlnText.cs index 5693d0e1..2e314635 100644 --- a/PROMS/Volian.Print.Library/vlnText.cs +++ b/PROMS/Volian.Print.Library/vlnText.cs @@ -1,32 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; using iTextSharp.text.pdf; -using iTextSharp.text; using VEPROMS.CSLA.Library; namespace Volian.Print.Library { public partial class vlnText : vlnPrintObject { - //public float Width - //{ - // get { return _CharsToTwips * Text.Length; } - //} - private string _Text; - public string Text - { - get { return _Text; } - set { _Text = value; } - } - private VE_Font _MyFont; - public VE_Font MyFont - { - get { return _MyFont; } - set { _MyFont = value; } - } - public vlnText(PdfContentByte cb, vlnParagraph myparent, string origText, string cleanText, float xoffset, float yoffset, VE_Font vFont) + public string Text { get; set; } + public VE_Font MyFont { get; set; } + public vlnText(PdfContentByte cb, vlnParagraph myparent, string origText, string cleanText, float xoffset, float yoffset, VE_Font vFont) { MyContentByte = cb; MyParent = myparent; diff --git a/PROMS/Volian.Svg.Library/FontFind.cs b/PROMS/Volian.Svg.Library/FontFind.cs deleted file mode 100644 index 1ddad575..00000000 --- a/PROMS/Volian.Svg.Library/FontFind.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; -using Microsoft.Win32; - -namespace Volian.Svg.Library -{ - //public static class FontFind - //{ - // public static string FileName(string fontName) - // { - // string baseFont = string.Empty; - // Regex find = new Regex(fontName + @".* ?\(.*\)", RegexOptions.IgnoreCase); - // RegistryKey regKey = Registry.LocalMachine.CreateSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Fonts"); - // string[] values = regKey.GetValueNames(); - // baseFont = regKey.GetValue(values[0]).ToString(); - // foreach (string valueName in regKey.GetValueNames()) - // { - // if (find.IsMatch(valueName)) - // return regKey.GetValue(valueName).ToString(); - // } - // return baseFont; - // } - // public static string FullFileName(string fontName) - // { - // return @"c:\windows\fonts\" + FileName(fontName); - // } - //} -} diff --git a/PROMS/Volian.Svg.Library/Graphics.cs b/PROMS/Volian.Svg.Library/Graphics.cs index 0b04d26b..02f07f00 100644 --- a/PROMS/Volian.Svg.Library/Graphics.cs +++ b/PROMS/Volian.Svg.Library/Graphics.cs @@ -17,13 +17,6 @@ namespace Volian.Svg.Library } public partial class Svg : SvgGroup { - public void Draw(Graphics graphics) - { - //SetupInheritance(); - //Console.WriteLine("{0}, DPI {1}", graphics.VisibleClipBounds, graphics.DpiX); - SvgParts.Draw(graphics, new SvgScale(DeviceDPI(graphics), graphics.VisibleClipBounds, _Width, _Height, _ViewBox), this, this); - //SvgParts.Draw(graphics, new SvgScale(100, graphics.VisibleClipBounds, _Width, _Height, _ViewBox)); - } public static float DeviceDPI(Graphics g) { PointF[] tmp = { new PointF(g.DpiX, g.DpiY) }; @@ -36,7 +29,6 @@ namespace Volian.Svg.Library public override void Draw(System.Drawing.Graphics graphics, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) { SetupInheritance(myParent.MyInheritedSettings); - //_MyLineSettings.Scale = scale.M(1F); if (FillColor != Color.Transparent) using (Brush brush = new SolidBrush(FillColor)) graphics.FillEllipse(brush, scale.X(CX - Radius), scale.Y(CY - Radius), scale.M(Radius * 2), scale.M(Radius * 2)); @@ -50,7 +42,6 @@ namespace Volian.Svg.Library public override void Draw(System.Drawing.Graphics graphics, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) { SetupInheritance(myParent.MyInheritedSettings); - //_MyLineSettings.Scale = scale.M(1F); if (FillColor != Color.Transparent) using (Brush brush = new SolidBrush(FillColor)) graphics.FillEllipse(brush, scale.X(CX - Radius), scale.Y(CY - Radius), scale.M(Radius * 2), scale.M(Radius * 2)); @@ -64,7 +55,6 @@ namespace Volian.Svg.Library public override void Draw(Graphics graphics, SvgScale myScale, Svg mySvg, SvgPartInheritance myParent) { // Don't draw - //_SvgParts.Draw(graphics, myScale); } } public partial class SvgEllipse : SvgShapePart @@ -85,7 +75,7 @@ namespace Volian.Svg.Library public override void Draw(Graphics graphics, SvgScale myScale, Svg mySvg, SvgPartInheritance myParent) { SetupInheritance(myParent.MyInheritedSettings); - _SvgParts.Draw(graphics, myScale, mySvg, this); + SvgParts.Draw(graphics, myScale, mySvg, this); } } public partial class SvgImage : SvgPart @@ -130,26 +120,9 @@ namespace Volian.Svg.Library graphics.DrawRectangle(pen, scale.X(X),scale.Y(Y), scale.M(Width), scale.M(Height)); } } - //public partial class SvgRtf : SvgShapePart - //{ - // //private static float _Factor = 1.085F; // 20 point Arial Font - // public override void Draw(System.Drawing.Graphics graphics, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) - // { - // SetupInheritance(myParent.MyInheritedSettings); - // _MyFontSettings.Scale = scale.M(1F); - // } - // private float YAdjustment(Graphics gr, Font fnt) - // { - // int yAsc = fnt.FontFamily.GetCellAscent(fnt.Style); - // int yLS = fnt.FontFamily.GetLineSpacing(fnt.Style); - // float gth = fnt.GetHeight(gr); - // float fAsc = (yAsc * gth) / yLS; - // return -fAsc; - // } - //} + public partial class SvgText : SvgShapePart { - //private static float _Factor = 1.085F; // 20 point Arial Font public override void Draw(System.Drawing.Graphics graphics, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) { SetupInheritance(myParent.MyInheritedSettings); @@ -175,8 +148,6 @@ namespace Volian.Svg.Library private float YAdjustment(Graphics gr, Font fnt) { int yAsc = fnt.FontFamily.GetCellAscent(fnt.Style); - //int yDesc = fnt.FontFamily.GetCellDescent(fnt.Style); - //int yEm = fnt.FontFamily.GetEmHeight(fnt.Style); int yLS = fnt.FontFamily.GetLineSpacing(fnt.Style); float gth = fnt.GetHeight(gr); float fh = fnt.Size; @@ -189,7 +160,7 @@ namespace Volian.Svg.Library public override void Draw(System.Drawing.Graphics graphics, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) { SetupInheritance(myParent.MyInheritedSettings); - mySvg[_UseID.Substring(1)].Draw(graphics, scale.AdjustOrigin(X, Y), mySvg, this); + mySvg[UseID.Substring(1)].Draw(graphics, scale.AdjustOrigin(X, Y), mySvg, this); } } } diff --git a/PROMS/Volian.Svg.Library/Svg.cs b/PROMS/Volian.Svg.Library/Svg.cs index 982a7029..03d52264 100644 --- a/PROMS/Volian.Svg.Library/Svg.cs +++ b/PROMS/Volian.Svg.Library/Svg.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; @@ -37,84 +35,46 @@ namespace Volian.Svg.Library } set { _Namespaces = value; } } - #endregion - #region Width - private SvgMeasurement _Width = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Width - { - get { return _Width; } - set { _Width = value; } - } - [System.ComponentModel.DefaultValueAttribute("0")] + #endregion + #region Width + [XmlIgnore] + public SvgMeasurement Width { get; set; } = new SvgMeasurement(); + [System.ComponentModel.DefaultValueAttribute("0")] [XmlAttribute("width")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Width_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Width); } - set { _Width = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Width); } + set { Width = SvgXmlConverter.GetObject(value); } } - //private string _Watermark=""; - //[XmlAttribute("watermark")] - //public string Watermark - //{ - // get { return _Watermark; } - // set { _Watermark = value; } - //} - //public void SetValidWaterMark(string token, string watermark) - //{ - // if (token == "{" + watermark.ToUpper() + "PAGE}" ) - // _Watermark = watermark; - //} - #endregion - #region Height - private SvgMeasurement _Height = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Height - { - get { return _Height; } - set { _Height = value; } - } - [System.ComponentModel.DefaultValueAttribute("0")] + #endregion + #region Height + [XmlIgnore] + public SvgMeasurement Height { get; set; } = new SvgMeasurement(); + [System.ComponentModel.DefaultValueAttribute("0")] [XmlAttribute("height")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Height_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Height); } - set { _Height = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Height); } + set { Height = SvgXmlConverter.GetObject(value); } } - #endregion - #region ViewBox - private SvgViewBox _ViewBox = new SvgViewBox("0 0 0 0"); - [XmlIgnore] - public SvgViewBox ViewBox - { - get { return _ViewBox; } - set { _ViewBox = value; } - } - [System.ComponentModel.DefaultValueAttribute("0 0 0 0")] + #endregion + #region ViewBox + [XmlIgnore] + public SvgViewBox ViewBox { get; set; } = new SvgViewBox("0 0 0 0"); + [System.ComponentModel.DefaultValueAttribute("0 0 0 0")] [XmlAttribute("viewBox")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string SVGViewBox_XmlSurrogate { - get { return SvgXmlConverter.GetString(_ViewBox); } - set { _ViewBox = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(ViewBox); } + set { ViewBox = SvgXmlConverter.GetObject(value); } } #endregion - //#region Setup Inheritance - //private void SetupInheritance() - //{ - // SvgParts.SetupInheritance(_MyInheritedSettings); - //} - ////override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) - ////{ - //// _MyInheritedSettings.MyParentsSettings = myParentsSettings; - //// SvgParts.SetupInheritance(_MyInheritedSettings); - ////} - //#endregion #region Part Lookup private Dictionary _LookUp; [XmlIgnore] diff --git a/PROMS/Volian.Svg.Library/SvgArc.cs b/PROMS/Volian.Svg.Library/SvgArc.cs index 407d26d1..9e3c7fd1 100644 --- a/PROMS/Volian.Svg.Library/SvgArc.cs +++ b/PROMS/Volian.Svg.Library/SvgArc.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,65 +10,48 @@ namespace Volian.Svg.Library public SvgArc() { ;} public SvgArc(PointF location, float radius, float startAngle, float endAngle, Color fillColor, Color lineColor, float lineWidth) { - _CX.Value = location.X; - _CY.Value = location.Y; - _Radius.Value = radius; + CX.Value = location.X; + CY.Value = location.Y; + Radius.Value = radius; FillColor = fillColor; LineColor = lineColor; LineWidth = new SvgMeasurement(lineWidth); } - //XMLElementAttribute(ElementName = "PREFIX", IsNullable = false) - #endregion - #region Location - private SvgMeasurement _CX = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement CX - { - get { return _CX; } - set { _CX = value; } - } - [XmlAttribute("cx")] + #endregion + #region Location + [XmlIgnore] + public SvgMeasurement CX { get; set; } = new SvgMeasurement(); + [XmlAttribute("cx")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string CX_XmlSurrogate { - get { return SvgXmlConverter.GetString(_CX); } - set { _CX = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(CX); } + set { CX = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _CY = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement CY - { - get { return _CY; } - set { _CY = value; } - } - [XmlAttribute("cy")] + + [XmlIgnore] + public SvgMeasurement CY { get; set; } = new SvgMeasurement(); + [XmlAttribute("cy")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string CY_XmlSurrogate { - get { return SvgXmlConverter.GetString(_CY); } - set { _CY = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(CY); } + set { CY = SvgXmlConverter.GetObject(value); } } - #endregion - #region Radius - private SvgMeasurement _Radius = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Radius - { - get { return _Radius; } - set { _Radius = value; } - } - [XmlAttribute("r")] + #endregion + #region Radius + [XmlIgnore] + public SvgMeasurement Radius { get; set; } = new SvgMeasurement(); + [XmlAttribute("r")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Radius); } - set { _Radius = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Radius); } + set { Radius = SvgXmlConverter.GetObject(value); } } #endregion - #region Angles - #endregion } } diff --git a/PROMS/Volian.Svg.Library/SvgCircle.cs b/PROMS/Volian.Svg.Library/SvgCircle.cs index 5c1b8500..9ff8f2fd 100644 --- a/PROMS/Volian.Svg.Library/SvgCircle.cs +++ b/PROMS/Volian.Svg.Library/SvgCircle.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,62 +10,47 @@ namespace Volian.Svg.Library public SvgCircle() { ;} public SvgCircle(PointF location, float radius, Color fillColor, Color lineColor, float lineWidth) { - _CX.Value = location.X; - _CY.Value = location.Y; - _Radius.Value = radius; + CX.Value = location.X; + CY.Value = location.Y; + Radius.Value = radius; FillColor = fillColor; LineColor = lineColor; LineWidth = new SvgMeasurement(lineWidth); } - //XMLElementAttribute(ElementName = "PREFIX", IsNullable = false) - #endregion - #region Location - private SvgMeasurement _CX = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement CX - { - get { return _CX; } - set { _CX = value; } - } - [XmlAttribute("cx")] + #endregion + #region Location + [XmlIgnore] + public SvgMeasurement CX { get; set; } = new SvgMeasurement(); + [XmlAttribute("cx")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string CX_XmlSurrogate { - get { return SvgXmlConverter.GetString(_CX); } - set { _CX = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(CX); } + set { CX = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _CY = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement CY - { - get { return _CY; } - set { _CY = value; } - } - [XmlAttribute("cy")] + + [XmlIgnore] + public SvgMeasurement CY { get; set; } = new SvgMeasurement(); + [XmlAttribute("cy")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string CY_XmlSurrogate { - get { return SvgXmlConverter.GetString(_CY); } - set { _CY = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(CY); } + set { CY = SvgXmlConverter.GetObject(value); } } - #endregion - #region Radius - private SvgMeasurement _Radius = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Radius - { - get { return _Radius; } - set { _Radius = value; } - } - [XmlAttribute("r")] + #endregion + #region Radius + [XmlIgnore] + public SvgMeasurement Radius { get; set; } = new SvgMeasurement(); + [XmlAttribute("r")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Radius); } - set { _Radius = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Radius); } + set { Radius = SvgXmlConverter.GetObject(value); } } #endregion } diff --git a/PROMS/Volian.Svg.Library/SvgDefine.cs b/PROMS/Volian.Svg.Library/SvgDefine.cs index 30a64e56..8e2ff09b 100644 --- a/PROMS/Volian.Svg.Library/SvgDefine.cs +++ b/PROMS/Volian.Svg.Library/SvgDefine.cs @@ -1,10 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml.Serialization; -using System.ComponentModel; -using System.Drawing; - namespace Volian.Svg.Library { public partial class SvgDefine : SvgGroup diff --git a/PROMS/Volian.Svg.Library/SvgEllipse.cs b/PROMS/Volian.Svg.Library/SvgEllipse.cs index bd72768d..7cf0c823 100644 --- a/PROMS/Volian.Svg.Library/SvgEllipse.cs +++ b/PROMS/Volian.Svg.Library/SvgEllipse.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,78 +10,59 @@ namespace Volian.Svg.Library public SvgEllipse() { ;} public SvgEllipse(PointF location, float radiusX, float radiusY, Color fillColor, Color lineColor, float lineWidth) { - _CX.Value = location.X; - _CY.Value = location.Y; - _RX.Value = radiusX; - _RY.Value = radiusY; + CX.Value = location.X; + CY.Value = location.Y; + RX.Value = radiusX; + RY.Value = radiusY; FillColor = fillColor; LineColor = lineColor; LineWidth = new SvgMeasurement(lineWidth); } - //XMLElementAttribute(ElementName = "PREFIX", IsNullable = false) - #endregion - #region Location - private SvgMeasurement _CX = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement CX - { - get { return _CX; } - set { _CX = value; } - } - [XmlAttribute("cx")] + #endregion + #region Location + [XmlIgnore] + public SvgMeasurement CX { get; set; } = new SvgMeasurement(); + [XmlAttribute("cx")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string CX_XmlSurrogate { - get { return SvgXmlConverter.GetString(_CX); } - set { _CX = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(CX); } + set { CX = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _CY = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement CY - { - get { return _CY; } - set { _CY = value; } - } - [XmlAttribute("cy")] + + [XmlIgnore] + public SvgMeasurement CY { get; set; } = new SvgMeasurement(); + [XmlAttribute("cy")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string CY_XmlSurrogate { - get { return SvgXmlConverter.GetString(_CY); } - set { _CY = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(CY); } + set { CY = SvgXmlConverter.GetObject(value); } } - #endregion - #region Size - private SvgMeasurement _RX = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement RX - { - get { return _RX; } - set { _RX = value; } - } - [XmlAttribute("rx")] + #endregion + #region Size + [XmlIgnore] + public SvgMeasurement RX { get; set; } = new SvgMeasurement(); + [XmlAttribute("rx")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string RX_RXmlSurrogate { - get { return SvgXmlConverter.GetString(_RX); } - set { _RX = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(RX); } + set { RX = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _RY = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement RY - { - get { return _RY; } - set { _RY = value; } - } - [XmlAttribute("ry")] + + [XmlIgnore] + public SvgMeasurement RY { get; set; } = new SvgMeasurement(); + [XmlAttribute("ry")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string RY_XmlSurrogate { - get { return SvgXmlConverter.GetString(_RY); } - set { _RY = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(RY); } + set { RY = SvgXmlConverter.GetObject(value); } } #endregion } diff --git a/PROMS/Volian.Svg.Library/SvgFillSettings.cs b/PROMS/Volian.Svg.Library/SvgFillSettings.cs index 5c371699..d35fddbe 100644 --- a/PROMS/Volian.Svg.Library/SvgFillSettings.cs +++ b/PROMS/Volian.Svg.Library/SvgFillSettings.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; namespace Volian.Svg.Library @@ -9,34 +6,18 @@ namespace Volian.Svg.Library { #region ctor public SvgFillSettings() { ;} - public SvgFillSettings(Color myColor) - { - _Fill = ColorTranslator.ToHtml(myColor); - } - //public SvgFillSettings(string myFill) - //{ - // _Fill = myFill; - //} - #endregion - #region Inheritance - private SvgFillSettings _MyParentsSettings = null; - public SvgFillSettings MyParentsSettings - { - get { return _MyParentsSettings; } - set - { - _MyParentsSettings = value; - } - } - #endregion - #region Internal Inherited Properties - protected string InheritedFill + public SvgFillSettings(Color myColor) => Fill = ColorTranslator.ToHtml(myColor); + #endregion + #region Inheritance + public SvgFillSettings MyParentsSettings { get; set; } = null; + #endregion + #region Internal Inherited Properties + protected string InheritedFill { get { - // Fill = "", "0" - Default, otherwise the value - if (_Fill != "" && _Fill != "0" && _Fill.ToLower() != "empty") return _Fill; // Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedFill; // Inherited + if (Fill != "" && Fill != "0" && Fill.ToLower() != "empty") return Fill; // Current Value + if (MyParentsSettings != null) return MyParentsSettings.InheritedFill; // Inherited return "Black"; // Default } } @@ -54,20 +35,12 @@ namespace Volian.Svg.Library } set { - if (value == Color.Transparent || value == Color.Empty) - _Fill = "none"; - else - _Fill = ColorTranslator.ToHtml(value); - } + Fill = value == Color.Transparent || value == Color.Empty ? "none" : ColorTranslator.ToHtml(value); + } } - #endregion - #region Properties - private string _Fill = string.Empty; // Default value is None - public string Fill - { - get { return _Fill; } - set { _Fill = value; } - } - #endregion - } + #endregion + #region Properties + public string Fill { get; set; } = string.Empty; + #endregion + } } diff --git a/PROMS/Volian.Svg.Library/SvgFontSettings.cs b/PROMS/Volian.Svg.Library/SvgFontSettings.cs index d151c16e..30e8100d 100644 --- a/PROMS/Volian.Svg.Library/SvgFontSettings.cs +++ b/PROMS/Volian.Svg.Library/SvgFontSettings.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; namespace Volian.Svg.Library @@ -17,33 +14,17 @@ namespace Volian.Svg.Library _FontWeight = ((myFont.Style & FontStyle.Bold) == FontStyle.Bold ? "bold" : "normal"); _TextDecoration = ((myFont.Style & FontStyle.Underline) == FontStyle.Underline ? "underline" : "normal"); } - //public SvgFontSettings(string myFontFamily, string myFontSize, string mySvgStyle, string myFontWeight, string myTextDecoration) - //{ - // _FontFamilyName = myFontFamily; - // _FontSize = myFontSize; - // _SVGFontStyle = mySvgStyle; - // _FontWeight = myFontWeight; - // _TextDecoration = myTextDecoration; - //} - #endregion - #region Inheritance - private SvgFontSettings _MyParentsSettings = null; - public SvgFontSettings MyParentsSettings - { - get { return _MyParentsSettings; } - set - { - _MyParentsSettings = value; - } - } - #endregion - #region Internal Inherited Properties - protected string InheritedFontFamily + #endregion + #region Inheritance + public SvgFontSettings MyParentsSettings { get; set; } = null; + #endregion + #region Internal Inherited Properties + protected string InheritedFontFamily { get { if (_FontFamily != "") return _FontFamily; - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedFontFamily; // Default + if (MyParentsSettings != null) return MyParentsSettings.InheritedFontFamily; // Default return "Arial"; // Absolute Default } } @@ -52,7 +33,7 @@ namespace Volian.Svg.Library get { if (_FontSize != "") return _FontSize; // Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedFontSize; // Default + if (MyParentsSettings != null) return MyParentsSettings.InheritedFontSize; // Default return "9PT"; // Absolute Default } } @@ -61,7 +42,7 @@ namespace Volian.Svg.Library get { if (_SVGFontStyle != "") return _SVGFontStyle; // Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedFontStyle;// Default + if (MyParentsSettings != null) return MyParentsSettings.InheritedFontStyle;// Default return "normal"; // Absolute Default } } @@ -70,7 +51,7 @@ namespace Volian.Svg.Library get { if (_FontWeight != "") return _FontWeight;// Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedFontWeight;// Default + if (MyParentsSettings != null) return MyParentsSettings.InheritedFontWeight;// Default return "normal"; // Absolute Default } } @@ -79,7 +60,7 @@ namespace Volian.Svg.Library get { if (_TextDecoration != "") return _TextDecoration;// Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedTextDecoration;// Default + if (MyParentsSettings != null) return MyParentsSettings.InheritedTextDecoration;// Default return "normal"; // Absolute Default } } @@ -110,13 +91,6 @@ namespace Volian.Svg.Library } set { - // This was disposing fonts that are saved in our static dictionary. - // caused problems with the step editor display after printing (found with Wolf Creek Chem procedure RW-G02 Step 6.1.17) - jsj 7/14/2017 - //if (_Font != null) - //{ - // Console.WriteLine("font dispose {0}, {1}", _Font, _Font.Style); - // //_Font.Dispose(); - //} if (value != null) { _FontFamily = value.FontFamily.Name; diff --git a/PROMS/Volian.Svg.Library/SvgGroup.cs b/PROMS/Volian.Svg.Library/SvgGroup.cs index 69a49907..a6380fd9 100644 --- a/PROMS/Volian.Svg.Library/SvgGroup.cs +++ b/PROMS/Volian.Svg.Library/SvgGroup.cs @@ -1,75 +1,48 @@ -using System; using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; -using System.ComponentModel; -using System.Drawing; namespace Volian.Svg.Library { public partial class SvgGroup : SvgPartInheritance { - #region Description - private string _Description = string.Empty; - [System.ComponentModel.DefaultValueAttribute("")] - [XmlElement("desc")] - public string Description + #region Description + [System.ComponentModel.DefaultValueAttribute("")] + [XmlElement("desc")] + public string Description { get; set; } = string.Empty; + #endregion + #region Title + [System.ComponentModel.DefaultValueAttribute("")] + [XmlElement("title")] + public string Title { get; set; } = string.Empty; + #endregion + #region Parts + // SVG Parts + [XmlElement("use", typeof(SvgUse))] + [XmlElement("image", typeof(SvgImage))] + [XmlElement("text", typeof(SvgText))] + [XmlElement("line", typeof(SvgLine))] + [XmlElement("circle", typeof(SvgCircle))] + [XmlElement("rect", typeof(SvgRectangle))] + [XmlElement("ellipse", typeof(SvgEllipse))] + [XmlElement("svg", typeof(Svg))] + [XmlElement("g", typeof(SvgGroup))] + [XmlElement("defs", typeof(SvgDefine))] + public SvgParts SvgParts { get; set; } = new SvgParts(); + public SvgPart Add(SvgPart svgPart) { - get { return _Description; } - set { _Description = value; } - } - #endregion - #region Title - private string _Title = string.Empty; - [System.ComponentModel.DefaultValueAttribute("")] - [XmlElement("title")] - public string Title - { - get { return _Title; } - set { _Title = value; } - } - #endregion - #region Parts - // SVG Parts - SvgParts _SvgParts = new SvgParts(); - //[XmlElement("foreignObject", typeof(SvgRtf))] - [XmlElement("use", typeof(SvgUse))] - [XmlElement("image", typeof(SvgImage))] - [XmlElement("text", typeof(SvgText))] - [XmlElement("line", typeof(SvgLine))] - [XmlElement("circle", typeof(SvgCircle))] - [XmlElement("rect", typeof(SvgRectangle))] - [XmlElement("ellipse", typeof(SvgEllipse))] - [XmlElement("svg", typeof(Svg))] - [XmlElement("g", typeof(SvgGroup))] - [XmlElement("defs", typeof(SvgDefine))] - public SvgParts SvgParts - { - get { return _SvgParts; } - set { _SvgParts = value; } - } - public SvgPart Add(SvgPart svgPart) - { - _SvgParts.Add(svgPart); + SvgParts.Add(svgPart); return svgPart; } - public void RemoveAt(int i) - { - _SvgParts.RemoveAt(i); - } - public int Count - { get { return _SvgParts.Count; } } - #endregion - #region Dictionary of Parts - internal override void AddLookup(Dictionary lookUp) + public void RemoveAt(int i) => SvgParts.RemoveAt(i); + public int Count => SvgParts.Count; + #endregion + #region Dictionary of Parts + internal override void AddLookup(Dictionary lookUp) { base.AddLookup(lookUp); SvgParts.AddLookup(lookUp); } - #endregion - public override string ToString() - { - return ID; - } - } + #endregion + public override string ToString() => ID; + } } \ No newline at end of file diff --git a/PROMS/Volian.Svg.Library/SvgImage.cs b/PROMS/Volian.Svg.Library/SvgImage.cs index 012cae61..be0a1843 100644 --- a/PROMS/Volian.Svg.Library/SvgImage.cs +++ b/PROMS/Volian.Svg.Library/SvgImage.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,87 +10,64 @@ namespace Volian.Svg.Library public SvgImage() { ;} public SvgImage(PointF location, SizeF size, string path) { - _X.Value = location.X; - _Y.Value = location.Y; - _Width.Value = size.Width; - _Height.Value = size.Height; - _ImagePath = path; + X.Value = location.X; + Y.Value = location.Y; + Width.Value = size.Width; + Height.Value = size.Height; + ImagePath = path; } - #endregion - #region Location - private SvgMeasurement _X = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement X - { - get { return _X; } - set { _X = value; } - } - [XmlAttribute("x")] + #endregion + #region Location + [XmlIgnore] + public SvgMeasurement X { get; set; } = new SvgMeasurement(); + [XmlAttribute("x")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X_XmlSurrogate { - get { return SvgXmlConverter.GetString(_X); } - set { _X = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(X); } + set { X = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Y = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Y - { - get { return _Y; } - set { _Y = value; } - } - [XmlAttribute("y")] + + [XmlIgnore] + public SvgMeasurement Y { get; set; } = new SvgMeasurement(); + [XmlAttribute("y")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Y_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Y); } - set { _Y = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Y); } + set { Y = SvgXmlConverter.GetObject(value); } } - #endregion - #region Size - private SvgMeasurement _Width = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Width - { - get { return _Width; } - set { _Width = value; } - } - [XmlAttribute("width")] + #endregion + #region Size + [XmlIgnore] + public SvgMeasurement Width { get; set; } = new SvgMeasurement(); + [XmlAttribute("width")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Width_WidthmlSurrogate { - get { return SvgXmlConverter.GetString(_Width); } - set { _Width = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Width); } + set { Width = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Height = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Height - { - get { return _Height; } - set { _Height = value; } - } - [XmlAttribute("height")] + + [XmlIgnore] + public SvgMeasurement Height { get; set; } = new SvgMeasurement(); + [XmlAttribute("height")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Height_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Height); } - set { _Height = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Height); } + set { Height = SvgXmlConverter.GetObject(value); } } - #endregion - #region Path to Image File - private string _ImagePath = null; - [XmlAttribute(AttributeName = "href", Namespace = "http://www.w3.org/1999/xlink")] - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public string ImagePath - { - get { return _ImagePath; } - set { _ImagePath = value; } - } - #endregion - } + #endregion + #region Path to Image File + [XmlAttribute(AttributeName = "href", Namespace = "http://www.w3.org/1999/xlink")] + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public string ImagePath { get; set; } = null; + #endregion + } } \ No newline at end of file diff --git a/PROMS/Volian.Svg.Library/SvgInheritedSettings.cs b/PROMS/Volian.Svg.Library/SvgInheritedSettings.cs index 702ad9cc..97e0d442 100644 --- a/PROMS/Volian.Svg.Library/SvgInheritedSettings.cs +++ b/PROMS/Volian.Svg.Library/SvgInheritedSettings.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace Volian.Svg.Library { internal class SvgInheritedSettings @@ -19,69 +15,54 @@ namespace Volian.Svg.Library MyFontSettings.MyParentsSettings = value.MyFontSettings; } } - #endregion - #region Line Settings - private SvgLineSettings _MyLineSettings = new SvgLineSettings(); - public SvgLineSettings MyLineSettings + #endregion + #region Line Settings + public SvgLineSettings MyLineSettings { get; set; } = new SvgLineSettings(); + public string Stroke { - get { return _MyLineSettings; } - set { _MyLineSettings = value; } - } - public string Stroke - { - get { return _MyLineSettings.Stroke; } - set { _MyLineSettings.Stroke = value; } + get { return MyLineSettings.Stroke; } + set { MyLineSettings.Stroke = value; } } public string StrokeWidth { - get { return _MyLineSettings.StrokeWidth; } - set { _MyLineSettings.StrokeWidth = value; } + get { return MyLineSettings.StrokeWidth; } + set { MyLineSettings.StrokeWidth = value; } } - #endregion - #region Fill Settings - private SvgFillSettings _MyFillSettings = new SvgFillSettings(); - internal SvgFillSettings MyFillSettings + #endregion + #region Fill Settings + internal SvgFillSettings MyFillSettings { get; set; } = new SvgFillSettings(); + public string Fill { - get { return _MyFillSettings; } - set { _MyFillSettings = value; } + get { return MyFillSettings.Fill; } + set { MyFillSettings.Fill = value; } } - public string Fill + #endregion + #region Font Settings + internal SvgFontSettings MyFontSettings { get; set; } = new SvgFontSettings(); + public string FontFamily { - get { return _MyFillSettings.Fill; } - set { _MyFillSettings.Fill = value; } - } - #endregion - #region Font Settings - private SvgFontSettings _MyFontSettings = new SvgFontSettings(); - internal SvgFontSettings MyFontSettings - { - get { return _MyFontSettings; } - set { _MyFontSettings = value; } - } - public string FontFamily - { - get { return _MyFontSettings.FontFamily; } - set { _MyFontSettings.FontFamily = value; } + get { return MyFontSettings.FontFamily; } + set { MyFontSettings.FontFamily = value; } } public string FontSize { - get { return _MyFontSettings.FontSize; } - set { _MyFontSettings.FontSize = value; } + get { return MyFontSettings.FontSize; } + set { MyFontSettings.FontSize = value; } } public string SVGFontStyle { - get { return _MyFontSettings.SVGFontStyle; } - set { _MyFontSettings.SVGFontStyle = value; } + get { return MyFontSettings.SVGFontStyle; } + set { MyFontSettings.SVGFontStyle = value; } } public string FontWeight { - get { return _MyFontSettings.FontWeight; } - set { _MyFontSettings.FontWeight = value; } + get { return MyFontSettings.FontWeight; } + set { MyFontSettings.FontWeight = value; } } public string TextDecoration { - get { return _MyFontSettings.TextDecoration; } - set { _MyFontSettings.TextDecoration = value; } + get { return MyFontSettings.TextDecoration; } + set { MyFontSettings.TextDecoration = value; } } #endregion } diff --git a/PROMS/Volian.Svg.Library/SvgLine.cs b/PROMS/Volian.Svg.Library/SvgLine.cs index c613d60a..63c28e19 100644 --- a/PROMS/Volian.Svg.Library/SvgLine.cs +++ b/PROMS/Volian.Svg.Library/SvgLine.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,146 +11,72 @@ namespace Volian.Svg.Library public SvgLine() { ;} public SvgLine(PointF location1, PointF location2, Color lineColor, float lineWidth) { - _X1.Value = location1.X; - _Y1.Value = location1.Y; - _X2.Value = location2.X; - _Y2.Value = location2.Y; + X1.Value = location1.X; + Y1.Value = location1.Y; + X2.Value = location2.X; + Y2.Value = location2.Y; LineColor = lineColor; LineWidth = new SvgMeasurement(lineWidth); } - //XMLElementAttribute(ElementName = "PREFIX", IsNullable = false) - #endregion - #region Location1 - private SvgMeasurement _X1 = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement X1 - { - get { return _X1; } - set { _X1 = value; } - } - [XmlAttribute("x1")] + #endregion + #region Location1 + [XmlIgnore] + public SvgMeasurement X1 { get; set; } = new SvgMeasurement(); + [XmlAttribute("x1")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X1_XmlSurrogate { - get { return SvgXmlConverter.GetString(_X1); } - set { _X1 = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(X1); } + set { X1 = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Y1 = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Y1 - { - get { return _Y1; } - set { _Y1 = value; } - } - [XmlAttribute("y1")] + + [XmlIgnore] + public SvgMeasurement Y1 { get; set; } = new SvgMeasurement(); + [XmlAttribute("y1")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Y1_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Y1); } - set { _Y1 = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Y1); } + set { Y1 = SvgXmlConverter.GetObject(value); } } - #endregion - #region Location2 - private SvgMeasurement _X2 = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement X2 - { - get { return _X2; } - set { _X2 = value; } - } - [XmlAttribute("x2")] + #endregion + #region Location2 + [XmlIgnore] + public SvgMeasurement X2 { get; set; } = new SvgMeasurement(); + [XmlAttribute("x2")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X2_XmlSurrogate { - get { return SvgXmlConverter.GetString(_X2); } - set { _X2 = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(X2); } + set { X2 = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Y2 = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Y2 - { - get { return _Y2; } - set { _Y2 = value; } - } - [XmlAttribute("y2")] + + [XmlIgnore] + public SvgMeasurement Y2 { get; set; } = new SvgMeasurement(); + [XmlAttribute("y2")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Y_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Y2); } - set { _Y2 = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Y2); } + set { Y2 = SvgXmlConverter.GetObject(value); } } - #endregion - #region Description - private string _Description = string.Empty; - [System.ComponentModel.DefaultValueAttribute("")] - [XmlElement("desc")] - public string Description - { - get { return _Description; } - set { _Description = value; } - } - #endregion - #region LineColor - //protected Color _LineColor = Color.Empty; - //[XmlIgnoreAttribute()] - //public Color LineColor - //{ - // get { return _LineWidth.Value == 0 ? Color.LightGray : _LineColor == Color.Empty ? Color.Gray : _LineColor; } - // set { _LineColor = value; } - //} - private Color AdjustColorForWidth(Color myColor, float myWidth) + #endregion + #region Description + [System.ComponentModel.DefaultValueAttribute("")] + [XmlElement("desc")] + public string Description { get; set; } = string.Empty; + #endregion + #region LineColor + private Color AdjustColorForWidth(Color myColor, float myWidth) { if (myWidth > 1F) return myColor; //Console.WriteLine("Line Width = {0}, Alpha = {1}", myWidth, Convert.ToInt32(myWidth * 255)); return Color.FromArgb(Convert.ToInt32(myWidth * 255), myColor); } - // Serializes the 'BackgroundColor' Color to XML. - //[System.ComponentModel.DefaultValueAttribute("none")] - //[XmlAttribute("stroke")] - //public string Stroke - //{ - // get { return _LineColor == Color.Empty ? "none" : _LineColor == Color.Black ? "" : ColorTranslator.ToHtml(_LineColor); } - // set { _LineColor = (value == "none" ? Color.Empty : (value == "" ? Color.Empty : ColorTranslator.FromHtml(value))); } - //} - #endregion - #region LineWidth - //private SvgMeasurement GetLineWidth() - //{ - // if (_LineWidth.Value == -1) return new SvgMeasurement(1F);// Minimum Strokewidth - // if (_LineWidth.Value == 0) return new SvgMeasurement(.01F);// Minimum Strokewidth - // if (_LineColor == Color.Empty) return new SvgMeasurement( .01F);// No Color - Minimum Strokewidth - // return _LineWidth; - //} - //private SvgMeasurement _LineWidth = new SvgMeasurement(); - //[XmlIgnore] - //public SvgMeasurement LineWidth - //{ - // get { return _LineWidth; } - // set { _LineWidth = value; } - //} - //[XmlAttribute("stroke-width")] - //[Browsable(false)] - //[EditorBrowsable(EditorBrowsableState.Never)] - //public string LineWidth_XmlSurrogate - //{ - // get - // { - // if (_LineWidth.Value == -1) - // return "none"; - // return VolianXmlConverter.GetString(_LineWidth); - // } - // set - // { - // if (value == "none") - // _LineWidth = VolianXmlConverter.GetObject("-1"); - // else - // _LineWidth = VolianXmlConverter.GetObject(value); - // } - //} #endregion } } diff --git a/PROMS/Volian.Svg.Library/SvgLinePart.cs b/PROMS/Volian.Svg.Library/SvgLinePart.cs index f0c859a7..e4e5004c 100644 --- a/PROMS/Volian.Svg.Library/SvgLinePart.cs +++ b/PROMS/Volian.Svg.Library/SvgLinePart.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; using System.Xml.Serialization; using System.ComponentModel; @@ -50,12 +47,9 @@ namespace Volian.Svg.Library get { return _MyLineSettings.OutlineWidth; } set { _MyLineSettings.OutlineWidth = value; } } - #endregion - #region Setup Inheritance - override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) - { - _MyLineSettings.MyParentsSettings = myParentsSettings.MyLineSettings; - } - #endregion - } + #endregion + #region Setup Inheritance + override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) => _MyLineSettings.MyParentsSettings = myParentsSettings.MyLineSettings; + #endregion + } } diff --git a/PROMS/Volian.Svg.Library/SvgLineSettings.cs b/PROMS/Volian.Svg.Library/SvgLineSettings.cs index b995d0d7..5bdd7066 100644 --- a/PROMS/Volian.Svg.Library/SvgLineSettings.cs +++ b/PROMS/Volian.Svg.Library/SvgLineSettings.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; -using System.ComponentModel; -using System.Xml.Serialization; namespace Volian.Svg.Library { @@ -13,34 +8,20 @@ namespace Volian.Svg.Library public SvgLineSettings() { ;} public SvgLineSettings(Color myColor, SvgMeasurement myWidth) { - _Stroke = ColorTranslator.ToHtml(myColor); - _StrokeWidth = myWidth.ToString(); + Stroke = ColorTranslator.ToHtml(myColor); + StrokeWidth = myWidth.ToString(); } - //public SvgLineSettings(string myStroke, string myStrokeWidth) - //{ - // _Stroke = myStroke; - // _StrokeWidth = myStrokeWidth; - //} - #endregion - #region Inheritance - private SvgLineSettings _MyParentsSettings = null; - public SvgLineSettings MyParentsSettings - { - get { return _MyParentsSettings; } - set - { - _MyParentsSettings = value; - } - } - #endregion - #region Internal Inherited Properties - protected string InheritedStroke + #endregion + #region Inheritance + public SvgLineSettings MyParentsSettings { get; set; } = null; + #endregion + #region Internal Inherited Properties + protected string InheritedStroke { get { - // Stroke = "", "0" - Default, otherwise the value - if (_Stroke != "" && _Stroke != "0") return _Stroke; // Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedStroke;// Inherited + if (Stroke != "" && Stroke != "0") return Stroke; // Current Value + if (MyParentsSettings != null) return MyParentsSettings.InheritedStroke;// Inherited return "None"; // Default } } @@ -49,68 +30,47 @@ namespace Volian.Svg.Library get { // StrokeWidth = "", "none" - Default, otherwise the value - if (_StrokeWidth != "" && _StrokeWidth != "none") return _StrokeWidth; // Current Value - if (_MyParentsSettings != null) return _MyParentsSettings.InheritedLineWidth; // Inherited + if (StrokeWidth != "" && StrokeWidth != "none") return StrokeWidth; // Current Value + if (MyParentsSettings != null) return MyParentsSettings.InheritedLineWidth; // Inherited return "1PX"; // Default } } - //protected string InheritedOutlineWidth - //{ - // get - // { - // // StrokeWidth = "", "none" - Default, otherwise the value - // if (_StrokeWidth != "" && _StrokeWidth.ToLower() != "none") return _StrokeWidth; // Current Value - // if (_MyParent != null) return _MyParent.InheritedLineWidth; // Inherited - // return "1PX"; // Default - // } - //} #endregion #region Inherited Values public SvgMeasurement LineWidth { get { - // Stroke = "None" - Light, otherwise the value - // StrokeWidth = "None" Light, otherwise the value string myStroke = InheritedStroke; string myWidth = InheritedLineWidth; - //if (myStroke.ToLower() == "none" || myWidth.ToLower() == "none") // Light - // return new SvgMeasurement(.001F, E_MeasurementUnits.PX); SvgMeasurement myMeasurement = new SvgMeasurement(myWidth); - //myMeasurement.Value *= _Scale; return myMeasurement; } set { - _StrokeWidth = value.ToString(); + StrokeWidth = value.ToString(); } } public SvgMeasurement OutlineWidth { get { - // Stroke = "None" - Eliminate, otherwise the value - // StrokeWidth = "0" Eliminate, otherwise the value string myStroke = InheritedStroke; - //string myWidth = InheritedOutlineWidth; string myWidth = InheritedLineWidth; if (myStroke.ToLower() == "none" || myWidth == "0") // Eliminate return new SvgMeasurement(0, E_MeasurementUnits.PX); SvgMeasurement myMeasurement = new SvgMeasurement(myWidth); - //myMeasurement.Value *= _Scale; return myMeasurement; } set { - _StrokeWidth = value.ToString(); + StrokeWidth = value.ToString(); } } public Color LineColor { get { - // Stroke = "None" - Eliminate, otherwise the value - // StrokeWidth = "None" Eliminate, otherwise the value string myStroke = InheritedStroke; string myWidth = InheritedLineWidth; if (myStroke.ToLower() == "none" || myWidth.ToLower() == "none" || myWidth == "0") // Light @@ -120,9 +80,9 @@ namespace Volian.Svg.Library set { if (value == Color.Empty) - _Stroke = "none"; + Stroke = "none"; else - _Stroke = ColorTranslator.ToHtml(value); + Stroke = ColorTranslator.ToHtml(value); } } @@ -130,10 +90,7 @@ namespace Volian.Svg.Library { get { - // Stroke = "None" - Eliminate, otherwise the value - // StrokeWidth = "0" Eliminate, otherwise the value string myStroke = InheritedStroke; - //string myWidth = InheritedOutlineWidth; string myWidth = InheritedLineWidth; if (myStroke.ToLower() == "none" || myWidth == "0") // Eliminate return Color.Empty; @@ -142,26 +99,16 @@ namespace Volian.Svg.Library set { if (value == Color.Empty) - _Stroke = "none"; + Stroke = "none"; else - _Stroke = ColorTranslator.ToHtml(value); + Stroke = ColorTranslator.ToHtml(value); } } - #endregion - #region Properties - private string _Stroke = string.Empty; // Default value is None - public string Stroke - { - get { return _Stroke; } - set { _Stroke = value; } - } - private string _StrokeWidth = string.Empty; // Default value is 1PX - public string StrokeWidth - { - get { return _StrokeWidth; } - set { _StrokeWidth = value; } - } - #endregion - } + #endregion + #region Properties + public string Stroke { get; set; } = string.Empty; + public string StrokeWidth { get; set; } = string.Empty; + #endregion + } } diff --git a/PROMS/Volian.Svg.Library/SvgMeasurement.cs b/PROMS/Volian.Svg.Library/SvgMeasurement.cs index e953cf6e..eabc42fd 100644 --- a/PROMS/Volian.Svg.Library/SvgMeasurement.cs +++ b/PROMS/Volian.Svg.Library/SvgMeasurement.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; using System.Text.RegularExpressions; namespace Volian.Svg.Library @@ -57,24 +53,24 @@ namespace Volian.Svg.Library public SvgMeasurement() { ;} public SvgMeasurement(int value) { - _Value = Convert.ToSingle(value); + Value = Convert.ToSingle(value); _Units = E_MeasurementUnits.PX; } public SvgMeasurement(float value) { - _Value = value; + Value = value; _Units = E_MeasurementUnits.PX; } public SvgMeasurement(float value, E_MeasurementUnits units) { - _Value = value; + Value = value; _Units = units; } public SvgMeasurement(string val) { val = val.Replace("{size}", "10");// B2020-145 BWD SAMG TSG-6 Fix for Base Format {size} parameter rather than font size MatchCollection mc = Regex.Matches(val.ToLower(), "([+-]?[.0-9]+)|(in|cm|mm|em|ex|pc|pt|px|percentage)"); - _Value = Convert.ToSingle(mc[0].Value); + Value = Convert.ToSingle(mc[0].Value); if (mc.Count == 2) { //Console.WriteLine("{0} - '{1}'", val, mc[1].Value.ToUpper()); @@ -93,108 +89,55 @@ namespace Volian.Svg.Library { float tmp = GetSizeInPoints(DPI); _Units = value; - _Value *= (tmp / GetSizeInPoints(DPI)); + Value *= (tmp / GetSizeInPoints(DPI)); } } - private float _Value; - public float Value - { - get { return _Value; } - set { _Value = value; } - } - #endregion - #region ToString - public override string ToString() + + public float Value { get; set; } + #endregion + #region ToString + public override string ToString() { switch (_Units) { case E_MeasurementUnits.PX: // Default - return string.Format("{0}", _Value); + return string.Format("{0}", Value); case E_MeasurementUnits.PERCENTAGE: // Precentage is preceded by a space - return string.Format("{0} {1}", _Value, _Units); + return string.Format("{0} {1}", Value, _Units); } - return string.Format("{0}{1}", _Value, _Units); + return string.Format("{0}{1}", Value, _Units); } #endregion - //public float SizeInPixels - //{ - // get - // { - // switch (_Units) - // { - // case E_MeasurementUnits.PT: //Points - 72 per inch - // return _Value * DPI / 72F; - // case E_MeasurementUnits.PC: //Picas - 6 per inch - // return _Value * DPI / 6F; - // case E_MeasurementUnits.IN: //inches - // return _Value * DPI; - // case E_MeasurementUnits.CM: // Centimeter - // return _Value * DPI / 2.54F; - // case E_MeasurementUnits.MM: // Millimeter - // return _Value * DPI / 25.4F; - // case E_MeasurementUnits.EM: // EMs - // return _Value * DPI / 8; - // case E_MeasurementUnits.EX: // EXs - // return _Value * DPI / 16; - // default: - // return _Value; - // } - // } - //} public float GetSizeInPoints(float myDPI) { switch (_Units) { case E_MeasurementUnits.PX: //Pixels myDPI per inch - return _Value * 72F / myDPI; + return Value * 72F / myDPI; case E_MeasurementUnits.PC: //Picas - 6 per inch - return _Value * 72F / 6F; + return Value * 72F / 6F; case E_MeasurementUnits.IN: //inches - return _Value * 72F; + return Value * 72F; case E_MeasurementUnits.CM: // Centimeter - return _Value * 72F / 2.54F; + return Value * 72F / 2.54F; case E_MeasurementUnits.MM: // Millimeter - return _Value * 72F / 25.4F; + return Value * 72F / 25.4F; case E_MeasurementUnits.EM: // EMs - return _Value * 72F / 8; + return Value * 72F / 8; case E_MeasurementUnits.EX: // EXs - return _Value * 72F / 16; + return Value * 72F / 16; default: // Points - return _Value; + return Value; } } - //public float SizeInPoints - //{ get { return SizeInPixels * 72 / DPI; } } - //public float SizeInInches - //{ get { return SizeInPixels / DPI; } } - //public float SizeInCentimeters - //{ get { return SizeInPixels * 2.54F / DPI; } } - //public float SizeInMillimeters - //{ get { return SizeInPixels * 25.4F / DPI; } } - //public float SizeInEms - //{ get { return SizeInPixels * 5 / (6 * DPI); } } - //public float SizeInExs - //{ get { return SizeInPixels * 5 / (6 * DPI); } } - //public float SizeInPicas - //{ get { return SizeInPixels * 6 / DPI; } } - //public Unit SizeInUnits - //{ get { return new Unit((double)SizeInPoints, UnitTypeEnum.Point); } } - public float GetSizeInPixels(float myDPI) - { return GetSizeInPoints(myDPI) * myDPI / 72F;} - public float GetSizeInInches(float myDPI) - { return GetSizeInPoints(myDPI) / 72F; } - public float GetSizeInCentimeters(float myDPI) - { return GetSizeInPoints(myDPI) * 2.54F / 72F; } - public float GetSizeInMillimeters(float myDPI) - { return GetSizeInPoints(myDPI) * 25.4F / 72F; } - public float GetSizeInEms(float myDPI) - { return GetSizeInPoints(myDPI) * 5 / (6 * 72F); } - public float GetSizeInExs(float myDPI) - { return GetSizeInPoints(myDPI) * 5 / (6 * 72F); } - public float GetSizeInPicas(float myDPI) - { return GetSizeInPoints(myDPI) * 6 / 72F; } - //public Unit GetSizeInUnits(float myDPI) - //{ return new Unit((double)GetSizeInPoints(myDPI), UnitTypeEnum.Point); } + public float GetSizeInPixels(float myDPI) => GetSizeInPoints(myDPI) * myDPI / 72F; + public float GetSizeInInches(float myDPI) => GetSizeInPoints(myDPI) / 72F; + public float GetSizeInCentimeters(float myDPI) => GetSizeInPoints(myDPI) * 2.54F / 72F; + public float GetSizeInMillimeters(float myDPI) => GetSizeInPoints(myDPI) * 25.4F / 72F; + public float GetSizeInEms(float myDPI) => GetSizeInPoints(myDPI) * 5 / (6 * 72F); + public float GetSizeInExs(float myDPI) => GetSizeInPoints(myDPI) * 5 / (6 * 72F); + public float GetSizeInPicas(float myDPI) => GetSizeInPoints(myDPI) * 6 / 72F; + public static float StringToPoints(string value) { SvgMeasurement tmp = new SvgMeasurement(value); @@ -226,26 +169,9 @@ namespace Volian.Svg.Library } public class MeasurementTypeConverter : ExpandableObjectConverter { - public override bool CanConvertTo(ITypeDescriptorContext context, Type t) - { - return t == typeof(String); - } - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) - { - if (destType == typeof(string) && value is SvgMeasurement) - { - return value.ToString(); - } - return base.ConvertTo(context, culture, value, destType); - } - public override bool CanConvertFrom(ITypeDescriptorContext context, Type t) - { - return t == typeof(String); - } - public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object val) - { - SvgMeasurement measurement = new SvgMeasurement((string)val); - return measurement; - } - } + public override bool CanConvertTo(ITypeDescriptorContext context, Type t) => t == typeof(String); + public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) => destType == typeof(string) && value is SvgMeasurement ? value.ToString() : base.ConvertTo(context, culture, value, destType); + public override bool CanConvertFrom(ITypeDescriptorContext context, Type t) => t == typeof(String); + public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object val) => new SvgMeasurement((string)val); + } } diff --git a/PROMS/Volian.Svg.Library/SvgPart.cs b/PROMS/Volian.Svg.Library/SvgPart.cs index 2f509335..af7068ef 100644 --- a/PROMS/Volian.Svg.Library/SvgPart.cs +++ b/PROMS/Volian.Svg.Library/SvgPart.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; using System.Xml.Serialization; -using System.Drawing; using System.ComponentModel; using System.Collections.Generic; @@ -21,28 +18,6 @@ namespace Volian.Svg.Library set { _ID = value; } } #endregion - //#region Parent and Containing Svg - //// ToDo: MyParent - //private SvgPartGrouping _MyParent; - //[XmlIgnore()] - //public SvgPartGrouping MyParent - //{ - // get { return _MyParent; } - // set { _MyParent = value; } - //} - //// ToDo: MySvg - //private Svg _MySvg; - //public Svg MySvg - //{ - // get { return _MySvg; } - // set { _MySvg = value; } - //} - //internal void SetParent(SvgPartGrouping myParent) - //{ - // _MyParent = myParent; - // _MySvg = myParent.MySvg == null? MyParent : myParent.MySvg; - //} - //#endregion #region Setup Inheritance virtual internal void SetupInheritance(SvgInheritedSettings myParentsSettings) { ; } #endregion diff --git a/PROMS/Volian.Svg.Library/SvgPartInheritance.cs b/PROMS/Volian.Svg.Library/SvgPartInheritance.cs index aaf48f24..ee41f0df 100644 --- a/PROMS/Volian.Svg.Library/SvgPartInheritance.cs +++ b/PROMS/Volian.Svg.Library/SvgPartInheritance.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; -using System.ComponentModel; -using System.Drawing; namespace Volian.Svg.Library { @@ -78,14 +73,10 @@ namespace Volian.Svg.Library get { return _MyInheritedSettings.TextDecoration; } set { _MyInheritedSettings.TextDecoration = value; } } - #endregion - #endregion - #region Setup Inheritance - override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) - { - _MyInheritedSettings.MyParentsSettings = myParentsSettings; - //_SvgParts.SetupInheritance(_MyInheritedSettings); - } - #endregion - } + #endregion + #endregion + #region Setup Inheritance + override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) => _MyInheritedSettings.MyParentsSettings = myParentsSettings; + #endregion + } } diff --git a/PROMS/Volian.Svg.Library/SvgParts.cs b/PROMS/Volian.Svg.Library/SvgParts.cs index 18cbb24f..7091dc46 100644 --- a/PROMS/Volian.Svg.Library/SvgParts.cs +++ b/PROMS/Volian.Svg.Library/SvgParts.cs @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Drawing; using System.ComponentModel; using System.Text; @@ -38,52 +37,39 @@ namespace Volian.Svg.Library { } - /// - /// - /// Initializes a new instance of based on another . - /// - /// - /// - /// A from which the contents are copied - /// - public SvgParts(SvgParts value) - { - this.AddRange(value); - } + /// + /// + /// Initializes a new instance of based on another . + /// + /// + /// + /// A from which the contents are copied + /// + public SvgParts(SvgParts value) => this.AddRange(value); - /// - /// - /// Initializes a new instance of containing any array of objects. - /// - /// - /// - /// A array of objects with which to intialize the collection - /// - public SvgParts(SvgPart[] value) - { - this.AddRange(value); - } + /// + /// + /// Initializes a new instance of containing any array of objects. + /// + /// + /// + /// A array of objects with which to intialize the collection + /// + public SvgParts(SvgPart[] value) => this.AddRange(value); - /// - /// Represents the entry at the specified index of the . - /// - /// The zero-based index of the entry to locate in the collection. - /// - /// The entry at the specified index of the collection. - /// - /// is outside the valid range of indexes for the collection. - public SvgPart this[int index] + /// + /// Represents the entry at the specified index of the . + /// + /// The zero-based index of the entry to locate in the collection. + /// + /// The entry at the specified index of the collection. + /// + /// is outside the valid range of indexes for the collection. + public SvgPart this[int index] { get { return ((SvgPart)(List[index])); } set { List[index] = value; } } - //#region SetupInheritance - //internal void SetupInheritance(SvgInheritedSettings myParentsSettings) - //{ - // foreach (SvgPart svgPart in List) - // svgPart.SetupInheritance(myParentsSettings); - //} - //#endregion #region Dictionary of Parts internal void AddLookup(Dictionary lookUp) { @@ -194,29 +180,26 @@ namespace Volian.Svg.Library List.CopyTo(array, index); } - /// - /// Returns the index of a in - /// the . - /// - /// The to locate. - /// - /// The index of the of in the - /// , if found; otherwise, -1. - /// - /// - public int IndexOf(SvgPart value) - { - return List.IndexOf(value); - } + /// + /// Returns the index of a in + /// the . + /// + /// The to locate. + /// + /// The index of the of in the + /// , if found; otherwise, -1. + /// + /// + public int IndexOf(SvgPart value) => List.IndexOf(value); - /// - /// Inserts a into the at the specified index. - /// - /// The zero-based index where should be inserted. - /// The to insert. - /// None. - /// - public void Insert(int index, SvgPart value) + /// + /// Inserts a into the at the specified index. + /// + /// The zero-based index where should be inserted. + /// The to insert. + /// None. + /// + public void Insert(int index, SvgPart value) { List.Insert(index, value); if (OnItemAdd != null) { OnItemAdd(this, new SVGPartArgs(value)); } @@ -288,45 +271,25 @@ namespace Volian.Svg.Library /// Event arguments for the SVGParts collection class. public class SVGPartArgs : EventArgs { - private SvgParts t; - /// Default constructor. - public SVGPartArgs() - { - t = new SvgParts(); - } + /// Default constructor. + public SVGPartArgs() => SVGParts = new SvgParts(); - /// Initializes with a SVGPart. - /// Data object. - public SVGPartArgs(SvgPart t) - : this() - { - this.t.Add(t); - } + /// Initializes with a SVGPart. + /// Data object. + public SVGPartArgs(SvgPart t) : this() => this.SVGParts.Add(t); - /// Initializes with a collection of SVGPart objects. - /// Collection of data. - public SVGPartArgs(SvgParts ts) - : this() - { - this.t.AddRange(ts); - } + /// Initializes with a collection of SVGPart objects. + /// Collection of data. + public SVGPartArgs(SvgParts ts) : this() => this.SVGParts.AddRange(ts); - /// Initializes with an array of SVGPart objects. - /// Array of data. - public SVGPartArgs(SvgPart[] ts) - : this() - { - this.t.AddRange(ts); - } + /// Initializes with an array of SVGPart objects. + /// Array of data. + public SVGPartArgs(SvgPart[] ts) : this() => this.SVGParts.AddRange(ts); - /// Gets or sets the data of this argument. - public SvgParts SVGParts - { - get { return t; } - set { t = value; } - } - } + /// Gets or sets the data of this argument. + public SvgParts SVGParts { get; set; } + } /// SVGParts event handler. public delegate void SVGPartHandler(object sender, SVGPartArgs e); @@ -338,43 +301,29 @@ namespace Volian.Svg.Library { private SvgPart Item { get { return (SvgPart)_Item; } } public SvgPartsPropertyDescriptor(SvgParts collection, int index) : base(collection, index) { ;} - public override string DisplayName - { get { return Item.GetType().Name; } } - } + public override string DisplayName => Item.GetType().Name; + } #endregion [Serializable()] public partial class vlnListPropertyDescriptor : PropertyDescriptor { protected object _Item = null; - public vlnListPropertyDescriptor(System.Collections.IList collection, int index) - : base("#" + index.ToString(), null) - { _Item = collection[index]; } - public override bool CanResetValue(object component) - { return true; } - public override Type ComponentType - { get { return _Item.GetType(); } } - public override object GetValue(object component) - { return _Item; } - public override bool IsReadOnly - { get { return false; } } - public override Type PropertyType - { get { return _Item.GetType(); } } - public override void ResetValue(object component) + public vlnListPropertyDescriptor(System.Collections.IList collection, int index) + : base($"#{index}", null) => _Item = collection[index]; + public override bool CanResetValue(object component) => true; + public override Type ComponentType => _Item.GetType(); + public override object GetValue(object component) => _Item; + public override bool IsReadOnly => false; + public override Type PropertyType => _Item.GetType(); + public override void ResetValue(object component) { ;} - public override bool ShouldSerializeValue(object component) - { return true; } - public override void SetValue(object component, object value) - { /*_Item = value*/;} - //public override AttributeCollection Attributes - //{ get { return new AttributeCollection(null); } } - public override string DisplayName - { get { return _Item.ToString(); } } - public override string Description - { get { return _Item.ToString(); } } - public override string Name - { get { return _Item.ToString(); } } + public override bool ShouldSerializeValue(object component) => true; + public override void SetValue(object component, object value) { /*_Item = value*/; } + public override string DisplayName => _Item.ToString(); + public override string Description => _Item.ToString(); + public override string Name => _Item.ToString(); - } // Class + } // Class #region Converter internal class SVGPartsConverter : ExpandableObjectConverter { @@ -383,7 +332,7 @@ namespace Volian.Svg.Library if (destType == typeof(string) && value is SvgParts) { // Return department and department role separated by comma. - return ((SvgParts)value).List.Count.ToString() + " SVG Drawing Parts"; + return $"{((SvgParts)value).List.Count} SVG Drawing Parts"; } return base.ConvertTo(context, culture, value, destType); } diff --git a/PROMS/Volian.Svg.Library/SvgRectangle.cs b/PROMS/Volian.Svg.Library/SvgRectangle.cs index 2e34ed35..56dca848 100644 --- a/PROMS/Volian.Svg.Library/SvgRectangle.cs +++ b/PROMS/Volian.Svg.Library/SvgRectangle.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,88 +10,64 @@ namespace Volian.Svg.Library public SvgRectangle() { ;} public SvgRectangle(PointF location, SizeF size, Color fillColor, Color lineColor, float lineWidth) { - _X.Value = location.X; - _Y.Value = location.Y; - _Width.Value = size.Width; - _Height.Value = size.Height; + X.Value = location.X; + Y.Value = location.Y; + Width.Value = size.Width; + Height.Value = size.Height; FillColor = fillColor; LineColor = lineColor; LineWidth = new SvgMeasurement(lineWidth); } - //XMLElementAttribute(ElementName = "PREFIX", IsNullable = false) - #endregion - #region Description - private string _Description = string.Empty; - [System.ComponentModel.DefaultValueAttribute("")] - [XmlElement("desc")] - public string Description - { - get { return _Description; } - set { _Description = value; } - } - #endregion - #region Location - private SvgMeasurement _X = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement X - { - get { return _X; } - set { _X = value; } - } - [XmlAttribute("x")] + #endregion + #region Description + [System.ComponentModel.DefaultValueAttribute("")] + [XmlElement("desc")] + public string Description { get; set; } = string.Empty; + #endregion + #region Location + [XmlIgnore] + public SvgMeasurement X { get; set; } = new SvgMeasurement(); + [XmlAttribute("x")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X_XmlSurrogate { - get { return SvgXmlConverter.GetString(_X); } - set { _X = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(X); } + set { X = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Y = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Y - { - get { return _Y; } - set { _Y = value; } - } - [XmlAttribute("y")] + + [XmlIgnore] + public SvgMeasurement Y { get; set; } = new SvgMeasurement(); + [XmlAttribute("y")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Y_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Y); } - set { _Y = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Y); } + set { Y = SvgXmlConverter.GetObject(value); } } - #endregion - #region Size - private SvgMeasurement _Width = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Width - { - get { return _Width; } - set { _Width = value; } - } - [XmlAttribute("width")] + #endregion + #region Size + [XmlIgnore] + public SvgMeasurement Width { get; set; } = new SvgMeasurement(); + [XmlAttribute("width")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Width_WidthmlSurrogate { - get { return SvgXmlConverter.GetString(_Width); } - set { _Width = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Width); } + set { Width = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Height = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Height - { - get { return _Height; } - set { _Height = value; } - } - [XmlAttribute("height")] + + [XmlIgnore] + public SvgMeasurement Height { get; set; } = new SvgMeasurement(); + [XmlAttribute("height")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Height_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Height); } - set { _Height = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Height); } + set { Height = SvgXmlConverter.GetObject(value); } } #endregion } diff --git a/PROMS/Volian.Svg.Library/SvgScale.cs b/PROMS/Volian.Svg.Library/SvgScale.cs index 94c523b0..ad8a92c5 100644 --- a/PROMS/Volian.Svg.Library/SvgScale.cs +++ b/PROMS/Volian.Svg.Library/SvgScale.cs @@ -1,48 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; namespace Volian.Svg.Library { public class SvgScale { - private float _XLowerLimit; - public float XLowerLimit - { - get { return _XLowerLimit; } - set { _XLowerLimit = value; } - } - private float _YLowerLimit; - public float YLowerLimit - { - get { return _YLowerLimit; } - set { _YLowerLimit = value; } - } - private float _Scale; // Scale from Logical to Physical - public float Scale - { get { return _Scale; } } - private float _Width; // Physical Width - public float Width - { get { return _Width; } } - private float _Height; // Physical Height - public float Height - { get { return _Height; } } - public float XUpperLimit - { get { return _Width * _Scale + _XLowerLimit; } } - public float YUpperLimit - { get { return _Height * _Scale + _YLowerLimit; } } - private float _DPI; - public float DPI - { get { return _DPI; } } - private SvgScale(SvgScale tmp,SvgMeasurement newX, SvgMeasurement newY) + public float XLowerLimit { get; set; } + public float YLowerLimit { get; set; } + private float _Scale; // Scale from Logical to Physical + public float Scale => _Scale; + private float _Width; // Physical Width + public float Width => _Width; + private float _Height; // Physical Height + public float Height => _Height; + public float XUpperLimit => _Width * _Scale + XLowerLimit; + public float YUpperLimit => _Height * _Scale + YLowerLimit; + private float _DPI; + public float DPI => _DPI; + private SvgScale(SvgScale tmp,SvgMeasurement newX, SvgMeasurement newY) { _DPI = tmp.DPI; _Scale = tmp.Scale; _Width = tmp.Width; _Height = tmp.Height; - _XLowerLimit = tmp.XLowerLimit - newX.GetSizeInPixels(DPI); - _YLowerLimit = tmp.YLowerLimit - newY.GetSizeInPixels(DPI); + XLowerLimit = tmp.XLowerLimit - newX.GetSizeInPixels(DPI); + YLowerLimit = tmp.YLowerLimit - newY.GetSizeInPixels(DPI); } public SvgScale(float myDPI, RectangleF bounds,SvgMeasurement width, SvgMeasurement height, SvgViewBox myViewBox) { @@ -62,28 +43,16 @@ namespace Volian.Svg.Library //Console.WriteLine("'Scale',{0}",_Scale); _Width = outputWidth / _Scale; _Height = outputHeight / _Scale; - _XLowerLimit = myViewBox.X + (inputWidth - _Width) / 2; - _YLowerLimit = myViewBox.Y + (inputHeight - _Height) / 2; + XLowerLimit = myViewBox.X + (inputWidth - _Width) / 2; + YLowerLimit = myViewBox.Y + (inputHeight - _Height) / 2; //if (myDPI != 96) Console.WriteLine("DPI {0}", myDPI); //Console.WriteLine("Scale,{0},{1},{2},{3},{4},{5},{6}", Scale, Width, Height, XLowerLimit, XUpperLimit, YLowerLimit, YUpperLimit); } - public SvgScale AdjustOrigin(SvgMeasurement newX, SvgMeasurement newY) - { - return new SvgScale(this, newX, newY); - } - public float X(float x) - { - return _Scale * (x - XLowerLimit); - } - public float Y(float y) - { - return _Scale * (y - YLowerLimit); - } - public float AbsX(SvgMeasurement x) - { - return x.GetSizeInPixels(DPI) + Svg.AbsoluteOffset.X; - } - public float AbsY(iTextSharp.text.pdf.PdfContentByte cb, SvgMeasurement y) + public SvgScale AdjustOrigin(SvgMeasurement newX, SvgMeasurement newY) => new SvgScale(this, newX, newY); + public float X(float x) => _Scale * (x - XLowerLimit); + public float Y(float y) => _Scale * (y - YLowerLimit); + public float AbsX(SvgMeasurement x) => x.GetSizeInPixels(DPI) + Svg.AbsoluteOffset.X; + public float AbsY(iTextSharp.text.pdf.PdfContentByte cb, SvgMeasurement y) { // the following line of code is 'taken' from the 16bit code: \promsnt\exe\wined\togdi.cpp // whenever doing an 'Absolute' macro. @@ -91,36 +60,21 @@ namespace Volian.Svg.Library yOffset = yOffset / 20; // convert from twips to points (point = 1/72 inch) return cb.PdfDocument.PageSize.Height - y.GetSizeInPixels(DPI) + yOffset + Svg.AbsoluteOffset.Y; } - public float Y(iTextSharp.text.pdf.PdfContentByte cb, float y) - { - return cb.PdfDocument.PageSize.Height - _Scale * (y - YLowerLimit); - } - public float M(float m) - { - return _Scale * m; - } - public float X(SvgMeasurement x) + public float Y(iTextSharp.text.pdf.PdfContentByte cb, float y) => cb.PdfDocument.PageSize.Height - _Scale * (y - YLowerLimit); + public float M(float m) => _Scale * m; + public float X(SvgMeasurement x) { float retval = _Scale * (x.GetSizeInPixels(DPI) - XLowerLimit); return retval; } - public float Y(SvgMeasurement y) - { - return _Scale * (y.GetSizeInPixels(DPI) - YLowerLimit); - } - public float Y(iTextSharp.text.pdf.PdfContentByte cb, SvgMeasurement y) + public float Y(SvgMeasurement y) => _Scale * (y.GetSizeInPixels(DPI) - YLowerLimit); + public float Y(iTextSharp.text.pdf.PdfContentByte cb, SvgMeasurement y) { float yOffset = 0; // = (cb.PdfWriter.CurrentPageNumber -1) * .8F * cb.PdfDocument.PageSize.Height; float myY = yOffset + cb.PdfDocument.PageSize.Height - _Scale * (y.GetSizeInPixels(DPI) - YLowerLimit); return myY; } - public float YY(SvgMeasurement y) - { - return -_Scale * y.GetSizeInPixels(DPI); - } - public float M(SvgMeasurement m) - { - return _Scale * m.GetSizeInPixels(DPI); - } - } + public float YY(SvgMeasurement y) => -_Scale * y.GetSizeInPixels(DPI); + public float M(SvgMeasurement m) => _Scale * m.GetSizeInPixels(DPI); + } } diff --git a/PROMS/Volian.Svg.Library/SvgSerializer.cs b/PROMS/Volian.Svg.Library/SvgSerializer.cs index c04a7754..13b4d915 100644 --- a/PROMS/Volian.Svg.Library/SvgSerializer.cs +++ b/PROMS/Volian.Svg.Library/SvgSerializer.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Xml; @@ -60,11 +59,9 @@ namespace Volian.Svg.Library } public class NonXsiTextWriter : XmlTextWriter { - public NonXsiTextWriter( TextWriter w ) : base( w ) {} - public NonXsiTextWriter( Stream w, Encoding encoding ) : base( w, encoding ) { - this.Formatting = Formatting.Indented; - } - public NonXsiTextWriter( string filename, Encoding encoding ) : base( filename, encoding ) {} + public NonXsiTextWriter( TextWriter w ) : base( w ) {} + public NonXsiTextWriter(Stream w, Encoding encoding) : base(w, encoding) => this.Formatting = Formatting.Indented; + public NonXsiTextWriter( string filename, Encoding encoding ) : base( filename, encoding ) {} bool _skip = false; public override void WriteStartAttribute( string prefix, string localName, string ns ) { diff --git a/PROMS/Volian.Svg.Library/SvgShapePart.cs b/PROMS/Volian.Svg.Library/SvgShapePart.cs index c1429167..82d47084 100644 --- a/PROMS/Volian.Svg.Library/SvgShapePart.cs +++ b/PROMS/Volian.Svg.Library/SvgShapePart.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using System.Xml.Serialization; using System.Drawing; using System.ComponentModel; diff --git a/PROMS/Volian.Svg.Library/SvgTest.cs b/PROMS/Volian.Svg.Library/SvgTest.cs index a0eaaab2..4017e45a 100644 --- a/PROMS/Volian.Svg.Library/SvgTest.cs +++ b/PROMS/Volian.Svg.Library/SvgTest.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.Drawing; diff --git a/PROMS/Volian.Svg.Library/SvgText.cs b/PROMS/Volian.Svg.Library/SvgText.cs index 41988c87..1f07473b 100644 --- a/PROMS/Volian.Svg.Library/SvgText.cs +++ b/PROMS/Volian.Svg.Library/SvgText.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; -using System.Drawing.Drawing2D; using System.Xml.Serialization; using System.ComponentModel; @@ -14,52 +10,38 @@ namespace Volian.Svg.Library public SvgText() { ;} public SvgText(PointF location, string text, Font font, Color fillColor) { - _X.Value = location.X; - _Y.Value = location.Y; + X.Value = location.X; + Y.Value = location.Y; Text = text; Font = font; FillColor = fillColor; LineColor = Color.Empty; LineWidth = new SvgMeasurement(0); } - #endregion - #region Location - private SvgJustify _Justify = SvgJustify.Left; - [XmlAttribute("Justify")] - public SvgJustify Justify - { - get { return _Justify; } - set { _Justify = value; } - } - private SvgMeasurement _X = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement X - { - get { return _X; } - set { _X = value; } - } - [XmlAttribute("x")] + #endregion + #region Location + [XmlAttribute("Justify")] + public SvgJustify Justify { get; set; } = SvgJustify.Left; + [XmlIgnore] + public SvgMeasurement X { get; set; } = new SvgMeasurement(); + [XmlAttribute("x")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X_XmlSurrogate { - get { return SvgXmlConverter.GetString(_X); } - set { _X = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(X); } + set { X = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Y = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Y - { - get { return _Y; } - set { _Y = value; } - } - [XmlAttribute("y")] + + [XmlIgnore] + public SvgMeasurement Y { get; set; } = new SvgMeasurement(); + [XmlAttribute("y")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Y_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Y); } - set { _Y = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Y); } + set { Y = SvgXmlConverter.GetObject(value); } } #endregion #region Text @@ -124,19 +106,14 @@ namespace Volian.Svg.Library get { return _MyFontSettings.TextDecoration; } set { _MyFontSettings.TextDecoration = value; } } - #endregion - #region Description - private string _Description = string.Empty; - [System.ComponentModel.DefaultValueAttribute("")] - [XmlElement("desc")] - public string Description - { - get { return _Description; } - set { _Description = value; } - } - #endregion - #region Setup Inheritance - override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) + #endregion + #region Description + [System.ComponentModel.DefaultValueAttribute("")] + [XmlElement("desc")] + public string Description { get; set; } = string.Empty; + #endregion + #region Setup Inheritance + override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) { base.SetupInheritance(myParentsSettings); _MyFontSettings.MyParentsSettings = myParentsSettings.MyFontSettings; diff --git a/PROMS/Volian.Svg.Library/SvgUse.cs b/PROMS/Volian.Svg.Library/SvgUse.cs index 26054bef..0425cb1b 100644 --- a/PROMS/Volian.Svg.Library/SvgUse.cs +++ b/PROMS/Volian.Svg.Library/SvgUse.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.ComponentModel; using System.Drawing; @@ -13,95 +10,66 @@ namespace Volian.Svg.Library public SvgUse() { ;} public SvgUse(PointF location, SizeF size, string id) { - _X.Value = location.X; - _Y.Value = location.Y; - _Width.Value = size.Width; - _Height.Value = size.Height; + X.Value = location.X; + Y.Value = location.Y; + Width.Value = size.Width; + Height.Value = size.Height; _ID = id; } - #endregion - #region Location - private SvgMeasurement _X = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement X - { - get { return _X; } - set { _X = value; } - } - [XmlAttribute("x")] + #endregion + #region Location + [XmlIgnore] + public SvgMeasurement X { get; set; } = new SvgMeasurement(); + [XmlAttribute("x")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string X_XmlSurrogate { - get { return SvgXmlConverter.GetString(_X); } - set { _X = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(X); } + set { X = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Y = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Y - { - get { return _Y; } - set { _Y = value; } - } - [XmlAttribute("y")] + + [XmlIgnore] + public SvgMeasurement Y { get; set; } = new SvgMeasurement(); + [XmlAttribute("y")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Y_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Y); } - set { _Y = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Y); } + set { Y = SvgXmlConverter.GetObject(value); } } - #endregion - #region Size - private SvgMeasurement _Width = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Width - { - get { return _Width; } - set { _Width = value; } - } - [XmlAttribute("width")] + #endregion + #region Size + [XmlIgnore] + public SvgMeasurement Width { get; set; } = new SvgMeasurement(); + [XmlAttribute("width")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Width_WidthmlSurrogate { - get { return SvgXmlConverter.GetString(_Width); } - set { _Width = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Width); } + set { Width = SvgXmlConverter.GetObject(value); } } - private SvgMeasurement _Height = new SvgMeasurement(); - [XmlIgnore] - public SvgMeasurement Height - { - get { return _Height; } - set { _Height = value; } - } - [XmlAttribute("height")] + + [XmlIgnore] + public SvgMeasurement Height { get; set; } = new SvgMeasurement(); + [XmlAttribute("height")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string Height_XmlSurrogate { - get { return SvgXmlConverter.GetString(_Height); } - set { _Height = SvgXmlConverter.GetObject(value); } + get { return SvgXmlConverter.GetString(Height); } + set { Height = SvgXmlConverter.GetObject(value); } } - #endregion - #region ID to be used - private string _UseID = null; - [XmlAttribute(AttributeName = "href", Namespace = "http://www.w3.org/1999/xlink")] - public string UseID - { - get { return _UseID; } - set { _UseID = value; } - } - #endregion - #region Setup Inheritance - override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) - { - _MyInheritedSettings.MyParentsSettings = myParentsSettings; - } - #endregion - public override string ToString() - { - return string.Format("({0}, {1}) Template '{2}'", this.X, this.Y, this.UseID); - } - } + #endregion + #region ID to be used + [XmlAttribute(AttributeName = "href", Namespace = "http://www.w3.org/1999/xlink")] + public string UseID { get; set; } = null; + #endregion + #region Setup Inheritance + override internal void SetupInheritance(SvgInheritedSettings myParentsSettings) => _MyInheritedSettings.MyParentsSettings = myParentsSettings; + #endregion + public override string ToString() => string.Format("({0}, {1}) Template '{2}'", this.X, this.Y, this.UseID); + } } diff --git a/PROMS/Volian.Svg.Library/SvgViewBox.cs b/PROMS/Volian.Svg.Library/SvgViewBox.cs index 1098d550..7dedc2f3 100644 --- a/PROMS/Volian.Svg.Library/SvgViewBox.cs +++ b/PROMS/Volian.Svg.Library/SvgViewBox.cs @@ -1,8 +1,6 @@ - using System; - using System.Collections.Generic; - using System.Text; - using System.Drawing; - using System.ComponentModel; +using System; +using System.Drawing; +using System.ComponentModel; namespace Volian.Svg.Library { @@ -11,11 +9,8 @@ namespace Volian.Svg.Library { #region ctor public SvgViewBox() { ;} - public SvgViewBox(float x, float y, float width, float height) - { - _MyRectangleF = new RectangleF(x, y, width, height); - } - public SvgViewBox(string val) + public SvgViewBox(float x, float y, float width, float height) => _MyRectangleF = new RectangleF(x, y, width, height); + public SvgViewBox(string val) { string[] parms = ((string)val).Split(' '); _MyRectangleF = new RectangleF(Convert.ToSingle(parms[0]), Convert.ToSingle(parms[1]), Convert.ToSingle(parms[2]), Convert.ToSingle(parms[3])); @@ -43,33 +38,17 @@ namespace Volian.Svg.Library get { return _MyRectangleF.Height; } set { _MyRectangleF.Height = value; } } - #endregion - #region ToString - public override string ToString() - { - return string.Format("{0} {1} {2} {3}", X, Y, Width, Height); - } - #endregion - } + #endregion + #region ToString + public override string ToString() => string.Format("{0} {1} {2} {3}", X, Y, Width, Height); + #endregion + } public class ViewBoxTypeConverter : ExpandableObjectConverter { - public override bool CanConvertTo(ITypeDescriptorContext context, Type t) - { - return t == typeof(String); - } - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) - { - if (destType == typeof(string) && value is SvgViewBox) - { - return value.ToString(); - } - return base.ConvertTo(context, culture, value, destType); - } - public override bool CanConvertFrom(ITypeDescriptorContext context, Type t) - { - return t == typeof(String); - } - public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object val) + public override bool CanConvertTo(ITypeDescriptorContext context, Type t) => t == typeof(string); + public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) => destType == typeof(string) && value is SvgViewBox ? value.ToString() : base.ConvertTo(context, culture, value, destType); + public override bool CanConvertFrom(ITypeDescriptorContext context, Type t) => t == typeof(string); + public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object val) { string[] parms = ((string)val).Split(' '); SvgViewBox viewBox = new SvgViewBox(Convert.ToSingle(parms[0]), Convert.ToSingle(parms[1]), Convert.ToSingle(parms[2]), Convert.ToSingle(parms[3])); diff --git a/PROMS/Volian.Svg.Library/SvgXMLConverter.cs b/PROMS/Volian.Svg.Library/SvgXMLConverter.cs index 815e7d9d..4db5c565 100644 --- a/PROMS/Volian.Svg.Library/SvgXMLConverter.cs +++ b/PROMS/Volian.Svg.Library/SvgXMLConverter.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; namespace Volian.Svg.Library @@ -13,10 +10,6 @@ namespace Volian.Svg.Library TypeConverter FontConverter = TypeDescriptor.GetConverter(typeof(T)); return FontConverter.ConvertToInvariantString(myObject); } - public static T GetObject(string value) - { - TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); - return (T)converter.ConvertFromInvariantString(value); - } - } + public static T GetObject(string value) => (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value); + } } diff --git a/PROMS/Volian.Svg.Library/Volian.Svg.Library.csproj b/PROMS/Volian.Svg.Library/Volian.Svg.Library.csproj index 9beda668..afe8ba6c 100644 --- a/PROMS/Volian.Svg.Library/Volian.Svg.Library.csproj +++ b/PROMS/Volian.Svg.Library/Volian.Svg.Library.csproj @@ -89,7 +89,6 @@ - diff --git a/PROMS/Volian.Svg.Library/iTextSharp.cs b/PROMS/Volian.Svg.Library/iTextSharp.cs index 0be29927..4a0771a9 100644 --- a/PROMS/Volian.Svg.Library/iTextSharp.cs +++ b/PROMS/Volian.Svg.Library/iTextSharp.cs @@ -1,18 +1,10 @@ using System; using System.Collections; -using System.Text; using System.Collections.Generic; using System.Xml.Serialization; using iTextSharp.text; using iTextSharp.text.pdf; -using iTextSharp.text.factories; -using Itenso.Rtf; -using Itenso.Rtf.Parser; -using Itenso.Rtf.Interpreter; -using Itenso.Rtf.Support; -using Microsoft.Win32; using System.Text.RegularExpressions; -using System.Xml; using System.IO; using Volian.Base.Library; @@ -97,23 +89,14 @@ namespace Volian.Svg.Library { get { return _MyText; } } - private SvgText _MySvgText; - public SvgText MySvgText - { - get { return _MySvgText; } - set { _MySvgText = value; } - } - private SvgScale _MySvgScale; - public SvgScale MySvgScale - { - get { return _MySvgScale; } - set { _MySvgScale = value; } - } - public SvgProcessTextArgs(string myText, SvgText mySvgText, SvgScale mySvgScale) + + public SvgText MySvgText { get; set; } + public SvgScale MySvgScale { get; set; } + public SvgProcessTextArgs(string myText, SvgText mySvgText, SvgScale mySvgScale) { _MyText = myText; - _MySvgText = mySvgText; - _MySvgScale = mySvgScale; + MySvgText = mySvgText; + MySvgScale = mySvgScale; } } public partial class Svg : SvgGroup @@ -121,7 +104,7 @@ namespace Volian.Svg.Library private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public void DrawMacro(string macroDef, float x, float y, PdfContentByte cb) { - _MyContentByte = cb; + MyContentByte = cb; SvgMeasurement X = new SvgMeasurement(x, E_MeasurementUnits.PT); SvgMeasurement Y = new SvgMeasurement(Height.GetSizeInPoints(72) - y, E_MeasurementUnits.PT); if (!this.LookUp.ContainsKey(macroDef)) return; // AEP - DU1 (missing C22 macro for AEP) @@ -157,45 +140,31 @@ namespace Volian.Svg.Library top = (yll > yul ? (yll > top ? yll : top) : (yul > top ? yul : top)); tmp.BoundingBox = new iTextSharp.text.Rectangle(xll, yll, xul, yul); } - private PdfContentByte _MyContentByte; - [XmlIgnore] - public PdfContentByte MyContentByte - { - get { return _MyContentByte; } - set { _MyContentByte = value; } - } - private float _LeftMargin = 0; - public float LeftMargin - { - get { return _LeftMargin; } - set { _LeftMargin = value; } - } - private float _TopMargin = 0; - public float TopMargin - { - get { return _TopMargin; } - set { _TopMargin = value; } - } - private SvgScale _MyScale; + + [XmlIgnore] + public PdfContentByte MyContentByte { get; set; } + + public float LeftMargin { get; set; } = 0; + + public float TopMargin { get; set; } = 0; + private SvgScale _MyScale; public SvgScale MyScale { get { if (_MyScale == null) { - _MyScale = new SvgScale(72, new System.Drawing.RectangleF(0, 0, _MyContentByte.PdfWriter.PageSize.Width, _MyContentByte.PdfWriter.PageSize.Height), _Width, _Height, _ViewBox); - _MyScale.XLowerLimit -= _LeftMargin; - _MyScale.YLowerLimit -= _TopMargin; + _MyScale = new SvgScale(72, new System.Drawing.RectangleF(0, 0, MyContentByte.PdfWriter.PageSize.Width, MyContentByte.PdfWriter.PageSize.Height), Width, Height, ViewBox); + _MyScale.XLowerLimit -= LeftMargin; + _MyScale.YLowerLimit -= TopMargin; } return _MyScale; } } public void Draw(PdfContentByte cb) { - //myPdf.Clear(); - _MyContentByte = cb; + MyContentByte = cb; _Templates = new Dictionary(); - //RegisterFonts(); SvgParts.Draw(cb, MyScale, this, this); //72 - Points } public static iTextSharp.text.Font GetFont(string fontName) @@ -214,36 +183,6 @@ namespace Volian.Svg.Library VlnItextFont.RegisterFont(fontName); return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, style, new iTextSharp.text.Color(color)); } - //private static string _FontFolder = null; - //public static string FontFolder - //{ - // get - // { - // if (_FontFolder == null) - // { - // _FontFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts); - // if (_FontFolder == null) _FontFolder = (String)Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Explorer").OpenSubKey("Shell Folders").GetValue("Fontz"); - // _MyLog.WarnFormat("FontFolder set to {0}", _FontFolder); - // } - // return _FontFolder; - // } - //} - private static int _StackTraceSkip = 1; - private static DateTime _LastTime = DateTime.Now; - private static DateTime _StartTime = DateTime.Now; - public static void ResetWhen() - { - _StartTime = _LastTime = DateTime.Now; - } - public static void WhenAndWhere() - { - DateTime thisTime = DateTime.Now; - System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(_StackTraceSkip, true); - Console.WriteLine("{0:000000},{1:000000},'{2}',{3},'{4}'", TimeSpan.FromTicks(thisTime.Ticks - _StartTime.Ticks).TotalMilliseconds, - TimeSpan.FromTicks(thisTime.Ticks - _LastTime.Ticks).TotalMilliseconds, sf.GetMethod().Name, sf.GetFileLineNumber() - ,sf.GetFileName()); - _LastTime = thisTime; - } } public partial class SvgArc : SvgShapePart { @@ -326,18 +265,13 @@ namespace Volian.Svg.Library { // TODO: Could I try creating a template // Don't draw - // SvgParts.Draw(cb, myScale, mySvg, myParent); PdfTemplate tmp = null; if (ID != "") tmp = mySvg.GetTemplate(ID, cb); // the size will be adjusted as items are added. SvgParts.Draw(tmp, myScale, mySvg, myParent); } public override void Draw(PdfTemplate tmp, SvgScale myScale, Svg mySvg, SvgPartInheritance myParent) { - // TODO: Could I try creating a template // Don't draw - // SvgParts.Draw(cb, myScale, mySvg, myParent); - //PdfTemplate tmp2 = mySvg.GetTemplate(ID); // the size will be adjusted as items are added. - //SvgParts.Draw(tmp2, myScale, mySvg, myParent); } } public partial class SvgUse : SvgPartInheritance @@ -348,24 +282,22 @@ namespace Volian.Svg.Library { // TODO: Could I use the template SetupInheritance(myParent.MyInheritedSettings); - if (mySvg.LookUp.ContainsKey(_UseID)) - mySvg[_UseID].Draw(cb, scale.AdjustOrigin(X, Y), mySvg, this); + if (mySvg.LookUp.ContainsKey(UseID)) + mySvg[UseID].Draw(cb, scale.AdjustOrigin(X, Y), mySvg, this); else { - if (!_MissingMacros.Contains(_UseID)) + if (!_MissingMacros.Contains(UseID)) { - _MissingMacros.Add(_UseID); - _MyLog.WarnFormat("Missing Macro '{0}'", _UseID); + _MissingMacros.Add(UseID); + _MyLog.WarnFormat("Missing Macro '{0}'", UseID); } } - //cb.AddTemplate(mySvg.GetTemplate(_UseID.Substring(1),cb), scale.X(X), scale.Y(cb, Y)); } public override void Draw(PdfTemplate tmp, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) { // TODO: Could I use the template SetupInheritance(myParent.MyInheritedSettings); - //mySvg[_UseID.Substring(1)].Draw(tmp, scale.AdjustOrigin(X, Y), mySvg, this); - mySvg[_UseID].Draw(tmp, scale.AdjustOrigin(X, Y), mySvg, this); + mySvg[UseID].Draw(tmp, scale.AdjustOrigin(X, Y), mySvg, this); } } public partial class SvgEllipse : SvgShapePart @@ -410,7 +342,7 @@ namespace Volian.Svg.Library public override void Draw(PdfContentByte cb, SvgScale myScale, Svg mySvg, SvgPartInheritance myParent) { SetupInheritance(myParent.MyInheritedSettings); - _SvgParts.Draw(cb, myScale, mySvg, this); + SvgParts.Draw(cb, myScale, mySvg, this); } public override void Draw(PdfTemplate tmp, SvgScale myScale, Svg mySvg, SvgPartInheritance myParent) { @@ -443,7 +375,8 @@ namespace Volian.Svg.Library { SetupInheritance(myParent.MyInheritedSettings); tmp.SaveState(); - try +#pragma warning disable CS0168 // Variable is declared but never used - ex kept for debugging + try { if (ImagePath != null) { @@ -457,7 +390,8 @@ namespace Volian.Svg.Library { //_MyLog.WarnFormat("SvgImage.Draw '{0}' {1} - {2}", ImagePath, ex.GetType().Name, ex.Message); } - tmp.RestoreState(); +#pragma warning restore CS0168 // Variable is declared but never used + tmp.RestoreState(); } } public partial class SvgLine : SvgLinePart @@ -581,28 +515,19 @@ namespace Volian.Svg.Library { case SvgJustify.Left: return Element.ALIGN_LEFT; - break; case SvgJustify.Center: return Element.ALIGN_CENTER; - break; case SvgJustify.Right: return Element.ALIGN_RIGHT; - break; } return Element.ALIGN_LEFT; } } public class VlnSplitCharacter : ISplitCharacter { - public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) - { - return (cc[current] == ' '); - } - public bool IsSplitCharacter(char c) - { - return (c == ' '); - } - } + public bool IsSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) => (cc[current] == ' '); + public bool IsSplitCharacter(char c) => (c == ' '); + } public static VlnSplitCharacter mySplitter = new VlnSplitCharacter(); // Draw's using PdfContentByte are for drawing PageList items. public override void Draw(PdfContentByte cb, SvgScale scale, Svg mySvg, SvgPartInheritance myParent) @@ -654,9 +579,6 @@ namespace Volian.Svg.Library } switch (Justify) { - //case SvgJustify.Left: - // x = x; - // break; case SvgJustify.Center: x-=w/2; break; @@ -687,12 +609,6 @@ namespace Volian.Svg.Library public static bool CompressPropSubSup = false; private Phrase BuildPhrase(string text, float fontSize, int fontStyle, iTextSharp.text.Font font) { - //if (text == "Caution") - //{ - // if (iTextSharp.text.FontFactory.IsRegistered("VolianScript")) - // Console.WriteLine("Is Registered"); - // Console.WriteLine("stop"); - //} bool fontUnderline = false; float fontTextRise = 0; @@ -700,8 +616,6 @@ namespace Volian.Svg.Library text = Regex.Replace(text, @"\\'[0-9a-fA-F][0-9a-fA-F]", new MatchEvaluator(ReplaceHexCharacter)); text += " "; - //if (text.Contains("\\")) -- these 2 lines made \ul and \ulnone in page list text not get resolved and would then print - //text = text.Replace("\\", ((char)9586).ToString()); // B2016-155 convert backslash char to the unicode symbol - to allow processing rtf commands \ul, \up, \dn, etc. // B2016-167: handle backslashes but don't do if the backslash is an underline rtf command int stindx = text.IndexOf("\\"); while (stindx != -1) @@ -892,170 +806,38 @@ namespace Volian.Svg.Library tmp.RestoreState(); } } - public class SvgPageTotal - { - public SvgPageTotal(System.Drawing.Font myFont, PdfContentByte cb) - { - _MyFont = myFont; - _MyTemplate = cb.CreateTemplate(100, 100); - _MyTemplate.BoundingBox= new Rectangle(-20, -20, 100, 100); - } - private int _PageCount=1; - private System.Drawing.Font _MyFont; - private PdfTemplate _MyTemplate; - public PdfTemplate MyTemplate - { - get { return _MyTemplate; } - } - public void Draw() - { - // Output Page Count - _MyTemplate.BeginText(); - iTextSharp.text.Font font = Svg.GetFont(_MyFont.Name); - BaseFont baseFont = font.BaseFont; - _MyTemplate.SetFontAndSize(baseFont,_MyFont.Size); - _MyTemplate.SetTextMatrix(0, 0); - _MyTemplate.ShowText(_PageCount.ToString()); - _MyTemplate.EndText(); - } - } public class SvgPageHelper : PdfPageEventHelper { - private bool _SpecialCAS; // B2023-005: CAS page, rotate watermark - public bool SpecialCAS + public bool SpecialCAS { get; set; } + public bool IsLandscape { get; set; } + public bool IsWatermarkLandscape { get; set; } + public Svg MySvg { get; set; } + public PdfLayer PageListLayer { get; set; } + public PdfLayer WatermarkLayer { get; set; } + public string Watermark { get; set; } = string.Empty; + public string WatermarkColor { get; set; } = "BLUE"; + public PdfLayer PROMSVersionLayer { get; set; } + public string PROMSVersion { get; set; } = string.Empty; + public bool DoZoomOMatic { get; set; } = false; + public int CurrentPageNumber { get; set; } = 0; + public int CurrentPageNumberNoFoldouts { get; set; } = 0; + public int CurrentTOCPageNumber { get; set; } = 0; + public bool OnFoldoutPage { get; set; } = false; + public bool CreatingFoldoutPage { get; set; } = false; + public bool CreatingSupInfoPage { get; set; } = false; + public SvgPageHelper(Svg mySvg) { - get { return _SpecialCAS; } - set { _SpecialCAS = value; } - } - private bool _IsLandscape; - public bool IsLandscape - { - get { return _IsLandscape; } - set { _IsLandscape = value; } - } - // B2019-145: added the following property so that the code would know that an adjustment should be made to print the watermark - // in landscape mode. Note that 'IsLandscape' could not be used because it also does the pagelist items. - private bool _IsWatermarkLandscape; - public bool IsWatermarkLandscape - { - get { return _IsWatermarkLandscape; } - set { _IsWatermarkLandscape = value; } - } - // B2018-124 we no longer need is list was not hanling "Information Only" water mark - //private List _AllowedWatermarks = new List(); - //public List AllowedWatermarks - //{ - // get { return _AllowedWatermarks; } - // set { _AllowedWatermarks = value; } - //} - private Svg _MySvg; - public Svg MySvg - { - get { return _MySvg; } - set { _MySvg = value; } - } - private PdfLayer _PageListLayer; - public PdfLayer PageListLayer - { - get { return _PageListLayer; } - set { _PageListLayer = value; } - } - private PdfLayer _WatermarkLayer; - public PdfLayer WatermarkLayer - { - get { return _WatermarkLayer; } - set { _WatermarkLayer = value; } - } - private string _Watermark=string.Empty; - public string Watermark - { - get { return _Watermark; } - set { _Watermark = value; } - } - private string _WatermarkColor = "BLUE"; - public string WatermarkColor - { - get { return _WatermarkColor; } - set { _WatermarkColor = value; } - } - private PdfLayer _PROMSVersionLayer; //C2018-009 print PROMS version - public PdfLayer PROMSVersionLayer - { - get { return _PROMSVersionLayer; } - set { _PROMSVersionLayer = value; } - } - private string _PROMSVersion = string.Empty; - public string PROMSVersion - { - get { return _PROMSVersion; } - set { _PROMSVersion = value; } - } - private bool _DoZoomOMatic = false; - public bool DoZoomOMatic - { - get { return _DoZoomOMatic; } - set { _DoZoomOMatic = value; } - } - private int _CurrentPageNumber = 0; - public int CurrentPageNumber - { - get { return _CurrentPageNumber; } - set { _CurrentPageNumber = value; } - } - private int _CurrentPageNumberNoFoldouts = 0; - public int CurrentPageNumberNoFoldouts - { - get { return _CurrentPageNumberNoFoldouts; } - set { _CurrentPageNumberNoFoldouts = value; } - } - private int _CurrentTOCPageNumber = 0; - public int CurrentTOCPageNumber - { - get { return _CurrentTOCPageNumber; } - set { _CurrentTOCPageNumber = value; } - } - private bool _OnFoldoutPage = false; - public bool OnFoldoutPage - { - get { return _OnFoldoutPage; } - set { _OnFoldoutPage = value; } - } - private bool _CreatingFoldoutPage = false; - public bool CreatingFoldoutPage - { - get { return _CreatingFoldoutPage; } - set { _CreatingFoldoutPage = value; } - } - private bool _CreatingSupInfoPage = false; - public bool CreatingSupInfoPage - { - get { return _CreatingSupInfoPage; } - set { _CreatingSupInfoPage = value; } - } - public SvgPageHelper(Svg mySvg) - { - _MySvg = mySvg; + MySvg = mySvg; } public SvgPageHelper() { } - private int _BGPageOffset = 0; - public int BackgroundPageOffset - { - get { return _BGPageOffset; } - set { _BGPageOffset = value; } - } - protected virtual string ReplacePageListToken(Match match) - { - return string.Empty; - } - public override void OnOpenDocument(PdfWriter writer, Document document) + public int BackgroundPageOffset { get; set; } = 0; + protected virtual string ReplacePageListToken(Match match) => string.Empty; + + public override void OnOpenDocument(PdfWriter writer, Document document) { - //base.OnOpenDocument(writer, document); - //tmpTotal = writer.DirectContent.CreateTemplate(100, 100); - //tmpTotal.BoundingBox = new Rectangle(-20, -20, 100, 100); - //PdfContentByte cb = writer.DirectContent; } public override void OnEndPage(PdfWriter writer, Document document) { @@ -1093,8 +875,8 @@ namespace Volian.Svg.Library { get { - if (_BackgroundReader == null && _BackgroundFile != null && File.Exists(_BackgroundFile)) - _BackgroundReader = new PdfReader(_BackgroundFile); + if (_BackgroundReader == null && BackgroundFile != null && File.Exists(BackgroundFile)) + _BackgroundReader = new PdfReader(BackgroundFile); return _BackgroundReader; } } @@ -1106,29 +888,17 @@ namespace Volian.Svg.Library return BackgroundReader.Info["Producer"].ToString().StartsWith("iTextSharp"); } } - private string _BackgroundFile = null; - public string BackgroundFile - { - get { return _BackgroundFile; } - set { _BackgroundFile = value; } - } - private PdfLayer _BackgroundLayer = null; - public PdfLayer BackgroundLayer - { - get { return _BackgroundLayer; } - set { _BackgroundLayer = value; } - } - private System.Drawing.PointF _BackgroundOffset = new System.Drawing.PointF(0, 0); + + public string BackgroundFile { get; set; } = null; + public PdfLayer BackgroundLayer { get; set; } = null; + private System.Drawing.PointF _BackgroundOffset = new System.Drawing.PointF(0, 0); public System.Drawing.PointF BackgroundOffset { get { return _BackgroundOffset; } set { _BackgroundOffset = value; } } - public int BackgroundPageCount - { - get { return BackgroundReader == null ? 0 : BackgroundReader.NumberOfPages; } - } - private PdfImportedPage GetBackgroundPage(PdfContentByte cb) + public int BackgroundPageCount => BackgroundReader == null ? 0 : BackgroundReader.NumberOfPages; + private PdfImportedPage GetBackgroundPage(PdfContentByte cb) { if (BackgroundReader == null) return null; int page = cb.PdfWriter.CurrentPageNumber + BackgroundPageOffset; @@ -1151,14 +921,10 @@ namespace Volian.Svg.Library ZoomOMatic(cb, 36); cb.RestoreState(); } - private bool _AllowAllWatermarks = false; - public bool AllowAllWatermarks - { - get { return _AllowAllWatermarks; } - set { _AllowAllWatermarks = value; } - } - //C2022-004 This will return the system drawing color from either the color name or ARGB values - public System.Drawing.Color GetWatermarkColor(string colorDescription) + + public bool AllowAllWatermarks { get; set; } = false; + //C2022-004 This will return the system drawing color from either the color name or ARGB values + public System.Drawing.Color GetWatermarkColor(string colorDescription) { System.Drawing.Color systemColor; if (colorDescription.StartsWith("[A=")) // if color is ARGB representation, parse out the values @@ -1192,9 +958,8 @@ namespace Volian.Svg.Library private void DrawWatermark(PdfContentByte cb) { if (Watermark == null || Watermark.ToLower().Contains("none") || Watermark == "") return; - //if (!AllowAllWatermarks && !AllowedWatermarks.Contains(Watermark)) return; -- B2018-124 not needed anymore with above if statement - this does not hanle "Information Only" cb.SaveState(); - if (_WatermarkLayer != null) cb.BeginLayer(_WatermarkLayer); + if (WatermarkLayer != null) cb.BeginLayer(WatermarkLayer); // B2023-005: Beaver Valley, second page of CAS page is a 'foldout' on large paper - need to rotate the // watermark if (SpecialCAS) @@ -1207,16 +972,13 @@ namespace Volian.Svg.Library else if (IsLandscape || IsWatermarkLandscape) // B2019-145: Added for printing landscape watermark on step section pages. { // The watermark needs to be rotated back for landscape pagelist - B2016-191 - //double a = -33 * (Math.PI / 180); - //System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix((float)Math.Cos(a), (float)Math.Sin(a), (float)-Math.Sin(a), (float)Math.Cos(a), -60, 320); double a = -90 * (Math.PI / 180); System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix((float)Math.Cos(a), (float)Math.Sin(a), (float)-Math.Sin(a), (float)Math.Cos(a), 0, cb.PdfDocument.PageSize.Height); cb.Transform(myMatrix); } SvgWatermark myWatermark = new SvgWatermark(cb, Watermark, GetWatermarkColor(WatermarkColor), .15F); - //myWatermark.SetSquareDotPattern(.7F); myWatermark.Draw(); - if (_WatermarkLayer != null) cb.EndLayer(); + if (WatermarkLayer != null) cb.EndLayer(); cb.RestoreState(); } //C2018-009 print PROMS version @@ -1226,32 +988,22 @@ namespace Volian.Svg.Library string text = PROMSVersion; float textBase =cb.PdfDocument.Top + 19; float textLeft = cb.PdfDocument.Right - 15; - if (_PROMSVersionLayer != null) cb.BeginLayer(_PROMSVersionLayer); + if (PROMSVersionLayer != null) cb.BeginLayer(PROMSVersionLayer); cb.BeginText(); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED), 6f); cb.SetTextMatrix(textLeft, textBase); cb.SetColorFill(new iTextSharp.text.Color(System.Drawing.Color.Indigo)); cb.ShowText(text); cb.EndText(); - if (_PROMSVersionLayer != null) cb.EndLayer(); + if (PROMSVersionLayer != null) cb.EndLayer(); cb.RestoreState(); } private void DrawPageList(PdfContentByte cb) { - if (_MySvg != null) + if (MySvg != null) { cb.SaveState(); - if (_PageListLayer != null) cb.BeginLayer(_PageListLayer); - // Do anything needed to finish off the page - //System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix(); - //myMatrix.Rotate(90); // Rotate the Pagelist items by 90 Degrees. - //// Translate by the Height of the page. - //myMatrix.Translate(cb.PdfDocument.PageSize.Height, 0, System.Drawing.Drawing2D.MatrixOrder.Append); - //// This was for fun - //// myMatrix.Scale(.75F, .75F, System.Drawing.Drawing2D.MatrixOrder.Append); - //cb.Transform(myMatrix); - //// You can look at the value of the Matrix at this point, to create the matrix directly like I did below - //OR + if (PageListLayer != null) cb.BeginLayer(PageListLayer); // Rotate 90 Degrees and Translate by the Height of the Page if (IsLandscape) @@ -1259,8 +1011,8 @@ namespace Volian.Svg.Library System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix(0, 1, -1, 0, cb.PdfDocument.PageSize.Height, 0); cb.Transform(myMatrix); } - _MySvg.Draw(cb); - if (_PageListLayer != null) cb.EndLayer(); + MySvg.Draw(cb); + if (PageListLayer != null) cb.EndLayer(); cb.RestoreState(); } } @@ -1277,7 +1029,7 @@ namespace Volian.Svg.Library } public override void OnStartPage(PdfWriter writer, Document document) { - //base.OnStartPage(writer, document); + } public override void OnCloseDocument(PdfWriter writer, Document document) { @@ -1289,137 +1041,24 @@ namespace Volian.Svg.Library private PdfContentByte _ContentByte; private string _Text; private System.Drawing.Color _Color; - private PdfPatternPainter _PatternPainter; - private BaseFont _Basefont; - private float _Fontsize; - private float _XOffset; - private float _YOffset; - private float _TextAngle; private float _Opacity; public SvgWatermark(PdfContentByte contentByte, string text, System.Drawing.Color color, float opacity) { _ContentByte = contentByte; _Text = text; - //float radius = .5F; - //float space = 3; // B2021-081: Blue was too intense with an alpha of 255 Read was too light with an alpha of 96 if (color != System.Drawing.Color.Red) _Color = System.Drawing.Color.FromArgb(96, color); else _Color = color; // C2021-019: save color for color override _Opacity = opacity; - //SetDotPattern(radius, space); - //SetTextLayout(); } - #region commentedout - //private void SetTextLayout() - //{ - // Rectangle pageSize = _ContentByte.PdfWriter.PageSize; // Get page size - // _Basefont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, BaseFont.EMBEDDED); - // float hgtA = _Basefont.GetAscentPoint(_Text, 12); - // //float hgtD = basefont.GetDescentPoint(text,20); - // float wid = _Basefont.GetWidthPointKerned(_Text, 12); - // //Console.WriteLine("{0} {1} {2}",hgtA,hgtD,wid); - // float rho = wid / hgtA; - // float x2 = (rho * pageSize.Height - pageSize.Width) / (rho * rho - 1); - // float y1 = x2 * rho; - // float y2 = pageSize.Height - y1; - // float x1 = pageSize.Width - x2; - // _XOffset = x2 + x1 / 2; - // _YOffset = y1 / 2; - // _TextAngle = CalcAngle(y1, x1); - // _Fontsize = (float)(10 * Math.Sqrt(x2 * x2 + y2 * y2) / hgtA); - //} - //public void SetDotPattern(float radius, float space) - //{ - // _PatternPainter = _ContentByte.CreatePattern(radius * 2, radius * 2, radius * 2 + space, radius * 2 + space); - // PdfGState gState = new PdfGState(); - // gState.FillOpacity = _Opacity; - // _PatternPainter.SetGState(gState); - // _PatternPainter.SetColorFill(_Color); - // _PatternPainter.Circle(radius, radius, radius); - // _PatternPainter.Fill(); - //} - //public void SetSquareDotPattern(float radius) - //{ - // _PatternPainter = _ContentByte.CreatePattern(radius * 4, radius * 2, radius * 4, radius * 2); - // PdfGState gState = new PdfGState(); - // gState.FillOpacity = .5f * _Opacity; - // _PatternPainter.SetGState(gState); - // _PatternPainter.SetColorFill(_Color); - // _PatternPainter.Rectangle(0, 0, radius, radius); - // _PatternPainter.Rectangle(radius * 2, radius, radius, radius); - // _PatternPainter.Fill(); - //} - //public void SetHashPattern(float thickness, float size) - //{ - // _PatternPainter = _ContentByte.CreatePattern(size, size, size, size); - // PdfGState gState = new PdfGState(); - // gState.FillOpacity = _Opacity; - // gState.StrokeOpacity = _Opacity; - // _PatternPainter.SetGState(gState); - // _PatternPainter.SetLineWidth(.01F); - // _PatternPainter.SetColorStroke(_Color); // Set color - // _PatternPainter.MoveTo(0, 0); - // _PatternPainter.LineTo(size, size); - // _PatternPainter.MoveTo(size, 0); - // _PatternPainter.LineTo(0, size); - // _PatternPainter.Stroke(); - //} - //public void SetTextPattern(float fontSize, float space) - //{ - // float hgtA = _Basefont.GetAscentPoint(_Text, fontSize) + _Basefont.GetDescentPoint(_Text, fontSize); - // float wid = _Basefont.GetWidthPointKerned(_Text, fontSize); - // _PatternPainter = _ContentByte.CreatePattern(wid, hgtA, wid + space, hgtA + space); - // _PatternPainter.SetFontAndSize(_Basefont, fontSize); - // _PatternPainter.BoundingBox = new Rectangle(-20, -20, 100, 100); - // _PatternPainter.BeginText(); - // PdfGState gs1 = new PdfGState(); - // gs1.FillOpacity = _Opacity; - // _PatternPainter.SetGState(gs1); - // _PatternPainter.SetColorFill(_Color); // Set color - // _PatternPainter.ShowText(_Text); - // _PatternPainter.EndText(); - //} - //public void SetTextPattern2(float fontSize) - //{ - // BaseFont _Basefont2 = BaseFont.CreateFont(BaseFont.HELVETICA, Encoding.ASCII.EncodingName, BaseFont.EMBEDDED); - // float hgtA = _Basefont2.GetAscentPoint(_Text, fontSize); - // float wid = _Basefont2.GetWidthPointKerned(_Text, fontSize); - // _PatternPainter = _ContentByte.CreatePattern(wid * 2, hgtA * 2, wid * 2, hgtA * 2); - // _PatternPainter.SetFontAndSize(_Basefont2, fontSize); - // _PatternPainter.BoundingBox = new Rectangle(-20, -20, 100, 100); - // _PatternPainter.BeginText(); - // PdfGState gs1 = new PdfGState(); - // gs1.FillOpacity = _Opacity; - // _PatternPainter.SetGState(gs1); - // _PatternPainter.SetColorFill(_Color); // Set color - // _PatternPainter.ShowText(_Text); - // _PatternPainter.ShowTextAligned(PdfContentByte.ALIGN_LEFT, _Text, wid, hgtA, 0); - // _PatternPainter.EndText(); - //} - #endregion public void Draw() { _ContentByte.SaveState(); - //_ContentByte.BeginText(); - //_ContentByte.SetPatternFill(_PatternPainter); - //_ContentByte.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); - //_ContentByte.SetLineWidth(.5F); - //_ContentByte.SetFontAndSize(_Basefont, _Fontsize);// Set font and size - //_ContentByte.SetColorStroke(_Color); - //PdfGState gs2 = new PdfGState(); - //gs2.StrokeOpacity = _Opacity; - //_ContentByte.SetGState(gs2); - //_ContentByte.ShowTextAlignedKerned(PdfContentByte.ALIGN_CENTER, _Text, _XOffset, _YOffset, _TextAngle);// Draw the text - //_ContentByte.EndText(); _ContentByte.AddImage(WatermarkImage); _ContentByte.RestoreState(); } - //private float CalcAngle(float opposite, float adjacent) - //{ - // return (float)(Math.Atan2(opposite, adjacent) * (180 / Math.PI)); - //} private Image _WatermarkImage; public Image WatermarkImage { @@ -1452,7 +1091,6 @@ namespace Volian.Svg.Library _Color, System.Drawing.Color.Transparent); g.FillPath(aHatchBrush, gp); g.DrawPath(new System.Drawing.Pen(_Color), gp); - //g.DrawRectangle(System.Drawing.Pens.Cyan, 0, 0, bnds.Width, bnds.Height); } _WatermarkImage = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Png); _WatermarkImage.SetAbsolutePosition(72, 72); @@ -1481,11 +1119,4 @@ namespace Volian.Svg.Library } } - public enum SvgWatermarkFill - { - Dots = 1, - Text1 = 2, - Text2 = 3, - Hash = 4 - } } diff --git a/PROMS/Volian.Utils.Library/MSWord/WordDoc.cs b/PROMS/Volian.Utils.Library/MSWord/WordDoc.cs index 86b436a0..e8c37df8 100644 --- a/PROMS/Volian.Utils.Library/MSWord/WordDoc.cs +++ b/PROMS/Volian.Utils.Library/MSWord/WordDoc.cs @@ -1,108 +1,9 @@ using System; -using System.Collections.Generic; -using System.Text; -using LBWordLibrary; namespace Volian.MSWord { public class WordDoc { - private static LBApplicationClass _MyWordApp; - public static LBApplicationClass MyWordApp - { - get - { - if (_MyWordApp == null) - _MyWordApp = new LBApplicationClass(); - return WordDoc._MyWordApp; - } - } - private LBDocumentClass _MyWordDoc; - public LBDocumentClass MyWordDoc - { - get - { return _MyWordDoc; } - } - private string _DocName; - public string DocName - { - get { return _DocName; } - set { _DocName = value; } - } - public WordDoc(string docName) - { - DocName = docName; - _MyWordDoc = MyWordApp.Documents.Open(_DocName, false); - } - public string Save() - { - try - { - MyWordDoc.SaveAs(DocName, LBWdSaveFormat.wdFormatDocument); - return "Successful Save"; - } - catch (Exception ex) - { - return string.Format("Error during Doc save - {0}", ex.Message); - } - } - public string Save(string docName) - { - DocName = docName; - return Save(); - } - public void Close() - { - MyWordDoc.Close(false); - } - public float SetLineSpacing(float linesPerInch) // if need landscape set too: , bool landscape) - { - float retval = 0; - LBSelection selection = MyWordApp.Selection; - selection.WholeStory(); - retval = selection.ParagraphFormat.LineSpacing; - selection.ParagraphFormat.SpaceBefore = 0; - selection.ParagraphFormat.SpaceAfter = 0; - selection.ParagraphFormat.LineSpacingRule = LBWdLineSpacing.wdLineSpaceExactly; - selection.ParagraphFormat.LineSpacing = 72 / linesPerInch; - return retval; - } - public float Length - { - get - { - try - { - return MyWordDoc.Length; - } - catch (Exception ex) - { - Console.WriteLine("Error Getting Length, {0}", ex.Message); - } - return 0; - } - } - public static void CloseApp() - { - if(_MyWordApp != null) - { - TryToQuit(); - KillWordApps(); - } - } - - private static void TryToQuit() - { - try - { - _MyWordApp.Quit(false); - } - catch (Exception ex) - { - Console.WriteLine("{0} - {1}", ex.GetType().Name, ex.Message); - } - _MyWordApp=null; - } public static void KillWordApps() { try @@ -124,15 +25,8 @@ namespace Volian.MSWord if(proc.MainWindowTitle=="") proc.Kill(); } - _MyWordApp = null; - } - public static System.Diagnostics.Process[] WordProcesses - { - get - { - return System.Diagnostics.Process.GetProcessesByName("WINWORD"); - } } + public static System.Diagnostics.Process[] WordProcesses => System.Diagnostics.Process.GetProcessesByName("WINWORD"); - } + } } diff --git a/PROMS/Volian.Utils.Library/vlnObject/vlnObject.cs b/PROMS/Volian.Utils.Library/vlnObject/vlnObject.cs index 3de17358..e1b24b77 100644 --- a/PROMS/Volian.Utils.Library/vlnObject/vlnObject.cs +++ b/PROMS/Volian.Utils.Library/vlnObject/vlnObject.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; -using System.Text; using System.Xml.Serialization; using System.Xml; using System.Xml.Schema; -using System.Collections; using System.IO; using System.Text.RegularExpressions; @@ -20,12 +18,9 @@ namespace vlnObjectLibrary { /* See if I need to do anything */ } - #region XML Serialization - public void WriteXml(XmlWriter w) - { - WriteXml(w, true); - } - public void WriteXml(XmlWriter w,bool bSaveParent) + #region XML Serialization + public void WriteXml(XmlWriter w) => WriteXml(w, true); + public void WriteXml(XmlWriter w,bool bSaveParent) { w.WriteAttributeString("title", Title); w.WriteAttributeString("path", Path); @@ -74,13 +69,10 @@ namespace vlnObjectLibrary xr.Close(); } - public XmlSchema GetSchema() - { - return (null); - } - #endregion - #region Constructors - public vlnObject(vlnObject parent, string type, string title, string path) + public XmlSchema GetSchema() => (null); + #endregion + #region Constructors + public vlnObject(vlnObject parent, string type, string title, string path) { m_Parent = parent; m_Type = type; @@ -148,11 +140,8 @@ namespace vlnObjectLibrary vlnObject b = new vlnObject(this, type, title, path); return b; } - public void AddProp(string name, string value) - { - PropArray[name.ToUpper()] = value; - } - public void AddProp(XmlReader xr) + public void AddProp(string name, string value) => PropArray[name.ToUpper()] = value; + public void AddProp(XmlReader xr) { SkipToElement(xr); string sName = null; @@ -182,11 +171,8 @@ namespace vlnObjectLibrary m_Children = value; } } - public void LoadChildren(string sXml) - { - LoadChildren(new XmlTextReader(new StringReader(sXml))); - } - public void LoadChildren(XmlReader xr) + public void LoadChildren(string sXml) => LoadChildren(new XmlTextReader(new StringReader(sXml))); + public void LoadChildren(XmlReader xr) { m_Children = new List(); SkipToElement(xr); @@ -212,8 +198,6 @@ namespace vlnObjectLibrary } public string ProcessString(string s) { - //string retval=s; - //string retval = Regex.Replace(s, "{[.]*}", new MatchEvaluator(ReplaceKey)); string retval = Regex.Replace(s, "{{.*?}}", new MatchEvaluator(ReplaceRow)); retval = Regex.Replace(retval, "{.*?}", new MatchEvaluator(ReplaceDrv)); return retval; diff --git a/PROMS/Volian.Utils.Library/vlnServerLibrary/vlnServer.cs b/PROMS/Volian.Utils.Library/vlnServerLibrary/vlnServer.cs index e3a0c027..f21a3667 100644 --- a/PROMS/Volian.Utils.Library/vlnServerLibrary/vlnServer.cs +++ b/PROMS/Volian.Utils.Library/vlnServerLibrary/vlnServer.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; -using System.Text; using vlnObjectLibrary; using System.Xml; using System.IO; using System.Data; using System.Data.OleDb; -using System.Reflection; namespace vlnServerLibrary { @@ -15,18 +13,10 @@ namespace vlnServerLibrary #region Log4Net private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion - #region Static Properties - private static string m_XmlControlPath = "vlnControl.xml"; - private static XmlDocument m_XmlControl; - public static string XMLControlPath - { - get { return m_XmlControlPath; } - set - { - m_XmlControlPath = value; - } - } - public static XmlDocument XMLControl + #region Static Properties + private static XmlDocument m_XmlControl; + public static string XMLControlPath { get; set; } = "vlnControl.xml"; + public static XmlDocument XMLControl { get { @@ -35,7 +25,7 @@ namespace vlnServerLibrary m_XmlControl = new XmlDocument(); lock (m_XmlControl) { - m_XmlControl.Load(m_XmlControlPath); + m_XmlControl.Load(XMLControlPath); } } return m_XmlControl; @@ -75,11 +65,8 @@ namespace vlnServerLibrary string xPath = string.Format(".//dbObject[@type='{0}']/@{1}", o.Parent.Type, s); return LookUpX(o,xPath); } - protected string LookUpX(vlnObject o,string xPath) - { - return LookUpX(o,xPath, XMLControl); - } - private void LoadChildrenFromDB(vlnObject o,string sSelect) + protected string LookUpX(vlnObject o, string xPath) => LookUpX(o, xPath, XMLControl); + private void LoadChildrenFromDB(vlnObject o,string sSelect) { if (sSelect != "") { @@ -89,7 +76,6 @@ namespace vlnServerLibrary OleDbConnectionStringBuilder csb = new OleDbConnectionStringBuilder(s); OleDbConnection dbConn = new OleDbConnection(csb.ConnectionString); string sTable = LookUp(o,"table"); - //if (dbConn.State != ConnectionState.Open) dbConn.Open(); OleDbDataAdapter da = new OleDbDataAdapter(sSelect, dbConn); DataSet ds = new DataSet(); da.Fill(ds, sTable); @@ -222,7 +208,7 @@ namespace vlnServerLibrary string sRetval = sDefault; if (sRetval[0] == '~') { - string sTitlePath = sPath + "\\title"; + string sTitlePath = $"{sPath}\\title"; if (File.Exists(sTitlePath)) { StreamReader sr = File.OpenText(sTitlePath); diff --git a/PROMS/XYPlots/GlobalSuppressions.cs b/PROMS/XYPlots/GlobalSuppressions.cs new file mode 100644 index 00000000..046248af --- /dev/null +++ b/PROMS/XYPlots/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/XYPlots/XYPlots.cs b/PROMS/XYPlots/XYPlots.cs index f9269c6c..d14ee178 100644 --- a/PROMS/XYPlots/XYPlots.cs +++ b/PROMS/XYPlots/XYPlots.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Windows.Forms; @@ -19,54 +18,35 @@ namespace XYPlots #region Log4Net // C2018-035 Added error Handling to provide more useful information when a plot fails private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - #endregion - static string _MyFontFamily = "Letter Gothic Tall"; - public static string MyFontFamily - { - get { return _MyFontFamily; } - set { _MyFontFamily = value; } - } - private static Color _BlackColor = Color.Red; + #endregion + public static string MyFontFamily { get; set; } = "Letter Gothic Tall"; public static Color BlackColor { get { return VG.VG.BlackColor; } set { VG.VG.BlackColor = value; } } - public float Width - { - get { return 72 * (LeftMargin + RightMargin) + printerunits[0] * .05F; } - } - public float Height - { - get { return 72 * (TopMargin + BottomMargin) + printerunits[1] * .05F; } - } - public float PlotWidth - { - get { return (float) userunits[X]; } - } - public float PlotHeight - { - get { return (float) userunits[Y]; } - } - private double ConvertToTwips = 4.8; - static int MAX_XY_STACK = 8; /* this is max of CIE cursor/font stack */ - static int DPI = 1440; //300; - static int CWIDEDOTS = 120; //25; - static int CHIGHDOTS = 240; //50; - static int STRAIGHT = 0; - static int CURVE = 1; - static int X = 0; - static int Y = 1; - static int Dimensions = 2; - static int USER = 0; - static int PLOT = 1; - static double PI = 3.141592653; - static double Zero = 0.0; - static double ANGLELIMIT = 1.0; + public float Width => 72 * (LeftMargin + RightMargin) + printerunits[0] * .05F; + public float Height => 72 * (TopMargin + BottomMargin) + printerunits[1] * .05F; + public float PlotWidth => (float)userunits[X]; + public float PlotHeight => (float)userunits[Y]; + private readonly double ConvertToTwips = 4.8; + static readonly int MAX_XY_STACK = 8; /* this is max of CIE cursor/font stack */ + static readonly int DPI = 1440; //300; + static readonly int CWIDEDOTS = 120; //25; + static readonly int CHIGHDOTS = 240; //50; + static readonly int STRAIGHT = 0; + static readonly int CURVE = 1; + static readonly int X = 0; + static readonly int Y = 1; + static readonly int Dimensions = 2; + static readonly int USER = 0; + static readonly int PLOT = 1; + static readonly double PI = 3.141592653; + static readonly double Zero = 0.0; + static readonly double ANGLELIMIT = 1.0; // !!!! NEED REAL SUPERSCRIPT ON/OFF TOKENS - static string[] SuperScript = { "##", "##" }; - static string[] SubScript = { "~~", "~~" }; - FileStream XYPlotFile; + static readonly string[] SuperScript = { "##", "##" }; + static readonly string[] SubScript = { "~~", "~~" }; private int[] SavedX; private int[] SavedY; private int stack; @@ -124,30 +104,30 @@ namespace XYPlots private string valuestring; private string powerstring; private int GridOnFlag, Visible, ShadowFlag; - private char[] type = new char[Dimensions]; - private double FontPitch = 10.0; - private double[] minimum = new double[Dimensions]; - private double[] maximum = new double[Dimensions]; - private double[] userunits = new double[Dimensions]; - private int[] printerunits = new int[Dimensions]; - private int[] Position = new int[Dimensions]; - private double[,] Scale = new double[2, Dimensions]; - private double[,] Offset = new double[2, Dimensions]; - private double[] delta = new double[Dimensions]; - private int[] cycles = new int[Dimensions]; - private int[] onecycle = new int[Dimensions]; - private int[] minor = new int[Dimensions]; - private int[] spcminor = new int[Dimensions]; - private string[] AxisTitles = new string[Dimensions]; - private int[] AxisLabel = new int[Dimensions];// 1 for YES(default), 0 for NO + private readonly char[] type = new char[Dimensions]; + private readonly double FontPitch = 10.0; + private readonly double[] minimum = new double[Dimensions]; + private readonly double[] maximum = new double[Dimensions]; + private readonly double[] userunits = new double[Dimensions]; + private readonly int[] printerunits = new int[Dimensions]; + private readonly int[] Position = new int[Dimensions]; + private readonly double[,] Scale = new double[2, Dimensions]; + private readonly double[,] Offset = new double[2, Dimensions]; + private readonly double[] delta = new double[Dimensions]; + private readonly int[] cycles = new int[Dimensions]; + private readonly int[] onecycle = new int[Dimensions]; + private readonly int[] minor = new int[Dimensions]; + private readonly int[] spcminor = new int[Dimensions]; + private readonly string[] AxisTitles = new string[Dimensions]; + private readonly int[] AxisLabel = new int[Dimensions];// 1 for YES(default), 0 for NO private int CurPenWidth, DrawDirection, LineFlag, LineDiv; private int EndFlag = 0; public string Buff; private int BuffPtr = 0; - private bool[,] doLOG10 = { { false, false }, { false, false } }; + private readonly bool[,] doLOG10 = { { false, false }, { false, false } }; public struct point { - public int[] xyValue; //new int[Dimensions]; + public int[] xyValue; } public struct XyBox { @@ -159,27 +139,21 @@ namespace XYPlots public class XyBoxes : List { } - private XyBoxes AllBoxes = new XyBoxes(); - private XyBoxes ActiveBoxes = new XyBoxes(); + private readonly XyBoxes AllBoxes = new XyBoxes(); + private readonly XyBoxes ActiveBoxes = new XyBoxes(); public class DataPoint { - public override string ToString() // Make it easier to Debug - { - return string.Format("{0},{1}", APoint.xyValue[X],APoint.xyValue[Y]); - } - private point m_APoint; + // Make it easier to Debug + public override string ToString() => string.Format("{0},{1}", APoint.xyValue[X], APoint.xyValue[Y]); + private point m_APoint; public point APoint { get { return m_APoint; } set { m_APoint = value; } } - private double m_slope; // slope of tangent to circle at this point - public double slope - { - get { return m_slope; } - set { m_slope = value; } - } - } + + public double slope { get; set; } + } public class DataPoints : List { } @@ -189,7 +163,8 @@ namespace XYPlots public int PlotDivisions; public DataPoints PlotDataPoints; }; - private List AllPlots = new List(); + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] + private List AllPlots = new List(); private int YLandScape = 0; /* y axis title is horizontal */ private point YTitleOrigin; /* y axis title origin if vertical */ private double FixAngle(double a1) @@ -212,41 +187,20 @@ namespace XYPlots result = (double)(val * val); return result; } - private double FMin(double f1, double f2) - { - return ((f1 >= f2) ? f2 : f1); - } - private double FMax(double f1, double f2) - { - return ((f1 >= f2) ? f1 : f2); - } - private double atan_deg(double x) - { - return (Math.Atan(x) * 180.0 / PI); - } - private double cos_deg(double x) - { - return (Math.Cos(x * PI / 180.0)); - } - private double tan_deg(double x) - { - return (Math.Tan(x * PI / 180.0)); - } - private double sin_deg(double x) - { - return (Math.Sin(x * PI / 180.0)); - } - /// - /// the following function is pointed to by a function pointer - /// and is provided for compatibility with log10() function usage - /// - /// - /// - private double linear(double x) - { - return x; - } - private bool isWhiteSpace(char cptr) + private double FMin(double f1, double f2) => ((f1 >= f2) ? f2 : f1); + private double FMax(double f1, double f2) => ((f1 >= f2) ? f1 : f2); + private double atan_deg(double x) => (Math.Atan(x) * 180.0 / PI); + private double cos_deg(double x) => (Math.Cos(x * PI / 180.0)); + private double tan_deg(double x) => (Math.Tan(x * PI / 180.0)); + private double sin_deg(double x) => (Math.Sin(x * PI / 180.0)); + /// + /// the following function is pointed to by a function pointer + /// and is provided for compatibility with log10() function usage + /// + /// + /// + private double linear(double x) => x; + private bool isWhiteSpace(char cptr) { bool rtnval = false; if (!cptr.Equals(null)) @@ -279,77 +233,8 @@ namespace XYPlots else return false; } - private bool LoadBuff(string FileName) - { - if (!File.Exists(FileName)) - { - if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. - { - // File does not exist, show error message - MessageBox.Show(String.Format("X/Y Plot File {0} Does Not Exist", FileName), "Error Opening X/Y Plot File"); - return false; - } - } - // Open the X/Y Plot file - try - { - XYPlotFile = File.OpenRead(FileName); - } - catch (Exception e) - { - if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. - { - // cannot open the x/y plot file - MessageBox.Show(e.Message, String.Format("Error Opening {0} for Reading", FileName)); - return false; - } - } - int blen = (int)XYPlotFile.Length; - int bread = 0; - // initialize a byte array to read into - byte[] bbuf = new byte[blen + 1]; - for (int i = 0; i < blen; i++) bbuf[i] = 0; - // Read the contents of the x/y plot file into the byte array - try - { - bread = XYPlotFile.Read(bbuf, 0, blen); - } - catch (Exception e) - { - if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. - { - MessageBox.Show(e.Message, String.Format("Error Reading {0}", FileName)); - return false; - } - } - try - { - XYPlotFile.Close(); - } - catch (Exception e) - { - if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. - { - MessageBox.Show(e.Message, String.Format("Error Closing {0}", FileName)); - return false; - } - } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < bbuf.Length; i++) - { - if (bbuf[i] == '\r' && bbuf[i - 1] == ' ') - sb.Remove(i - 1, 1); - sb.Append(Convert.ToChar(bbuf[i])); - } - Buff = sb.ToString(); - BuffPtr = 0; - return true; - } - private void LoadBuffFromString(string str) - { - Buff = str; - } - private int getint() + private void LoadBuffFromString(string str) => Buff = str; + private int getint() { int retval; string np = NextPiece(); @@ -394,30 +279,21 @@ namespace XYPlots retval = Convert.ToDouble(NextPiece()); return retval; } - private char NextChar() - { - return Buff[BuffPtr++]; - } - private char getchr() + private char NextChar() => Buff[BuffPtr++]; + private char getchr() { string nxtstring = NextPiece(); - if (nxtstring.Equals("")) - return '\0'; - else - return nxtstring[0]; - } - // C2018-035 Added error Handling to provide more useful information when a plot fails - private string _XYPlotIssue; - public string XYPlotIssue + return nxtstring.Equals("") ? '\0' : nxtstring[0]; + } + + public string XYPlotIssue { get; set; } + private point GetPair(int flag) { - get { return _XYPlotIssue; } - set { _XYPlotIssue = value; } - } - private point GetPair(int flag) - { - point retval = new point(); - retval.xyValue = new int[Dimensions]; - double x, y; + point retval = new point + { + xyValue = new int[Dimensions] + }; + double x, y; char[] sepchar = { ',' }; string nextPiece = NextPiece(); // Plot Definition string[] xystr = nextPiece.Split(sepchar); @@ -472,7 +348,7 @@ namespace XYPlots if (retval == ' ') { Lbuff.Append('\n'); - retval = NextChar(); + _ = NextChar(); retval = NextChar(); } break; @@ -502,7 +378,6 @@ namespace XYPlots Buff = Buff.Substring(4); } // remove an extra spaces between >< - //Buff = Regex.Replace(Buff, @"[ ]+<", "<"); Buff = Buff.Replace(">\r ", ">\r\n "); Buff = Buff.Replace(">\n ", ">\r\n "); // C2022-003 if RO has symbols Buff = Regex.Replace(Buff, @"[ ]+<", "<"); @@ -544,7 +419,7 @@ namespace XYPlots if (LinesUsed == 0) LinesUsed = (int)(1.5 * CHIGHDOTS); /* adjust for x axis tics */ LinesUsed += printerunits[Y]; - LinesUsed = LinesUsed / CHIGHDOTS; + LinesUsed /= CHIGHDOTS; } private void GetScaleInfo() { @@ -608,11 +483,8 @@ namespace XYPlots Offset[PLOT, Y] = -Scale[PLOT, Y] * Math.Log10(minimum[Y]); } } - private void GetAxisTitle(int flag) - { - AxisTitles[flag] = GetString(); - } - private string stripSuperSub(string instr) + private void GetAxisTitle(int flag) => AxisTitles[flag] = GetString(); + private string stripSuperSub(string instr) { StringBuilder sb = new StringBuilder(instr); sb.Replace(SuperScript[0], ""); @@ -623,24 +495,27 @@ namespace XYPlots } private point DetermineBoxMax(XyBox boxptr) { - point newval = new point(); - newval.xyValue = new int[Dimensions]; - string tmp; + point newval = new point + { + xyValue = new int[Dimensions] + }; + string tmp; int pos = 0, prevPos = 0; - int nl = 0, xmax = 0, ilen = 0; - tmp = stripSuperSub(boxptr.BoxText); + int nl = 0, xmax = 0; + tmp = stripSuperSub(boxptr.BoxText); tmp = tmp.Replace("\r\n", "\n"); - while ((pos = tmp.IndexOf('\n', pos)) > -1) - { - ilen = pos - prevPos; - xmax = Math.Max(xmax, ilen); - // OLD: prevPos = pos; - prevPos = pos + 1; - pos++; - nl++; - } - // OLD: ilen = tmp.Substring(prevPos + 1).Length; - ilen = tmp.Length - prevPos; // tmp.Substring(prevPos).Length; + int ilen; + while ((pos = tmp.IndexOf('\n', pos)) > -1) + { + ilen = pos - prevPos; + xmax = Math.Max(xmax, ilen); + // OLD: prevPos = pos; + prevPos = pos + 1; + pos++; + nl++; + } + // OLD: ilen = tmp.Substring(prevPos + 1).Length; + ilen = tmp.Length - prevPos; // tmp.Substring(prevPos).Length; xmax = Math.Max(xmax, ilen) + 2; newval.xyValue[X] = boxptr.BoxMinimum.xyValue[X] + (xmax * CWIDEDOTS); // OLD: newval.xyValue[Y] = boxptr.BoxMinimum.xyValue[Y] - (nl * CHIGHDOTS) - (int)(30 * ConvertToTwips); @@ -659,11 +534,15 @@ namespace XYPlots NewBox.Shadow = ShadowFlag; ShadowFlag = 0; NewBox.BoxMaximum = DetermineBoxMax(NewBox); - point minPoint = new point(); - minPoint.xyValue = new int[Dimensions]; - point maxPoint = new point(); - maxPoint.xyValue = new int[Dimensions]; - minPoint.xyValue[X] = Origin.xyValue[X]; + point minPoint = new point + { + xyValue = new int[Dimensions] + }; + point maxPoint = new point + { + xyValue = new int[Dimensions] + }; + minPoint.xyValue[X] = Origin.xyValue[X]; minPoint.xyValue[Y] = NewBox.BoxMaximum.xyValue[Y]; maxPoint.xyValue[X] = NewBox.BoxMaximum.xyValue[X]; maxPoint.xyValue[Y] = Origin.xyValue[Y]; @@ -681,9 +560,11 @@ namespace XYPlots pointcount = EndFlag = 0; while (EndFlag == 0) { - DataPoint pl = new DataPoint(); - pl.APoint = new point(); - pl.APoint = GetPair(PLOT); + DataPoint pl = new DataPoint + { + APoint = new point() + }; + pl.APoint = GetPair(PLOT); pointcount++; dataPoints.Add(pl); } @@ -725,7 +606,6 @@ namespace XYPlots DataPoint thispt, prevpt, firstpt; long yval, y1, y3; int PlAryIdx = 0; - int PlAryNumItems = dataPoints.Count; prevpt = dataPoints[PlAryIdx]; PlAryIdx++; thispt = dataPoints[PlAryIdx]; @@ -747,11 +627,13 @@ namespace XYPlots } private void AddAPlot(DataPoints ptr) { - PlotLine NewLine = new PlotLine(); - NewLine.PlotType = LineFlag; - NewLine.PlotDivisions = LineDiv; - NewLine.PlotDataPoints = ptr; - AllPlots.Insert(0, NewLine); + PlotLine NewLine = new PlotLine + { + PlotType = LineFlag, + PlotDivisions = LineDiv, + PlotDataPoints = ptr + }; + AllPlots.Insert(0, NewLine); } private void GenerateGrid(VG.Page pg, IVGOutput vgOutput) { @@ -762,27 +644,14 @@ namespace XYPlots SetPenDiameter(5); BoxRelative(printerunits[X], printerunits[Y], CurPenWidth, pg, vgOutput); if (GridOnFlag == 0) Visible = 0; - //if (vgOutput is VGOut_Graphics) - //{ - DoGrid(X, pg, vgOutput, 1); - DoGrid(Y, pg, vgOutput, 1); - DoGrid(X, pg, vgOutput, 2); - DoGrid(Y, pg, vgOutput, 2); - DoGrid(X, pg, vgOutput, 3); - DoGrid(Y, pg, vgOutput, 3); - //} - //else if (vgOutput is VGOut_C1PDF) - //{ - // DrawDirection = Y; - // DoGrid(X, pg, vgOutput); - // DrawDirection = X; - // DoGrid(Y, pg, vgOutput); - //} + DoGrid(X, pg, vgOutput, 1); + DoGrid(Y, pg, vgOutput, 1); + DoGrid(X, pg, vgOutput, 2); + DoGrid(Y, pg, vgOutput, 2); + DoGrid(X, pg, vgOutput, 3); + DoGrid(Y, pg, vgOutput, 3); Visible = 1; RecallPosition(); - // Draw outline last to overlap any grid lines. - //SetPenDiameter(5); - //BoxRelative(printerunits[X], printerunits[Y], CurPenWidth, pg, vgOutput); } private void DoGrid(int flag, VG.Page pg, IVGOutput vgOutput) { @@ -903,7 +772,7 @@ namespace XYPlots { if (!SubLogValue) DrawGridRelative((int)(-30 * ConvertToTwips), 0, pg, vgOutput); - // OLD: MoveRelative((int)(-(15 + 300 * size / (int)FontPitch) * ConvertToTwips), (int)(-15 * ConvertToTwips)); + MoveRelative((int)(-(14 + 250 * size / (int)FontPitch) * ConvertToTwips), (int)(-16 * ConvertToTwips)); if ((AxisLabel[1]) != 0) { @@ -975,7 +844,7 @@ namespace XYPlots { int tlen; powerstring = string.Format("x10{0}{1}{2}", SuperScript[0], i.ToString(), SuperScript[1]); - valuestring = valuestring + powerstring; + valuestring += powerstring; tlen = SuperScript[0].Length + SuperScript[1].Length; return (powerstring.Length - tlen); } @@ -993,7 +862,9 @@ namespace XYPlots LinesUsed += (3 * CHIGHDOTS); AxisTitles[X] = null; } - if ((AxisTitles[Y] != null) && (len = AxisTitles[Y].Length) > 0) +#pragma warning disable IDE0059 // Unnecessary assignment of a value + //Keeping len = AxisTitles[Y].Length for Debugging + if ((AxisTitles[Y] != null) && (len = AxisTitles[Y].Length) > 0) { if (YLandScape > 0) { @@ -1014,7 +885,8 @@ namespace XYPlots } AxisTitles[Y] = null; } - RecallPosition(); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + RecallPosition(); } private void DoBoxes(VG.Page pg, IVGOutput vgOutput) { @@ -1116,9 +988,11 @@ namespace XYPlots } private point FindModifiedCenter(double rprime, point PtOnArc, double ang) { - point newcenter = new point(); - newcenter.xyValue = new int[Dimensions]; - newcenter.xyValue[X] = (int)(PtOnArc.xyValue[X] - rprime * cos_deg(ang)); + point newcenter = new point + { + xyValue = new int[Dimensions] + }; + newcenter.xyValue[X] = (int)(PtOnArc.xyValue[X] - rprime * cos_deg(ang)); newcenter.xyValue[Y] = (int)(PtOnArc.xyValue[Y] - rprime * sin_deg(ang)); return (newcenter); } @@ -1136,9 +1010,11 @@ namespace XYPlots x2 = pt2.APoint.xyValue[X]; y2 = pt2.APoint.xyValue[Y]; midpt = new DataPoint(); - pt = new point(); - pt.xyValue = new int[Dimensions]; - so = FindSlope(pt1.APoint, pt2.APoint); + pt = new point + { + xyValue = new int[Dimensions] + }; + so = FindSlope(pt1.APoint, pt2.APoint); midpt.slope = (4.0 * so - pt1.slope - pt2.slope) / 2.0; pt.xyValue[X] = x1 + (x2 - x1) / 2; pt.xyValue[Y] = y1 + (y2 - y1) / 2; @@ -1249,9 +1125,11 @@ namespace XYPlots double c1, c2, s1, s2; double t3a, t4a; point cp1, cp2; - t3 = FixAngle(t3a=GetAngle(pt1.slope)); - t4 = FixAngle(t4a=GetAngle(pt2.slope)); - thetaa = GetAngleBetweenPoints(pt1.APoint, pt2.APoint); +#pragma warning disable IDE0059 // Unnecessary assignment of a value - Keeping t3a,t4a for Debugging + t3 = FixAngle(t3a=GetAngle(pt1.slope)); + t4 = FixAngle(t4a=GetAngle(pt2.slope)); +#pragma warning restore IDE0059 // Unnecessary assignment of a value + thetaa = GetAngleBetweenPoints(pt1.APoint, pt2.APoint); if ((t3 - thetaa) * (t4 - thetaa) >= 0.0) { double tprime; @@ -1453,11 +1331,11 @@ namespace XYPlots } private void PrintStackError(string relation, int limit) { - if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. - { - MessageBox.Show(String.Format("Position Stack Pointer {0} {1}", relation, limit.ToString()), "Print Stack Error"); - } - } + if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. + { + MessageBox.Show(String.Format("Position Stack Pointer {0} {1}", relation, limit.ToString()), "Print Stack Error"); + } + } private void SavePosition() { if (stack >= MAX_XY_STACK) PrintStackError(">=", MAX_XY_STACK); @@ -1470,15 +1348,9 @@ namespace XYPlots Position[X] = SavedX[--stack]; Position[Y] = SavedY[stack]; } - private void MoveTo(point pnt) - { - MoveAbsolute(pnt.xyValue[X], pnt.xyValue[Y]); - } - private void DrawTo(point pnt, VG.Page pg, IVGOutput vgOutput) - { - DrawAbsolute(pnt.xyValue[X], pnt.xyValue[Y], pg, vgOutput); - } - private void MoveAbsolute(int ptx, int pty) + private void MoveTo(point pnt) => MoveAbsolute(pnt.xyValue[X], pnt.xyValue[Y]); + private void DrawTo(point pnt, VG.Page pg, IVGOutput vgOutput) => DrawAbsolute(pnt.xyValue[X], pnt.xyValue[Y], pg, vgOutput); + private void MoveAbsolute(int ptx, int pty) { int x, y; x = ptx - Position[X]; @@ -1499,11 +1371,7 @@ namespace XYPlots y = Position[Y] - pty; DrawGridRelative(x, y, pg, vgOutput); } - private void relval(string ptr, int i) - { - ptr = string.Format("+{0}", i.ToString()); - } - private void MoveRelative(int x, int y) + private void MoveRelative(int x, int y) { Position[X] += x; Position[Y] -= y; @@ -1535,7 +1403,6 @@ namespace XYPlots private void DrawArc(double radius, double Sangle, double Eangle, point cp, int x, int y, VG.Page pg, IVGOutput vgOutput) { DebugOutput("r={0} sAngle={1} eAngle={2} cp={3},{4} x={5} y={6}", radius, Sangle, Eangle, cp.xyValue[0], cp.xyValue[1], x, y); - int dx, dy; long radchk; radchk = (long)radius; if (radchk > 72000L) @@ -1543,8 +1410,9 @@ namespace XYPlots DrawAbsolute(x, y, pg, vgOutput); return; } - dx = x - cp.xyValue[X]; //jj - dy = Math.Abs(cp.xyValue[Y] - Position[Y]); //jj + //For Debugging + //int dx = x - cp.xyValue[X]; //jj + //int dy = Math.Abs(cp.xyValue[Y] - Position[Y]); //jj float x1 = cp.xyValue[X] - (float)radius; float y1 = cp.xyValue[Y] - (float)radius; float w1 = (float)radius * 2; @@ -1676,7 +1544,7 @@ namespace XYPlots { if (!BaseLnSettings.blBaseLine) // B2026-056 suppress messages when running baseline. { - MessageBox.Show(msg + "\n" + msg2 + "\n\n This p=Process Will Terminate", "\n## ERROR ## - "); + MessageBox.Show($"{msg}\n{msg2}\n\n This p=Process Will Terminate", "\n## ERROR ## - "); Environment.Exit(255); } } @@ -1733,9 +1601,8 @@ namespace XYPlots else if (wn > DPI / 5) dn = dd / 5; else dn = dd / 2; GenGrid(flag, n - dd, n, dn, wn, lw - 1, val, pg, vgOutput); - wn = 0; - } - val = valn; + } + val = valn; if (flag == Y) val = printerunits[Y] - val; //jj MoveAbsolute((flag == X ? val : 0), (flag == Y ? val : 0)); @@ -1779,15 +1646,9 @@ namespace XYPlots GraphText(tstr.ToString(), pg, vgOutput); RecallPosition(); } - private void FreeBoxList() - { - AllBoxes.Clear(); - } - private void FreeLineList() - { - AllPlots.Clear(); - } - private void Init_Graphic_Vars() + private void FreeBoxList() => AllBoxes.Clear(); + private void FreeLineList() => AllPlots.Clear(); + private void Init_Graphic_Vars() { int i; SavedX = new int[MAX_XY_STACK]; @@ -1854,72 +1715,72 @@ namespace XYPlots // - break up the string (if needed) and change the font pitch // for the text that is to be super/subscripted VG_Text drawText; - string tstr = ""; - int Xpos, Ypos; - int sidx = 0; // beginning of string + int Xpos, Ypos; + int sidx = 0; // beginning of string int idx = 0; // current position in string Xpos = Position[X]; Ypos = Position[Y]; - while (idx < txt.Length) - { - int tidx; - if ((tidx = txt.IndexOf(SuperScript[0], idx)) > -1) - { - // print text up to the superscript - tstr = txt.Substring(sidx, tidx - sidx); - drawText = new VG_Text(Xpos, Ypos, (int)FontPitch, tstr, MyFontFamily, "", "", "", pg); - drawText.Draw(vgOutput); - Xpos += (CWIDEDOTS * tstr.Length); - tidx += SuperScript[0].Length; - idx = tidx; - sidx = idx; - tidx = txt.IndexOf(SuperScript[1], idx); - if (tidx > 0) - { - // switch font pitch, move up some, and print the superscript text - tstr = txt.Substring(sidx, tidx - sidx); - Ypos -= (CHIGHDOTS / 2); // move up half a char heigth - drawText = new VG_Text(Xpos, Ypos, (int)(FontPitch / 2), tstr, MyFontFamily, "", "", "", pg); - drawText.Draw(vgOutput); - Ypos += (CHIGHDOTS / 2); // move back down - Xpos += ((CWIDEDOTS / 2) * tstr.Length); // positon half the width of the string - tidx += SuperScript[1].Length; - idx = tidx; - sidx = idx; - continue; // go back to beginning of while loop - } - } - else if ((tidx = txt.IndexOf(SubScript[0], idx)) > -1) - { - // print text up to the superscript - tstr = txt.Substring(sidx, tidx - sidx); - drawText = new VG_Text(Xpos, Ypos, (int)FontPitch, tstr, MyFontFamily, "", "", "", pg); - drawText.Draw(vgOutput); - Xpos += (CWIDEDOTS * tstr.Length); - tidx += SubScript[0].Length; - idx = tidx; - sidx = idx; - tidx = txt.IndexOf(SubScript[1], idx); - if (tidx > 0) - { - // switch font pitch, move up some, and print the superscript text - tstr = txt.Substring(sidx, tidx - sidx); - drawText = new VG_Text(Xpos, Ypos, (int)(FontPitch / 2), tstr, MyFontFamily, "", "", "", pg); - drawText.Draw(vgOutput); - Xpos += ((CWIDEDOTS / 2) * tstr.Length); // positon half the width of the string - tidx += SubScript[1].Length; - idx = tidx; - sidx = idx; - continue; // go back to beginning of while loop - } - } - else - { - idx++; - } - } // end while + string tstr; + while (idx < txt.Length) + { + int tidx; + if ((tidx = txt.IndexOf(SuperScript[0], idx)) > -1) + { + // print text up to the superscript + tstr = txt.Substring(sidx, tidx - sidx); + drawText = new VG_Text(Xpos, Ypos, (int)FontPitch, tstr, MyFontFamily, "", "", "", pg); + drawText.Draw(vgOutput); + Xpos += (CWIDEDOTS * tstr.Length); + tidx += SuperScript[0].Length; + idx = tidx; + sidx = idx; + tidx = txt.IndexOf(SuperScript[1], idx); + if (tidx > 0) + { + // switch font pitch, move up some, and print the superscript text + tstr = txt.Substring(sidx, tidx - sidx); + Ypos -= (CHIGHDOTS / 2); // move up half a char heigth + drawText = new VG_Text(Xpos, Ypos, (int)(FontPitch / 2), tstr, MyFontFamily, "", "", "", pg); + drawText.Draw(vgOutput); + Ypos += (CHIGHDOTS / 2); // move back down + Xpos += ((CWIDEDOTS / 2) * tstr.Length); // positon half the width of the string + tidx += SuperScript[1].Length; + idx = tidx; + sidx = idx; + continue; // go back to beginning of while loop + } + } + else if ((tidx = txt.IndexOf(SubScript[0], idx)) > -1) + { + // print text up to the superscript + tstr = txt.Substring(sidx, tidx - sidx); + drawText = new VG_Text(Xpos, Ypos, (int)FontPitch, tstr, MyFontFamily, "", "", "", pg); + drawText.Draw(vgOutput); + Xpos += (CWIDEDOTS * tstr.Length); + tidx += SubScript[0].Length; + idx = tidx; + sidx = idx; + tidx = txt.IndexOf(SubScript[1], idx); + if (tidx > 0) + { + // switch font pitch, move up some, and print the superscript text + tstr = txt.Substring(sidx, tidx - sidx); + drawText = new VG_Text(Xpos, Ypos, (int)(FontPitch / 2), tstr, MyFontFamily, "", "", "", pg); + drawText.Draw(vgOutput); + Xpos += ((CWIDEDOTS / 2) * tstr.Length); // positon half the width of the string + tidx += SubScript[1].Length; + idx = tidx; + sidx = idx; + continue; // go back to beginning of while loop + } + } + else + { + idx++; + } + } // end while - if (sidx < txt.Length) + if (sidx < txt.Length) { tstr = txt.Substring(sidx); drawText = new VG_Text(Xpos, Ypos, (int)FontPitch, tstr, MyFontFamily, "", "", "", pg); @@ -1942,19 +1803,10 @@ namespace XYPlots //VG.VG_Arc.iColor = 0; //#endif } - private int _OffsetX = 0; - public int OffsetX - { - get { return _OffsetX; } - set { _OffsetX = value; } - } - private int _OffsetY = 0; - public int OffsetY - { - get { return _OffsetY; } - set { _OffsetY = value; } - } - public void Setup() + + public int OffsetX { get; set; } = 0; + public int OffsetY { get; set; } = 0; + public void Setup() { char Command, PrevCommand = ' '; Init_Graphic_Vars(); @@ -2037,13 +1889,15 @@ namespace XYPlots step = "FreeLineList";FreeLineList(); step = "CloseGraph";CloseGraph(); } - catch (Exception ex) + catch (Exception) { _MyLog.WarnFormat("X/Y Plot Error - {0} - {1} - {2}", step, XYPlotIssue ?? "Unknown Issue"); throw new Exception(String.Format("X/Y Plot Error - {0} - {1}",step,XYPlotIssue ?? "Unknown Issue")); } } - private void ShowPoints(DataPoints dataPoints) + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Kept for Debugging")] + private void ShowPoints(DataPoints dataPoints) { //#if DEBUG //foreach (DataPoint pl in dataPoints) @@ -2053,7 +1907,8 @@ namespace XYPlots //#endif } public static string Key = ""; - private void DebugOutput(string format, params object[] args) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping args for future use/Debugging")] + private void DebugOutput(string format, params object[] args) { //#if DEBUG //if (args.Length == 0) @@ -2061,7 +1916,8 @@ namespace XYPlots //Console.WriteLine(format, args); //#endif } - private void DebugShowLocation(string command) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping command for Debugging")] + private void DebugShowLocation(string command) { //Console.WriteLine("'{0}',{1},{2}", command, Position[X], Position[Y]); } diff --git a/PROMS/XYPlots/XYPlots.csproj b/PROMS/XYPlots/XYPlots.csproj index b94ba2be..7b3edae8 100644 --- a/PROMS/XYPlots/XYPlots.csproj +++ b/PROMS/XYPlots/XYPlots.csproj @@ -161,6 +161,7 @@ frmXYPlot.cs + Code diff --git a/PROMS/XYPlots/frmXYPlot.cs b/PROMS/XYPlots/frmXYPlot.cs index 461fed05..3263a356 100644 --- a/PROMS/XYPlots/frmXYPlot.cs +++ b/PROMS/XYPlots/frmXYPlot.cs @@ -1,24 +1,15 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Diagnostics; using System.Drawing; -using System.Drawing.Imaging; -using System.Drawing.Printing; -using System.IO; -using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using VG; -//using XYPlots; namespace XYPlots { public partial class frmXYPlot : Form { - private string _XYPlot; - private string _Title; + private readonly string _XYPlot; + private readonly string _Title; public frmXYPlot(string title,string xyPlot) { InitializeComponent();