// ========================================================================
// 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 AssignmentInfoEvent(object sender);
    /// 
    ///	AssignmentInfo Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(AssignmentInfoConverter))]
    public partial class AssignmentInfo : ReadOnlyBase, IDisposable
    {
        public event AssignmentInfoEvent 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(AssignmentInfo assignmentInfo)
        {
            if (!_CacheList.Contains(assignmentInfo)) _CacheList.Add(assignmentInfo); // In AddToCache
        }
        protected static void RemoveFromCache(AssignmentInfo assignmentInfo)
        {
            while (_CacheList.Contains(assignmentInfo)) _CacheList.Remove(assignmentInfo); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            while (_CacheList.Count > 0) // Move AssignmentInfo(s) from temporary _CacheList to _CacheByPrimaryKey
            {
                AssignmentInfo tmp = _CacheList[0]; // Get the first AssignmentInfo
                string pKey = tmp.AID.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 AssignmentInfo
            }
        }
        internal static void AddList(AssignmentInfoList lst)
        {
            foreach (AssignmentInfo item in lst) AddToCache(item);
        }
        protected static AssignmentInfo GetCachedByPrimaryKey(int aid)
        {
            ConvertListToDictionary();
            string key = aid.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 Assignment _Editable;
        private IVEHasBrokenRules HasBrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = null;
                if (_Editable != null)
                    hasBrokenRules = _Editable.HasBrokenRules;
                return hasBrokenRules;
            }
        }
        private int _AID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int AID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _AID;
            }
        }
        private int _GID;
        public int GID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyGroup != null) _GID = _MyGroup.GID;
                return _GID;
            }
        }
        private GroupInfo _MyGroup;
        public GroupInfo MyGroup
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyGroup == null && _GID != 0) _MyGroup = GroupInfo.Get(_GID);
                return _MyGroup;
            }
        }
        private int _RID;
        public int RID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyRole != null) _RID = _MyRole.RID;
                return _RID;
            }
        }
        private RoleInfo _MyRole;
        public RoleInfo MyRole
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyRole == null && _RID != 0) _MyRole = RoleInfo.Get(_RID);
                return _MyRole;
            }
        }
        private int _FolderID;
        public int FolderID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyFolder != null) _FolderID = _MyFolder.FolderID;
                return _FolderID;
            }
        }
        private FolderInfo _MyFolder;
        public FolderInfo MyFolder
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyFolder == null && _FolderID != 0) _MyFolder = FolderInfo.Get(_FolderID);
                return _MyFolder;
            }
        }
        private string _StartDate = string.Empty;
        public string StartDate
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _StartDate;
            }
        }
        private string _EndDate = string.Empty;
        public string EndDate
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _EndDate;
            }
        }
        private DateTime _DTS = new DateTime();
        public DateTime DTS
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DTS;
            }
        }
        private string _UsrID = string.Empty;
        public string UsrID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _UsrID;
            }
        }
        // CSLATODO: Replace base AssignmentInfo.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current AssignmentInfo
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // CSLATODO: Check AssignmentInfo.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 AssignmentInfo
        protected override object GetIdValue()
        {
            return MyAssignmentInfoUnique; // Absolutely Unique ID
        }
        #endregion
        #region Factory Methods
        private static int _AssignmentInfoUnique = 0;
        private static int AssignmentInfoUnique
        { get { return ++_AssignmentInfoUnique; } }
        private int _MyAssignmentInfoUnique = AssignmentInfoUnique;
        public int MyAssignmentInfoUnique // Absolutely Unique ID - Info
        { get { return _MyAssignmentInfoUnique; } }
        protected AssignmentInfo()
        {/* 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; } }
        ~AssignmentInfo()
        {
            _CountFinalized++;
        }
        public void Dispose()
        {
            if (_Disposed) return;
            _CountDisposed++;
            _Disposed = true;
            RemoveFromCache(this);
            if (!_CacheByPrimaryKey.ContainsKey(AID.ToString())) return;
            List listAssignmentInfo = _CacheByPrimaryKey[AID.ToString()]; // Get the list of items
            while (listAssignmentInfo.Contains(this)) listAssignmentInfo.Remove(this); // Remove the item from the list
            if (listAssignmentInfo.Count == 0) // If there are no items left in the list
                _CacheByPrimaryKey.Remove(AID.ToString()); // remove the list
        }
        public virtual Assignment Get()
        {
            return _Editable = Assignment.Get(_AID);
        }
        public static void Refresh(Assignment tmp)
        {
            string key = tmp.AID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AssignmentInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(Assignment tmp)
        {
            if (_GID != tmp.GID)
            {
                if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for old value
                _GID = tmp.GID; // Update the value
            }
            _MyGroup = null; // Reset list so that the next line gets a new list
            if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for new value
            if (_RID != tmp.RID)
            {
                if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for old value
                _RID = tmp.RID; // Update the value
            }
            _MyRole = null; // Reset list so that the next line gets a new list
            if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for new value
            if (_FolderID != tmp.FolderID)
            {
                if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for old value
                _FolderID = tmp.FolderID; // Update the value
            }
            _MyFolder = null; // Reset list so that the next line gets a new list
            if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for new value
            _StartDate = tmp.StartDate;
            _EndDate = tmp.EndDate;
            _DTS = tmp.DTS;
            _UsrID = tmp.UsrID;
            _AssignmentInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static void Refresh(FolderAssignment tmp)
        {
            string key = tmp.AID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AssignmentInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(FolderAssignment tmp)
        {
            if (_GID != tmp.GID)
            {
                if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for old value
                _GID = tmp.GID; // Update the value
            }
            _MyGroup = null; // Reset list so that the next line gets a new list
            if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for new value
            if (_RID != tmp.RID)
            {
                if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for old value
                _RID = tmp.RID; // Update the value
            }
            _MyRole = null; // Reset list so that the next line gets a new list
            if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for new value
            _StartDate = tmp.StartDate;
            _EndDate = tmp.EndDate;
            _DTS = tmp.DTS;
            _UsrID = tmp.UsrID;
            _AssignmentInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static void Refresh(GroupAssignment tmp)
        {
            string key = tmp.AID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AssignmentInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(GroupAssignment tmp)
        {
            if (_RID != tmp.RID)
            {
                if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for old value
                _RID = tmp.RID; // Update the value
            }
            _MyRole = null; // Reset list so that the next line gets a new list
            if (MyRole != null) MyRole.RefreshRoleAssignments(); // Update List for new value
            if (_FolderID != tmp.FolderID)
            {
                if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for old value
                _FolderID = tmp.FolderID; // Update the value
            }
            _MyFolder = null; // Reset list so that the next line gets a new list
            if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for new value
            _StartDate = tmp.StartDate;
            _EndDate = tmp.EndDate;
            _DTS = tmp.DTS;
            _UsrID = tmp.UsrID;
            _AssignmentInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static void Refresh(RoleAssignment tmp)
        {
            string key = tmp.AID.ToString();
            ConvertListToDictionary();
            if (_CacheByPrimaryKey.ContainsKey(key))
                foreach (AssignmentInfo tmpInfo in _CacheByPrimaryKey[key])
                    tmpInfo.RefreshFields(tmp);
        }
        protected virtual void RefreshFields(RoleAssignment tmp)
        {
            if (_GID != tmp.GID)
            {
                if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for old value
                _GID = tmp.GID; // Update the value
            }
            _MyGroup = null; // Reset list so that the next line gets a new list
            if (MyGroup != null) MyGroup.RefreshGroupAssignments(); // Update List for new value
            if (_FolderID != tmp.FolderID)
            {
                if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for old value
                _FolderID = tmp.FolderID; // Update the value
            }
            _MyFolder = null; // Reset list so that the next line gets a new list
            if (MyFolder != null) MyFolder.RefreshFolderAssignments(); // Update List for new value
            _StartDate = tmp.StartDate;
            _EndDate = tmp.EndDate;
            _DTS = tmp.DTS;
            _UsrID = tmp.UsrID;
            _AssignmentInfoExtension.Refresh(this);
            OnChange();// raise an event
        }
        public static AssignmentInfo Get(int aid)
        {
            //if (!CanGetObject())
            //  throw new System.Security.SecurityException("User not authorized to view a Assignment");
            try
            {
                AssignmentInfo tmp = GetCachedByPrimaryKey(aid);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(aid));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up AssignmentInfo
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on AssignmentInfo.Get", ex);
            }
        }
        #endregion
        #region Data Access Portal
        internal AssignmentInfo(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AssignmentInfo.Constructor", GetHashCode());
            try
            {
                ReadData(dr);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("AssignmentInfo.Constructor", ex);
                throw new DbCslaException("AssignmentInfo.Constructor", ex);
            }
        }
        [Serializable()]
        protected class PKCriteria
        {
            private int _AID;
            public int AID
            { get { return _AID; } }
            public PKCriteria(int aid)
            {
                _AID = aid;
            }
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AssignmentInfo.ReadData", GetHashCode());
            try
            {
                _AID = dr.GetInt32("AID");
                _GID = dr.GetInt32("GID");
                _RID = dr.GetInt32("RID");
                _FolderID = dr.GetInt32("FolderID");
                _StartDate = dr.GetSmartDate("StartDate").Text;
                _EndDate = dr.GetSmartDate("EndDate").Text;
                _DTS = dr.GetDateTime("DTS");
                _UsrID = dr.GetString("UsrID");
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("AssignmentInfo.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("AssignmentInfo.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AssignmentInfo.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 = "getAssignment";
                        cm.Parameters.AddWithValue("@AID", criteria.AID);
                        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("AssignmentInfo.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("AssignmentInfo.DataPortal_Fetch", ex);
            }
        }
        #endregion
        // Standard Refresh
        #region extension
        AssignmentInfoExtension _AssignmentInfoExtension = new AssignmentInfoExtension();
        [Serializable()]
        partial class AssignmentInfoExtension : extensionBase { }
        [Serializable()]
        class extensionBase
        {
            // Default Refresh
            public virtual void Refresh(AssignmentInfo tmp) { }
        }
        #endregion
    } // Class
    #region Converter
    internal class AssignmentInfoConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is AssignmentInfo)
            {
                // Return the ToString value
                return ((AssignmentInfo)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace