// ======================================================================== // Copyright 2007 - Volian Enterprises, Inc. All rights reserved. // Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE // ------------------------------------------------------------------------ // $Workfile: $ $Revision: $ // $Author: $ $Date: $ // // $History: $ // ======================================================================== using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; namespace VEPROMS.CSLA.Library { /// /// Item Generated by MyGeneration using the CSLA Object Mapping template /// [Serializable()] [TypeConverter(typeof(ItemConverter))] public partial class Item : BusinessBase, IDisposable, IVEHasBrokenRules { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Refresh private List _RefreshItems = new List(); private List _RefreshItemAnnotations = new List(); private List _RefreshItemDocVersions = new List(); private List _RefreshItemParts = new List(); private List _RefreshItemTransitions_RangeID = new List(); private List _RefreshItemTransitions_ToID = new List(); private void AddToRefreshList(List refreshItems, List refreshItemAnnotations, List refreshItemDocVersions, List refreshItemParts, List refreshItemTransitions_RangeID, List refreshItemTransitions_ToID) { if (IsDirty) refreshItems.Add(this); if (_ItemAnnotations != null && _ItemAnnotations.IsDirty) { foreach (ItemAnnotation tmp in _ItemAnnotations) { if (tmp.IsDirty) refreshItemAnnotations.Add(tmp); } } if (_ItemDocVersions != null && _ItemDocVersions.IsDirty) { foreach (ItemDocVersion tmp in _ItemDocVersions) { if (tmp.IsDirty) refreshItemDocVersions.Add(tmp); } } if (_NextItems != null && _NextItems.IsDirty) { foreach (Item tmp in _NextItems) { tmp.AddToRefreshList(refreshItems, refreshItemAnnotations, refreshItemDocVersions, refreshItemParts, refreshItemTransitions_RangeID, refreshItemTransitions_ToID); } } if (_ItemParts != null && _ItemParts.IsDirty) { foreach (ItemPart tmp in _ItemParts) { if (tmp.IsDirty) refreshItemParts.Add(tmp); } } if (_ItemTransitions_RangeID != null && _ItemTransitions_RangeID.IsDirty) { foreach (ItemTransition_RangeID tmp in _ItemTransitions_RangeID) { if (tmp.IsDirty) refreshItemTransitions_RangeID.Add(tmp); } } if (_ItemTransitions_ToID != null && _ItemTransitions_ToID.IsDirty) { foreach (ItemTransition_ToID tmp in _ItemTransitions_ToID) { if (tmp.IsDirty) refreshItemTransitions_ToID.Add(tmp); } } } private void ClearRefreshList() { _RefreshItems = new List(); _RefreshItemAnnotations = new List(); _RefreshItemDocVersions = new List(); _RefreshItemParts = new List(); _RefreshItemTransitions_RangeID = new List(); _RefreshItemTransitions_ToID = new List(); } private void BuildRefreshList() { ClearRefreshList(); AddToRefreshList(_RefreshItems, _RefreshItemAnnotations, _RefreshItemDocVersions, _RefreshItemParts, _RefreshItemTransitions_RangeID, _RefreshItemTransitions_ToID); } private void ProcessRefreshList() { foreach (Item tmp in _RefreshItems) { if (tmp._MyContent != null) { ContentInfo.Refresh(tmp._MyContent); if (tmp._MyContent?.MyImage != null) ImageInfo.Refresh(tmp._MyContent.MyImage); } ItemInfo.Refresh(tmp); } foreach (ItemAnnotation tmp in _RefreshItemAnnotations) { AnnotationInfo.Refresh(tmp); } foreach (ItemDocVersion tmp in _RefreshItemDocVersions) { DocVersionInfo.Refresh(tmp); } foreach (ItemPart tmp in _RefreshItemParts) { PartInfo.Refresh(tmp); } foreach (ItemTransition_RangeID tmp in _RefreshItemTransitions_RangeID) { TransitionInfo.Refresh(tmp); } foreach (ItemTransition_ToID tmp in _RefreshItemTransitions_ToID) { TransitionInfo.Refresh(tmp); } ClearRefreshList(); } #endregion #region Collection [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static List _CacheList = new List(); protected static void AddToCache(Item item) { if (!_CacheList.Contains(item)) _CacheList.Add(item); // In AddToCache } protected static void RemoveFromCache(Item item) { while (_CacheList.Contains(item)) _CacheList.Remove(item); // In RemoveFromCache } [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Item(s) from temporary _CacheList to _CacheByPrimaryKey { Item tmp = _CacheList[0]; // Get the first Item string pKey = tmp.ItemID.ToString(); if (!_CacheByPrimaryKey.ContainsKey(pKey)) { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey } _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheList.RemoveAt(0); // Remove the first Item } } protected static Item GetCachedByPrimaryKey(int itemID) { ConvertListToDictionary(); string key = itemID.ToString(); if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage => _ErrorMessage; private static int _nextItemID = -1; public static int NextItemID => _nextItemID--; private int _ItemID; [System.ComponentModel.DataObjectField(true, true)] public int ItemID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ItemID; } } private int? _PreviousID; public int? PreviousID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyPrevious != null) _PreviousID = _MyPrevious.ItemID; return _PreviousID; } } private Item _MyPrevious; public Item MyPrevious { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyPrevious == null && _PreviousID != null) _MyPrevious = Item.Get((int)_PreviousID); return _MyPrevious; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if ((_MyPrevious == null ? _PreviousID : (int?)_MyPrevious.ItemID) != (value == null ? null : (int?)value.ItemID)) { _MyPrevious = value; _PreviousID = (value == null ? null : (int?)value.ItemID); PropertyHasChanged(); } } } private int _ContentID; public int ContentID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyContent != null) _ContentID = _MyContent.ContentID; return _ContentID; } } private Content _MyContent; public Content MyContent { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyContent == null && _ContentID != 0) _MyContent = Content.Get(_ContentID); return _MyContent; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_MyContent != value) { _MyContent = value; _ContentID = value.ContentID;// Update underlying data field PropertyHasChanged(); } } } private DateTime _DTS = new DateTime(); public DateTime DTS { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _DTS; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_DTS != value) { _DTS = value; PropertyHasChanged(); } } } private string _UserID = string.Empty; public string UserID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _UserID; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_UserID != value) { _UserID = value; PropertyHasChanged(); } } } private byte[] _LastChanged = new byte[8];//timestamp private int _ItemAnnotationCount = 0; /// /// Count of ItemAnnotations for this Item /// public int ItemAnnotationCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ItemAnnotationCount; } } private ItemAnnotations _ItemAnnotations = null; /// /// Related Field /// [TypeConverter(typeof(ItemAnnotationsConverter))] public ItemAnnotations ItemAnnotations { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_ItemAnnotationCount < 0 || (_ItemAnnotationCount > 0 && _ItemAnnotations == null)) _ItemAnnotations = ItemAnnotations.GetByItemID(ItemID); if (_ItemAnnotationCount < 0) _ItemAnnotationCount = _ItemAnnotations == null ? 0 : _ItemAnnotations.Count; if (_ItemAnnotations == null) _ItemAnnotations = ItemAnnotations.New(); return _ItemAnnotations; } } public void Reset_ItemAnnotations() => _ItemAnnotationCount = -1; private int _ItemDocVersionCount = 0; /// /// Count of ItemDocVersions for this Item /// public int ItemDocVersionCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ItemDocVersionCount; } } private ItemDocVersions _ItemDocVersions = null; /// /// Related Field /// [TypeConverter(typeof(ItemDocVersionsConverter))] public ItemDocVersions ItemDocVersions { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_ItemDocVersionCount < 0 || (_ItemDocVersionCount > 0 && _ItemDocVersions == null)) _ItemDocVersions = ItemDocVersions.GetByItemID(ItemID); if (_ItemDocVersionCount < 0) _ItemDocVersionCount = _ItemDocVersions == null ? 0 : _ItemDocVersions.Count; if (_ItemDocVersions == null) _ItemDocVersions = ItemDocVersions.New(); return _ItemDocVersions; } } public void Reset_ItemDocVersions() => _ItemDocVersionCount = -1; private int _NextItemCount = 0; /// /// Count of NextItems for this Item /// public int NextItemCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _NextItemCount; } } private NextItems _NextItems = null; /// /// Related Field /// [TypeConverter(typeof(NextItemsConverter))] public NextItems NextItems { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_NextItemCount < 0 || (_NextItemCount > 0 && _NextItems == null)) _NextItems = NextItems.GetByPreviousID(ItemID); if (_NextItemCount < 0) _NextItemCount = _NextItems == null ? 0 : _NextItems.Count; if (_NextItems == null) _NextItems = NextItems.New(); return _NextItems; } } public void Reset_NextItems() => _NextItemCount = -1; private int _ItemPartCount = 0; /// /// Count of ItemParts for this Item /// public int ItemPartCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ItemPartCount; } } private ItemParts _ItemParts = null; /// /// Related Field /// [TypeConverter(typeof(ItemPartsConverter))] public ItemParts ItemParts { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_ItemPartCount < 0 || (_ItemPartCount > 0 && _ItemParts == null)) _ItemParts = ItemParts.GetByItemID(ItemID); if (_ItemPartCount < 0) _ItemPartCount = _ItemParts == null ? 0 : _ItemParts.Count; if (_ItemParts == null) _ItemParts = ItemParts.New(); return _ItemParts; } } public void Reset_ItemParts() => _ItemPartCount = -1; private int _ItemTransition_RangeIDCount = 0; /// /// Count of ItemTransitions for this Item /// public int ItemTransition_RangeIDCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ItemTransition_RangeIDCount; } } private ItemTransitions_RangeID _ItemTransitions_RangeID = null; /// /// Related Field /// [TypeConverter(typeof(ItemTransitions_RangeIDConverter))] public ItemTransitions_RangeID ItemTransitions_RangeID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_ItemTransition_RangeIDCount < 0 || (_ItemTransition_RangeIDCount > 0 && _ItemTransitions_RangeID == null)) _ItemTransitions_RangeID = ItemTransitions_RangeID.GetByRangeID(ItemID); if (_ItemTransition_RangeIDCount < 0) _ItemTransition_RangeIDCount = _ItemTransitions_RangeID == null ? 0 : _ItemTransitions_RangeID.Count; if (_ItemTransitions_RangeID == null) _ItemTransitions_RangeID = ItemTransitions_RangeID.New(); return _ItemTransitions_RangeID; } } public void Reset_ItemTransitions_RangeID() => _ItemTransition_RangeIDCount = -1; private int _ItemTransition_ToIDCount = 0; /// /// Count of ItemTransitions for this Item /// public int ItemTransition_ToIDCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ItemTransition_ToIDCount; } } private ItemTransitions_ToID _ItemTransitions_ToID = null; /// /// Related Field /// [TypeConverter(typeof(ItemTransitions_ToIDConverter))] public ItemTransitions_ToID ItemTransitions_ToID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_ItemTransition_ToIDCount < 0 || (_ItemTransition_ToIDCount > 0 && _ItemTransitions_ToID == null)) _ItemTransitions_ToID = ItemTransitions_ToID.GetByToID(ItemID); if (_ItemTransition_ToIDCount < 0) _ItemTransition_ToIDCount = _ItemTransitions_ToID == null ? 0 : _ItemTransitions_ToID.Count; if (_ItemTransitions_ToID == null) _ItemTransitions_ToID = ItemTransitions_ToID.New(); return _ItemTransitions_ToID; } } public void Reset_ItemTransitions_ToID() => _ItemTransition_ToIDCount = -1; public override bool IsDirty { get { if (base.IsDirty) return true; return IsDirtyList(new List()); } } public bool IsDirtyList(List list) { if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); return base.IsDirty || (_ItemAnnotations != null && _ItemAnnotations.IsDirtyList(list)) || (_ItemDocVersions != null && _ItemDocVersions.IsDirtyList(list)) || (_NextItems != null && _NextItems.IsDirtyList(list)) || (_ItemParts != null && _ItemParts.IsDirtyList(list)) || (_ItemTransitions_RangeID != null && _ItemTransitions_RangeID.IsDirtyList(list)) || (_ItemTransitions_ToID != null && _ItemTransitions_ToID.IsDirtyList(list)) || (_MyContent != null && _MyContent.IsDirtyList(list)); } public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) return (IsNew && !IsDirty) || base.IsValid; list.Add(this); return ((IsNew && !IsDirty) || base.IsValid) && (_ItemAnnotations == null || _ItemAnnotations.IsValidList(list)) && (_ItemDocVersions == null || _ItemDocVersions.IsValidList(list)) && (_NextItems == null || _NextItems.IsValidList(list)) && (_ItemParts == null || _ItemParts.IsValidList(list)) && (_ItemTransitions_RangeID == null || _ItemTransitions_RangeID.IsValidList(list)) && (_ItemTransitions_ToID == null || _ItemTransitions_ToID.IsValidList(list)) && (_MyContent == null || _MyContent.IsValidList(list)); } // CSLATODO: Check Item.GetIdValue to assure that the ID returned is unique /// /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// /// A Unique ID for the current Item protected override object GetIdValue() => MyItemUnique; // Absolutely Unique ID #endregion #region ValidationRules [NonSerialized] private bool _CheckingBrokenRules = false; public IVEHasBrokenRules HasBrokenRules { get { if (_CheckingBrokenRules) return null; if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this; try { _CheckingBrokenRules = true; IVEHasBrokenRules hasBrokenRules = null; if (_ItemAnnotations != null && (hasBrokenRules = _ItemAnnotations.HasBrokenRules) != null) return hasBrokenRules; if (_ItemDocVersions != null && (hasBrokenRules = _ItemDocVersions.HasBrokenRules) != null) return hasBrokenRules; if (_NextItems != null && (hasBrokenRules = _NextItems.HasBrokenRules) != null) return hasBrokenRules; if (_ItemParts != null && (hasBrokenRules = _ItemParts.HasBrokenRules) != null) return hasBrokenRules; if (_ItemTransitions_RangeID != null && (hasBrokenRules = _ItemTransitions_RangeID.HasBrokenRules) != null) return hasBrokenRules; if (_ItemTransitions_ToID != null && (hasBrokenRules = _ItemTransitions_ToID.HasBrokenRules) != null) return hasBrokenRules; if (_MyContent != null && (hasBrokenRules = _MyContent.HasBrokenRules) != null) return hasBrokenRules; return hasBrokenRules; } finally { _CheckingBrokenRules = false; } } } public BrokenRulesCollection BrokenRules { get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (Equals(hasBrokenRules)) return BrokenRulesCollection; return hasBrokenRules?.BrokenRules; } } protected override void AddBusinessRules() { ValidationRules.AddRule(MyContentRequired, "MyContent"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "UserID"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); //ValidationRules.AddDependantProperty("x", "y"); _ItemExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _ItemExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: Add other validation rules } private static bool MyContentRequired(Item target, Csla.Validation.RuleArgs e) { if (target._ContentID == 0 && target._MyContent == null) // Required field missing { e.Description = "Required"; return false; } return true; } #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields _ItemExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //CSLATODO: Who can read/write which fields _ItemExtension.AddInstanceAuthorizationRules(AuthorizationRules); } #endregion #region Factory Methods public int CurrentEditLevel => EditLevel; private static int _ItemUnique = 0; protected static int ItemUnique => ++_ItemUnique; private readonly int _MyItemUnique = ItemUnique; // Absolutely Unique ID - Editable public int MyItemUnique => _MyItemUnique; protected Item() {/* require use of factory methods */ AddToCache(this); } private bool _Disposed = false; private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; private static int IncrementCountCreated => ++_CountCreated; private readonly int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated; public static int CountNotDisposed => _CountCreated - _CountDisposed; public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Item() { _CountFinalized++; } private bool _DisposeOfContent = true; // part B2017-060 when Item is in a Using statement, the content was being freed after it's use, we needed the content to stick around public bool DisposeOfContent { get { return _DisposeOfContent; } set { _DisposeOfContent = value; } } public void Dispose() { if (_Disposed) return; _CountDisposed++; _Disposed = true; RemoveFromDictionaries(); if (_MyContent != null && DisposeOfContent) { _MyContent.Dispose(); _MyContent = null; } if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID = null; if (_ItemTransitions_ToID != null) _ItemTransitions_ToID = null; } private void RemoveFromDictionaries() { RemoveFromCache(this); if (_CacheByPrimaryKey.ContainsKey(ItemID.ToString())) { List listItem = _CacheByPrimaryKey[ItemID.ToString()]; // Get the list of items while (listItem.Contains(this)) listItem.Remove(this); // Remove the item from the list if (listItem.Count == 0) //If there are no items left in the list _CacheByPrimaryKey.Remove(ItemID.ToString()); // remove the list } } public static Item New() { try { return DataPortal.Create(); } catch (Exception ex) { throw new DbCslaException("Error on Item.New", ex); } } public static Item New(Content myContent) { Item tmp = Item.New(); tmp.MyContent = myContent; return tmp; } public static Item New(Item myPrevious, Content myContent, DateTime dts, string userID) { Item tmp = Item.New(); tmp.MyPrevious = myPrevious; tmp.MyContent = myContent; tmp.DTS = dts; tmp.UserID = userID; return tmp; } public static Item MakeItem(Item myPrevious, Content myContent, DateTime dts, string userID) { Item tmp = Item.New(myPrevious, myContent, dts, userID); if (tmp.IsSavable) tmp = tmp.Save(); else { Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; } } return tmp; } public static Item New(Item myPrevious, Content myContent) { Item tmp = Item.New(); tmp.MyPrevious = myPrevious; tmp.MyContent = myContent; return tmp; } public static Item MakeItem(Item myPrevious, Content myContent) { Item tmp = Item.New(myPrevious, myContent); if (tmp.IsSavable) tmp = tmp.Save(); else { Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; } } return tmp; } public static Item Get(int itemID) { try { Item tmp = GetCachedByPrimaryKey(itemID); if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(itemID)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Item tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Item.Get", ex); } } public static Item Get(SafeDataReader dr, Item previous) { if (dr.Read()) return new Item(dr, previous); return null; } internal Item(SafeDataReader dr) => ReadData(dr); [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] private Item(SafeDataReader dr, Item previous) { ReadData(dr); MarkAsChild(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal Item(SafeDataReader dr, int parentID) { ReadData(dr); MarkAsChild(); } public static void Delete(int itemID) { try { DataPortal.Delete(new PKCriteria(itemID)); } catch (Exception ex) { throw new DbCslaException("Error on Item.Delete", ex); } } public override Item Save() { try { BuildRefreshList(); Item item = base.Save(); RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(item);//Refresh the item in AllList ProcessRefreshList(); return item; } catch (Exception ex) { throw new DbCslaException("Error on CSLA Save", ex); } } #endregion #region Data Access Portal [Serializable()] protected class PKCriteria { private readonly int _ItemID; public int ItemID => _ItemID; public PKCriteria(int itemID) => _ItemID = itemID; } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { _ItemID = NextItemID; // Database Defaults _DTS = _ItemExtension.DefaultDTS; _UserID = _ItemExtension.DefaultUserID; // CSLATODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.ReadData", GetHashCode()); try { _ItemID = dr.GetInt32("ItemID"); _PreviousID = (int?)dr.GetValue("PreviousID"); _ContentID = dr.GetInt32("ContentID"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); _ItemAnnotationCount = dr.GetInt32("AnnotationCount"); _ItemDocVersionCount = dr.GetInt32("DocVersionCount"); _NextItemCount = dr.GetInt32("NextCount"); _ItemPartCount = dr.GetInt32("PartCount"); _ItemTransition_RangeIDCount = dr.GetInt32("Transition_RangeIDCount"); _ItemTransition_ToIDCount = dr.GetInt32("Transition_ToIDCount"); MarkOld(); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Item.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.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 = "getItem"; cm.Parameters.AddWithValue("@ItemID", criteria.ItemID); cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); // load child objects dr.NextResult(); _ItemAnnotations = ItemAnnotations.Get(dr); // load child objects dr.NextResult(); _ItemDocVersions = ItemDocVersions.Get(dr); // load child objects dr.NextResult(); _ItemParts = ItemParts.Get(dr); // load child objects dr.NextResult(); _ItemTransitions_RangeID = ItemTransitions_RangeID.Get(dr); // load child objects dr.NextResult(); _ItemTransitions_ToID = ItemTransitions_ToID.Get(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("Item.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Item.DataPortal_Fetch", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; SQLInsert(); // 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("Item.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Item.DataPortal_Insert", ex); } finally { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Insert", GetHashCode()); } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLInsert() { if (!IsDirty) return; try { _MyContent?.Update(); using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addItem"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@PreviousID", PreviousID); cm.Parameters.AddWithValue("@ContentID", ContentID); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); // Output Calculated Columns SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_ItemID); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure _ItemID = (int)cm.Parameters["@newItemID"].Value; _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } } MarkOld(); // update child objects _ItemAnnotations?.Update(this); _ItemDocVersions?.Update(this); _NextItems?.Update(this); _ItemParts?.Update(this); _ItemTransitions_RangeID?.Update(this); _ItemTransitions_ToID?.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.SQLInsert", GetHashCode()); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Item.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, ref int itemID, Item myPrevious, Content myContent, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addItem"; // Input All Fields - Except Calculated Columns if (myPrevious != null) cm.Parameters.AddWithValue("@PreviousID", myPrevious.ItemID); cm.Parameters.AddWithValue("@ContentID", myContent.ContentID); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_ItemID); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure itemID = (int)cm.Parameters["@newItemID"].Value; return (byte[])cm.Parameters["@newLastChanged"].Value; } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.Add", ex); throw new DbCslaException("Item.Add", ex); } } public static void DeactivateStateDisplayTabTmp(string UserID) { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { try { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "DeactivateStateDisplayTabTmp"; cm.CommandTimeout = Database.DefaultTimeout; cm.Parameters.AddWithValue("@UserID", UserID); cm.ExecuteNonQuery(); } catch (Exception ex) { Database.LogException("ItemExt.DeactivateStateDisplayTabTmp", ex); } } } } public static void AddDisplayTabsState(int itemID, string displayTabID, string displayTabName, string UserID, int order) //private void DataPortal_Fetch(int itemID, string displayTabID, string displayTabName) { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { try { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "AddDisplayTabState"; cm.CommandTimeout = Database.DefaultTimeout; cm.Parameters.AddWithValue("@ItemID", itemID); cm.Parameters.AddWithValue("@displayTabID", displayTabID); cm.Parameters.AddWithValue("@displayTabName", displayTabName); cm.Parameters.AddWithValue("@UserID", UserID); cm.Parameters.AddWithValue("@order", order); cm.ExecuteNonQuery(); } catch (Exception ex) { Database.LogException("ItemExt.AddDisplayTabsState", ex); } } } } public static DataTable GetDisplayTabs(string UserID) //, string displayTabID, string displayTabName) //public static void DeactivateStateDisplayTabTmp(string UserID) { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { try { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "GetDisplayTabdata"; cm.CommandTimeout = Database.DefaultTimeout; cm.Parameters.AddWithValue("@UserID", UserID); SqlDataAdapter da = new SqlDataAdapter(cm); SqlDataReader reader = cm.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(reader); return dt; } catch (Exception) { //B2025-004 //if it fails loading previously open tabs, simply treat it as if no tabs were open //instead of crashing return new DataTable(); } } } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Update", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; SQLUpdate(); // 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("Item.DataPortal_Update", ex); _ErrorMessage = ex.Message; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.SQLUpdate", GetHashCode()); try { _MyContent?.Update(); using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) { if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updateItem"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@ItemID", _ItemID); cm.Parameters.AddWithValue("@PreviousID", PreviousID); cm.Parameters.AddWithValue("@ContentID", ContentID); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@LastChanged", _LastChanged); // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } } } MarkOld(); // use the open connection to update child objects _ItemAnnotations?.Update(this); _ItemDocVersions?.Update(this); _NextItems?.Update(this); _ItemParts?.Update(this); _ItemTransitions_RangeID?.Update(this); _ItemTransitions_ToID?.Update(this); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.SQLUpdate", ex); _ErrorMessage = ex.Message; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } internal void Update() { if (!IsDirty) return; if (base.IsDirty) { using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) { if (IsNew) _LastChanged = Item.Add(cn, ref _ItemID, _MyPrevious, _MyContent, _DTS, _UserID); else _LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, _ContentID, _DTS, _UserID, ref _LastChanged); } MarkOld(); } _ItemAnnotations?.Update(this); _ItemDocVersions?.Update(this); _NextItems?.Update(this); _ItemParts?.Update(this); _ItemTransitions_RangeID?.Update(this); _ItemTransitions_ToID?.Update(this); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")] internal void DeleteSelf(Item item) { // if we're not dirty then don't update the database if (!IsDirty) return; // if we're new then don't update the database if (IsNew) return; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) { Item.Remove(cn, _ItemID); } MarkNew(); } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, ref int itemID, int? previousID, int contentID, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updateItem"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ItemID", itemID); cm.Parameters.AddWithValue("@PreviousID", previousID); cm.Parameters.AddWithValue("@ContentID", contentID); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@LastChanged", lastChanged); // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure return (byte[])cm.Parameters["@newLastChanged"].Value; } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.Update", ex); throw new DbCslaException("Item.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ItemID)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "deleteItem"; cm.Parameters.AddWithValue("@ItemID", criteria.ItemID); cm.ExecuteNonQuery(); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Item.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int itemID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "deleteItem"; // Input PK Fields cm.Parameters.AddWithValue("@ItemID", itemID); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.Remove", ex); throw new DbCslaException("Item.Remove", ex); } } #endregion #region Exists public static bool Exists(int itemID) { ExistsCommand result; try { result = DataPortal.Execute(new ExistsCommand(itemID)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on Item.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private readonly int _ItemID; private bool _exists; public bool Exists => _exists; public ExistsCommand(int itemID) => _ItemID = itemID; protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "existsItem"; cm.Parameters.AddWithValue("@ItemID", _ItemID); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.DataPortal_Execute", ex); throw new DbCslaException("Item.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension readonly ItemExtension _ItemExtension = new ItemExtension(); [Serializable()] partial class ItemExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual DateTime DefaultDTS => DateTime.Now; public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID; // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } // Instance Authorization Rules public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } // Validation Rules public virtual void AddValidationRules(Csla.Validation.ValidationRules rules) { // Needs to be overriden to add new validation rules } // InstanceValidation Rules public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) { // Needs to be overriden to add new validation rules } } #endregion } // Class #region Converter internal class ItemConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is Item myitem) { // Return the ToString value return myitem.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace