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..30b890e5 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; } @@ -364,14 +313,12 @@ 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; @@ -407,14 +354,12 @@ 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; @@ -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; @@ -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; 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..b87ab97e 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; } @@ -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 7c8f36c5..aec5e2bb 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}", 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}", 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}", 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..4d9fdbaf 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,14 +21,10 @@ namespace VEPROMS.CSLA.Library [Serializable()] protected class DocIDCriteria { - private int _DocID; - public int DocID - { get { return _DocID; } } - public DocIDCriteria(int docID) - { - _DocID = docID; - } - } + private readonly int _DocID; + public int DocID => _DocID; + public DocIDCriteria(int docID) => _DocID = docID; + } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(DocIDCriteria criteria) { @@ -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);