// ========================================================================
// 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 ZTransitionInfoEvent(object sender);
    /// 
    ///	ZTransitionInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(ZTransitionInfoConverter))]
    public partial class ZTransitionInfo : ReadOnlyBase, IDisposable
    {
        public event ZTransitionInfoEvent 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(ZTransitionInfo zTransitionInfo)
        {
            if (!_CacheList.Contains(zTransitionInfo)) _CacheList.Add(zTransitionInfo); // In AddToCache
        }
        protected static void RemoveFromCache(ZTransitionInfo zTransitionInfo)
        {
            while (_CacheList.Contains(zTransitionInfo)) _CacheList.Remove(zTransitionInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List remove = new List();
            foreach (ZTransitionInfo tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.TransitionID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.TransitionID.ToString()] = new List(); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[tmp.TransitionID.ToString()].Add(tmp); // Add to Primary Key list
                remove.Add(tmp);
            }
            foreach (ZTransitionInfo tmp in remove)
                RemoveFromCache(tmp);
        }
        protected static ZTransitionInfo GetCachedByPrimaryKey(int transitionID)
        {
            ConvertListToDictionary();
            string key = transitionID.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 ZTransition _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _TransitionID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int TransitionID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyTransition != null) _TransitionID = _MyTransition.TransitionID;
                return _TransitionID;
            }
        }
        private TransitionInfo _MyTransition;
        [System.ComponentModel.DataObjectField(true, true)]
        public TransitionInfo MyTransition
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyTransition == null && _TransitionID != 0) _MyTransition = TransitionInfo.Get(_TransitionID);
                return _MyTransition;
            }
        }
        private string _Oldto = string.Empty;
        public string Oldto
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _Oldto;
            }
        }
        // TODO: Replace base ZTransitionInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current ZTransitionInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // TODO: Check ZTransitionInfo.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 ZTransitionInfo
        protected override object GetIdValue()
        {
            return _TransitionID;
        }
        #endregion
        #region Factory Methods
        private static int _ZTransitionInfoUnique = 0;
        private static int ZTransitionInfoUnique
        { get { return ++_ZTransitionInfoUnique; } }
        private int _MyZTransitionInfoUnique = ZTransitionInfoUnique;
        public int MyZTransitionInfoUnique
        { get { return _MyZTransitionInfoUnique; } }
        protected ZTransitionInfo()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(TransitionID.ToString())) return;
            List listZTransitionInfo = _CacheByPrimaryKey[TransitionID.ToString()]; // Get the list of items
            while (listZTransitionInfo.Contains(this)) listZTransitionInfo.Remove(this); // Remove the item from the list
            if (listZTransitionInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list
        }
        public virtual ZTransition Get()
        {
            return _Editable = ZTransition.Get(_TransitionID);
        }
        public static void Refresh(ZTransition tmp)
        {
            string key = tmp.TransitionID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (ZTransitionInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(ZTransition tmp)
        {
            _Oldto = tmp.Oldto;
            _ZTransitionInfoExtension.Refresh(this);
            if (_MyTransition != null)
            {
                _MyTransition.Dispose();// Dispose related value
                _MyTransition = null;// Reset related value
            }
            OnChange();// raise an event
        }
        public static ZTransitionInfo Get(int transitionID)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a ZTransition");
            try
            {
                ZTransitionInfo tmp = GetCachedByPrimaryKey(transitionID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(transitionID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up ZTransitionInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on ZTransitionInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal ZTransitionInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransitionInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("ZTransitionInfo.Constructor", ex);
                throw new DbCslaException("ZTransitionInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _TransitionID;
            public int TransitionID
            { get { return _TransitionID; } }
            public PKCriteria(int transitionID)
            {
                _TransitionID = transitionID;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransitionInfo.ReadData", GetHashCode());
            try
            {
                _TransitionID = dr.GetInt32("TransitionID");
                _Oldto = dr.GetString("oldto");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("ZTransitionInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("ZTransitionInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransitionInfo.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 = "getZTransition";
                        cm.Parameters.AddWithValue("@TransitionID", criteria.TransitionID);
                        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("ZTransitionInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("ZTransitionInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        ZTransitionInfoExtension _ZTransitionInfoExtension = new ZTransitionInfoExtension();
        [Serializable()]
        partial class ZTransitionInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(ZTransitionInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class ZTransitionInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is ZTransitionInfo)
            {
                // Return the ToString value
                return ((ZTransitionInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace