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