// ========================================================================
// 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;
namespace VEPROMS.CSLA.Library
{
    public delegate void DocVersionROFstInfoEvent(object sender);
    /// 
    ///	DocVersionROFstInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(DocVersionROFstInfoConverter))]
    public partial class DocVersionROFstInfo : ReadOnlyBase, IDisposable
    {
        public event DocVersionROFstInfoEvent 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(DocVersionROFstInfo docVersionROFstInfo)
        {
            if (!_CacheList.Contains(docVersionROFstInfo)) _CacheList.Add(docVersionROFstInfo); // In AddToCache
        }
        protected static void RemoveFromCache(DocVersionROFstInfo docVersionROFstInfo)
        {
            while (_CacheList.Contains(docVersionROFstInfo)) _CacheList.Remove(docVersionROFstInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List remove = new List();
            foreach (DocVersionROFstInfo tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.VersionID.ToString() + "_" + tmp.ROFstID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.VersionID.ToString() + "_" + tmp.ROFstID.ToString()] = new List(); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[tmp.VersionID.ToString() + "_" + tmp.ROFstID.ToString()].Add(tmp); // Add to Primary Key list
                remove.Add(tmp);
            }
            foreach (DocVersionROFstInfo tmp in remove)
                RemoveFromCache(tmp);
        }
        internal static void AddList(DocVersionROFstInfoList lst)
        {
            foreach (DocVersionROFstInfo item in lst) AddToCache(item);
        }
        protected static DocVersionROFstInfo GetCachedByPrimaryKey(int versionID, int rOFstID)
        {
            ConvertListToDictionary();
            string key = versionID.ToString() + "_" + rOFstID.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 DocVersionROFst _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _VersionID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int VersionID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyDocVersion != null) _VersionID = _MyDocVersion.VersionID;
                return _VersionID;
            }
        }
        private DocVersionInfo _MyDocVersion;
        [System.ComponentModel.DataObjectField(true, true)]
        public DocVersionInfo MyDocVersion
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyDocVersion == null && _VersionID != 0) _MyDocVersion = DocVersionInfo.Get(_VersionID);
                return _MyDocVersion;
            }
        }
        private int _ROFstID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int ROFstID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyROFst != null) _ROFstID = _MyROFst.ROFstID;
                return _ROFstID;
            }
        }
        private ROFstInfo _MyROFst;
        [System.ComponentModel.DataObjectField(true, true)]
        public ROFstInfo MyROFst
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyROFst == null && _ROFstID != 0) _MyROFst = ROFstInfo.Get(_ROFstID);
                return _MyROFst;
            }
        }
        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;
            }
        }
        // TODO: Replace base DocVersionROFstInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current DocVersionROFstInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // TODO: Check DocVersionROFstInfo.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 DocVersionROFstInfo
        protected override object GetIdValue()
        {
            return (_VersionID.ToString() + "." + _ROFstID.ToString()).GetHashCode();
        }
        #endregion
        #region Factory Methods
        private static int _DocVersionROFstInfoUnique = 0;
        private static int DocVersionROFstInfoUnique
        { get { return ++_DocVersionROFstInfoUnique; } }
        private int _MyDocVersionROFstInfoUnique = DocVersionROFstInfoUnique;
        public int MyDocVersionROFstInfoUnique
        { get { return _MyDocVersionROFstInfoUnique; } }
        protected DocVersionROFstInfo()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(VersionID.ToString() + "_" + ROFstID.ToString())) return;
            List listDocVersionROFstInfo = _CacheByPrimaryKey[VersionID.ToString() + "_" + ROFstID.ToString()]; // Get the list of items
            while (listDocVersionROFstInfo.Contains(this)) listDocVersionROFstInfo.Remove(this); // Remove the item from the list
            if (listDocVersionROFstInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(VersionID.ToString() + "_" + ROFstID.ToString()); // remove the list
        }
        public virtual DocVersionROFst Get()
        {
            return _Editable = DocVersionROFst.Get(_VersionID, _ROFstID);
        }
        public static void Refresh(DocVersionROFst tmp)
        {
            string key = tmp.VersionID.ToString() + "_" + tmp.ROFstID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (DocVersionROFstInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(DocVersionROFst tmp)
        {
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _DocVersionROFstInfoExtension.Refresh(this);
            if (_MyDocVersion != null)
            {
                _MyDocVersion.Dispose();// Dispose related value
                _MyDocVersion = null;// Reset related value
            }
            if (_MyROFst != null)
            {
                _MyROFst.Dispose();// Dispose related value
                _MyROFst = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static void Refresh(DocVersion myDocVersion, DocVersionDocVersionROFst tmp)
        {
            string key = myDocVersion.VersionID.ToString() + "_" + tmp.ROFstID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (DocVersionROFstInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(DocVersionDocVersionROFst tmp)
        {
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _DocVersionROFstInfoExtension.Refresh(this);
            if (_MyDocVersion != null)
            {
                _MyDocVersion.Dispose();// Dispose related value
                _MyDocVersion = null;// Reset related value
            }
            if (_MyROFst != null)
            {
                _MyROFst.Dispose();// Dispose related value
                _MyROFst = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static void Refresh(ROFst myROFst, ROFstDocVersionROFst tmp)
        {
            string key = tmp.VersionID.ToString() + "_" + myROFst.ROFstID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (DocVersionROFstInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ROFstDocVersionROFst tmp)
        {
            _DTS = tmp.DTS;
            _UserID = tmp.UserID;
            _DocVersionROFstInfoExtension.Refresh(this);
            if (_MyDocVersion != null)
            {
                _MyDocVersion.Dispose();// Dispose related value
                _MyDocVersion = null;// Reset related value
            }
            if (_MyROFst != null)
            {
                _MyROFst.Dispose();// Dispose related value
                _MyROFst = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static DocVersionROFstInfo Get(int versionID, int rOFstID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a DocVersionROFst");
            try
            {
                DocVersionROFstInfo tmp = GetCachedByPrimaryKey(versionID, rOFstID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(versionID, rOFstID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up DocVersionROFstInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on DocVersionROFstInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal DocVersionROFstInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionROFstInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionROFstInfo.Constructor", ex);
                throw new DbCslaException("DocVersionROFstInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _VersionID;
            public int VersionID
            { get { return _VersionID; } }
            private int _ROFstID;
            public int ROFstID
            { get { return _ROFstID; } }
            public PKCriteria(int versionID, int rOFstID)
            {
                _VersionID = versionID;
                _ROFstID = rOFstID;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionROFstInfo.ReadData", GetHashCode());
            try
            {
                _VersionID = dr.GetInt32("VersionID");
                _ROFstID = dr.GetInt32("ROFstID");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionROFstInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("DocVersionROFstInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionROFstInfo.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 = "getDocVersionROFst";
                        cm.Parameters.AddWithValue("@VersionID", criteria.VersionID);
                        cm.Parameters.AddWithValue("@ROFstID", criteria.ROFstID);
                        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("DocVersionROFstInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("DocVersionROFstInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        DocVersionROFstInfoExtension _DocVersionROFstInfoExtension = new DocVersionROFstInfoExtension();
        [Serializable()]
        partial class DocVersionROFstInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(DocVersionROFstInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class DocVersionROFstInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is DocVersionROFstInfo)
            {
                // Return the ToString value
                return ((DocVersionROFstInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace