// ========================================================================
// 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.Configuration;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using Volian.Base.Library;
namespace VEPROMS.CSLA.Library
{
    public delegate void ItemInfoEvent(object sender);
    /// 
    ///	ItemInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(ItemInfoConverter))]
    public partial class ItemInfo : ReadOnlyBase, IDisposable
    {
        public event ItemInfoEvent Changed;
        private void OnChange()
        {
            if (Changed != null) Changed(this);
        }
        #region Log4Net
        private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion
        #region Collection
        private static List _CacheList = new List();
        protected static void AddToCache(ItemInfo itemInfo)
        {
            if (!_CacheList.Contains(itemInfo))
                _CacheList.Add(itemInfo); // In AddToCache
                                          //try
                                          //{
                                          //  _CacheList.Add(itemInfo); // In AddToCache
                                          //}
                                          //catch (Exception ex)
                                          //{
                                          //  _MyLog.ErrorFormat("ItemInfo {0}.{1} already exists in the cache", itemInfo.ItemID, itemInfo.MyItemInfoUnique);
                                          //}
        }
        protected static void RemoveFromCache(ItemInfo itemInfo)
        {
            while (_CacheList.Contains(itemInfo)) _CacheList.Remove(itemInfo); // In RemoveFromCache
        }
        protected static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        protected static void ConvertListToDictionary()
        {
            while (_CacheList.Count > 0) // Move ItemInfo(s) from temporary _CacheList to _CacheByPrimaryKey
            {
                ItemInfo tmp = _CacheList[0]; // Get the first ItemInfo
                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 ItemInfo
            }
        }
        internal static void AddList(ItemInfoList lst)
        {
            foreach (ItemInfo item in lst) AddToCache(item);
        }
        protected static ItemInfo 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
        {
            get { return _ErrorMessage; }
        }
        protected Item _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        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 ItemInfo _MyPrevious;
        public ItemInfo MyPrevious
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyPrevious == null && _PreviousID != null)
                {
                    if (this is ProcedureInfo)
                        _MyPrevious = ProcedureInfo.Get((int)_PreviousID);
                    else if (this is SectionInfo)
                        _MyPrevious = SectionInfo.Get((int)_PreviousID);
                    else if (this is StepInfo)
                        _MyPrevious = StepInfo.Get((int)_PreviousID);
                    else
                        _MyPrevious = ItemInfo.Get((int)_PreviousID);
                }
                return _MyPrevious;
            }
            set
            {
                _MyPrevious = value;
            }
        }
        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 ContentInfo _MyContent;
        public ContentInfo MyContent
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyContent == null && _ContentID != 0) _MyContent = ContentInfo.Get(_ContentID);
                return _MyContent;
            }
        }
        private DateTime _DTS = new DateTime();
        public DateTime DTS
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DTS;
            }
        }
        private string _UserID = string.Empty;
        public string UserID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _UserID;
            }
        }
        private int _ItemAnnotationCount = 0;
        /// 
        /// Count of ItemAnnotations for this Item
        /// 
        public int ItemAnnotationCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemAnnotationCount < 0)
                    _ItemAnnotationCount = ItemAnnotations.Count;
                return _ItemAnnotationCount;
            }
        }
        private AnnotationInfoList _ItemAnnotations = null;
        [TypeConverter(typeof(AnnotationInfoListConverter))]
        public AnnotationInfoList ItemAnnotations
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemAnnotationCount < 0 || (_ItemAnnotationCount > 0 && _ItemAnnotations == null))
                    _ItemAnnotations = AnnotationInfoList.GetByItemID(_ItemID);
                if (_ItemAnnotationCount < 0)
                    _ItemAnnotationCount = _ItemAnnotations.Count;
                return _ItemAnnotations;
            }
        }
        public void RefreshItemAnnotations()
        {
            _ItemAnnotationCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemAnnotationCount = -1; // This will cause the data to be requeried
        }
        private int _ItemDocVersionCount = 0;
        /// 
        /// Count of ItemDocVersions for this Item
        /// 
        public int ItemDocVersionCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemDocVersionCount < 0)
                    _ItemDocVersionCount = ItemDocVersions.Count;
                return _ItemDocVersionCount;
            }
        }
        private DocVersionInfoList _ItemDocVersions = null;
        [TypeConverter(typeof(DocVersionInfoListConverter))]
        public DocVersionInfoList ItemDocVersions
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemDocVersionCount < 0 || (_ItemDocVersionCount > 0 && _ItemDocVersions == null))
                    _ItemDocVersions = DocVersionInfoList.GetByItemID(_ItemID);
                if (_ItemDocVersionCount < 0)
                    _ItemDocVersionCount = _ItemDocVersions.Count;
                return _ItemDocVersions;
            }
        }
        public void RefreshItemDocVersions()
        {
            _ItemDocVersionCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemDocVersionCount = -1; // This will cause the data to be requeried
        }
        // B2016-130: GetNext was added so that NextItems was not used for finding the next item in a list of iteminfos using 'nextitems'.  
        // When using 'nextitems' internal list data structures for items were not maintained consistently with the database items during
        // some occurrences of copy/paste/delete.
        [Serializable()]
        private class PreviousIDCriteria
        {
            public PreviousIDCriteria(int? previousID)
            {
                _PreviousID = previousID;
            }
            private int? _PreviousID;
            public int? PreviousID
            {
                get { return _PreviousID; }
                set { _PreviousID = value; }
            }
        }
        public ItemInfo GetNext()
        {
            try
            {
                ItemInfo tmp = DataPortal.Fetch(new PreviousIDCriteria(ItemID));
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up ItemInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on ItemInfo.GetNext", ex);
            }
        }
        private void DataPortal_Fetch(PreviousIDCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfo.DataPortal_FetchPreviousID", GetHashCode());
            try
            {
                using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                {
                    ApplicationContext.LocalContext["cn"] = cn;
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "getNextItems";
                        cm.Parameters.AddWithValue("@PreviousID", criteria.PreviousID);
                        cm.CommandTimeout = Database.DefaultTimeout;
                        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("ItemInfo.DataPortal_FetchPreviousID", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("ItemInfo.DataPortal_Fetch", ex);
            }
        }
        private int _NextItemCount = 0;
        /// 
        /// Count of NextItems for this Item
        /// 
        public int NextItemCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_NextItemCount < 0)
                    _NextItemCount = NextItems.Count;
                return _NextItemCount;
            }
        }
        private ItemInfoList _NextItems = null;
        [TypeConverter(typeof(ItemInfoListConverter))]
        public ItemInfoList NextItems
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_NextItemCount < 0 || (_NextItemCount > 0 && _NextItems == null))
                    _NextItems = ItemInfoList.GetNext(_ItemID);
                if (_NextItemCount < 0)
                    _NextItemCount = _NextItems.Count;
                return _NextItems;
            }
        }
        public void RefreshNextItems()
        {
            _NextItemCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._NextItemCount = -1; // This will cause the data to be requeried
        }
        private int _ItemPartCount = 0;
        /// 
        /// Count of ItemParts for this Item
        /// 
        public int ItemPartCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemPartCount < 0)
                    _ItemPartCount = ItemParts.Count;
                return _ItemPartCount;
            }
        }
        private PartInfoList _ItemParts = null;
        [TypeConverter(typeof(PartInfoListConverter))]
        public PartInfoList ItemParts
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                //int profileDepth = ProfileTimer.Push(">>>> ItemParts");
                if (_ItemPartCount < 0 || (_ItemPartCount > 0 && _ItemParts == null))
                    _ItemParts = PartInfoList.GetByItemID(_ItemID);
                if (_ItemPartCount < 0)
                    _ItemPartCount = _ItemParts.Count;
                //ProfileTimer.Pop(profileDepth);
                return _ItemParts;
            }
        }
        public void RefreshItemParts()
        {
            _ItemPartCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemPartCount = -1; // This will cause the data to be requeried
        }
        private int _ItemTransition_RangeIDCount = 0;
        /// 
        /// Count of ItemTransitions_RangeID for this Item
        /// 
        public int ItemTransition_RangeIDCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemTransition_RangeIDCount < 0)
                    _ItemTransition_RangeIDCount = ItemTransitions_RangeID.Count;
                return _ItemTransition_RangeIDCount;
            }
        }
        private TransitionInfoList _ItemTransitions_RangeID = null;
        [TypeConverter(typeof(TransitionInfoListConverter))]
        public TransitionInfoList ItemTransitions_RangeID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemTransition_RangeIDCount < 0 || (_ItemTransition_RangeIDCount > 0 && _ItemTransitions_RangeID == null))
                    _ItemTransitions_RangeID = TransitionInfoList.GetByRangeID(_ItemID);
                if (_ItemTransition_RangeIDCount < 0)
                    _ItemTransition_RangeIDCount = _ItemTransitions_RangeID.Count;
                return _ItemTransitions_RangeID;
            }
        }
        public void RefreshItemTransitions_RangeID()
        {
            _ItemTransition_RangeIDCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemTransition_RangeIDCount = -1; // This will cause the data to be requeried
        }
        private int _ItemTransition_ToIDCount = 0;
        /// 
        /// Count of ItemTransitions_ToID for this Item
        /// 
        public int ItemTransition_ToIDCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemTransition_ToIDCount < 0)
                    _ItemTransition_ToIDCount = ItemTransitions_ToID.Count;
                return _ItemTransition_ToIDCount;
            }
        }
        private TransitionInfoList _ItemTransitions_ToID = null;
        [TypeConverter(typeof(TransitionInfoListConverter))]
        public TransitionInfoList ItemTransitions_ToID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemTransition_ToIDCount < 0 || (_ItemTransition_ToIDCount > 0 && _ItemTransitions_ToID == null))
                    _ItemTransitions_ToID = TransitionInfoList.GetByToID(_ItemID);
                if (_ItemTransition_ToIDCount < 0)
                    _ItemTransition_ToIDCount = _ItemTransitions_ToID.Count;
                return _ItemTransitions_ToID;
            }
        }
        public void RefreshItemTransitions_ToID()
        {
            _ItemTransition_ToIDCount = -1;
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(_ItemID.ToString()))
                foreach (ItemInfo tmp in _CacheByPrimaryKey[_ItemID.ToString()])
                    tmp._ItemTransition_ToIDCount = -1; // This will cause the data to be requeried
        }
        // CSLATODO: Replace base ItemInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current ItemInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // CSLATODO: Check ItemInfo.GetIdValue to assure that the ID returned is unique
        /// 
        /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
        /// 
        /// A Unique ID for the current ItemInfo
        protected override object GetIdValue()
        {
            return MyItemInfoUnique; // Absolutely Unique ID
        }
        #endregion
        #region Factory Methods
        private static int _ItemInfoUnique = 0;
        private static int ItemInfoUnique
        {
            get
            {
                int ui = ++_ItemInfoUnique;
                //Useful for debug to identify where item is being created:
                //if (ui == 73) Console.WriteLine("here");
                return ui;
            }
        }
        private int _MyItemInfoUnique = ItemInfoUnique;
        public int MyItemInfoUnique // Absolutely Unique ID - Info
        { get { return _MyItemInfoUnique; } }
        protected ItemInfo()
        {/* 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
        { 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; } }
        ~ItemInfo()
        {
            _CountFinalized++;
        }
        public void Dispose()
        {
            if (_Disposed) return;
            _CountDisposed++;
            _Disposed = true;
            _ItemParts?.Dispose();
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(ItemID.ToString())) return;
            List listItemInfo = _CacheByPrimaryKey[ItemID.ToString()]; // Get the list of items
            while (listItemInfo.Contains(this)) listItemInfo.Remove(this); // Remove the item from the list
            if (listItemInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(ItemID.ToString()); // remove the list
            if (_MyContent != null)
                _MyContent = null;
            if (_MyPrevious != null)
                _MyPrevious = null;
            //if (_ActiveFormat != null)
            //  _ActiveFormat = null;
            //if (_ActiveParent != null)
            //  _ActiveParent = null;
            //if (_ActiveSection != null)
            //  _ActiveSection = null;
            //if (_MyDocVersion != null)
            //  _MyDocVersion = null;
            //if (_ParentNoteOrCaution != null)
            //  _ParentNoteOrCaution = null;
        }
        public virtual Item Get()
        {
            return _Editable = Item.Get(_ItemID);
        }
        public static void Refresh(Item tmp)
        {
            string key = tmp.ItemID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (ItemInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Item tmp)
        {
            if (_PreviousID != tmp.PreviousID)
            {
                if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for old value
                _PreviousID = tmp.PreviousID; // Update the value
            }
            _MyPrevious = null; // Reset list so that the next line gets a new list
            if (MyPrevious != null) MyPrevious.RefreshNextItems(); // Update List for new value
                                                                   //if (_ContentID != tmp.ContentID)
                                                                   //{
            if (MyContent != null) MyContent.RefreshContentItems(); // Update List for old value
            _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
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _ItemInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static void Refresh(ContentItem tmp)
        {
            string key = tmp.ItemID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (ItemInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ContentItem tmp)
        {
            if (_PreviousID != tmp.PreviousID)
            {
                if (MyPrevious != null) 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
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _ItemInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static ItemInfo Get(int itemID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Item");
            try
            {
                ItemInfo tmp = GetCachedByPrimaryKey(itemID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(itemID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up ItemInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on ItemInfo.Get", ex);
            }
        }
        // B2016-130: Just get an item from the database, but don't add it to the cache because it gets
        // freed (only use this in a 'using' statement).
        public static ItemInfo GetNonCached(int itemID)
        {
            try
            {
                ItemInfo tmp = DataPortal.Fetch(new PKCriteria(itemID));
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up ItemInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on ItemInfo.GetNonCached", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal ItemInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemInfo.Constructor", ex);
                throw new DbCslaException("ItemInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _ItemID;
            public int ItemID
            { get { return _ItemID; } }
            public PKCriteria(int itemID)
            {
                _ItemID = itemID;
            }
        }
        protected void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfo.ReadData", GetHashCode());
            try
            {
                _ItemID = dr.GetInt32("ItemID");
                _PreviousID = (int?)dr.GetValue("PreviousID");
                _ContentID = dr.GetInt32("ContentID");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
                _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");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("ItemInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("ItemInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ItemInfo.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);
                        }
                    }
                    // 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("ItemInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("ItemInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        ItemInfoExtension _ItemInfoExtension = new ItemInfoExtension();
        [Serializable()]
        partial class ItemInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(ItemInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class ItemInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is ItemInfo)
            {
                // Return the ToString value
                return ((ItemInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace