// ========================================================================
// 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 CheckInfoEvent(object sender);
	/// 
	///	CheckInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(CheckInfoConverter))]
	public partial class CheckInfo : ReadOnlyBase, IDisposable
	{
		public event CheckInfoEvent 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(CheckInfo checkInfo)
		{
			if (!_CacheList.Contains(checkInfo)) _CacheList.Add(checkInfo); // In AddToCache
		}
		protected static void RemoveFromCache(CheckInfo checkInfo)
		{
			while (_CacheList.Contains(checkInfo)) _CacheList.Remove(checkInfo); // In RemoveFromCache
		}
		private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
		private static void ConvertListToDictionary()
		{
			while (_CacheList.Count > 0) // Move CheckInfo(s) from temporary _CacheList to _CacheByPrimaryKey
			{
				CheckInfo tmp = _CacheList[0]; // Get the first CheckInfo
				string pKey = tmp.CheckID.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 CheckInfo
			}
		}
		internal static void AddList(CheckInfoList lst)
		{
			foreach (CheckInfo item in lst) AddToCache(item);
		}
		protected static CheckInfo GetCachedByPrimaryKey(int checkID)
		{
			ConvertListToDictionary();
			string key = checkID.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 Check _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _CheckID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int CheckID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("CheckID", true);
				return _CheckID;
			}
		}
		private int _RevisionID;
		public int RevisionID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RevisionID", true);
				if (_MyRevision != null) _RevisionID = _MyRevision.RevisionID;
				return _RevisionID;
			}
		}
		private RevisionInfo _MyRevision;
		public RevisionInfo MyRevision
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyRevision", true);
				if (_MyRevision == null && _RevisionID != 0) _MyRevision = RevisionInfo.Get(_RevisionID);
				return _MyRevision;
			}
		}
		private int _StageID;
		public int StageID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("StageID", true);
				if (_MyStage != null) _StageID = _MyStage.StageID;
				return _StageID;
			}
		}
		private StageInfo _MyStage;
		public StageInfo MyStage
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyStage", true);
				if (_MyStage == null && _StageID != 0) _MyStage = StageInfo.GetJustStage(_StageID);
				return _MyStage;
			}
		}
		private string _ConsistencyChecks = string.Empty;
		public string ConsistencyChecks
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ConsistencyChecks", true);
				return _ConsistencyChecks;
			}
		}
		private DateTime _DTS = new DateTime();
		public DateTime DTS
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("DTS", true);
				return _DTS;
			}
		}
		private string _UserID = string.Empty;
		public string UserID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("UserID", true);
				return _UserID;
			}
		}
		// CSLATODO: Replace base CheckInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current CheckInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// CSLATODO: Check CheckInfo.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 CheckInfo
		protected override object GetIdValue()
		{
			return MyCheckInfoUnique; // Absolutely Unique ID
		}
		#endregion
		#region Factory Methods
		private static int _CheckInfoUnique = 0;
		private static int CheckInfoUnique
		{ get { return ++_CheckInfoUnique; } }
		private int _MyCheckInfoUnique = CheckInfoUnique;
		public int MyCheckInfoUnique // Absolutely Unique ID - Info
		{ get { return _MyCheckInfoUnique; } }
		protected CheckInfo()
		{/* 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; } }
		~CheckInfo()
		{
			_CountFinalized++;
		}
		public void Dispose()
		{
			if (_Disposed) return;
			_CountDisposed++;
			_Disposed = true;
			RemoveFromCache(this);
			if (!_CacheByPrimaryKey.ContainsKey(CheckID.ToString())) return;
			List listCheckInfo = _CacheByPrimaryKey[CheckID.ToString()]; // Get the list of items
			while (listCheckInfo.Contains(this)) listCheckInfo.Remove(this); // Remove the item from the list
			if (listCheckInfo.Count == 0) // If there are no items left in the list
				_CacheByPrimaryKey.Remove(CheckID.ToString()); // remove the list
		}
		public virtual Check Get()
		{
			return _Editable = Check.Get(_CheckID);
		}
		public static void Refresh(Check tmp)
		{
			string key = tmp.CheckID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (CheckInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(Check tmp)
		{
			if (_RevisionID != tmp.RevisionID)
			{
				if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for old value
				_RevisionID = tmp.RevisionID; // Update the value
			}
			_MyRevision = null; // Reset list so that the next line gets a new list
			if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for new value
			if (_StageID != tmp.StageID)
			{
				if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for old value
				_StageID = tmp.StageID; // Update the value
			}
			_MyStage = null; // Reset list so that the next line gets a new list
			if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for new value
			_ConsistencyChecks = tmp.ConsistencyChecks;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_CheckInfoExtension.Refresh(this);
			OnChange();// raise an event
		}
		public static void Refresh(RevisionCheck tmp)
		{
			string key = tmp.CheckID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (CheckInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(RevisionCheck tmp)
		{
			if (_StageID != tmp.StageID)
			{
				if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for old value
				_StageID = tmp.StageID; // Update the value
			}
			_MyStage = null; // Reset list so that the next line gets a new list
			if (MyStage != null) MyStage.RefreshStageChecks(); // Update List for new value
			_ConsistencyChecks = tmp.ConsistencyChecks;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_CheckInfoExtension.Refresh(this);
			OnChange();// raise an event
		}
		public static void Refresh(StageCheck tmp)
		{
			string key = tmp.CheckID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (CheckInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(StageCheck tmp)
		{
			if (_RevisionID != tmp.RevisionID)
			{
				if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for old value
				_RevisionID = tmp.RevisionID; // Update the value
			}
			_MyRevision = null; // Reset list so that the next line gets a new list
			if (MyRevision != null) MyRevision.RefreshRevisionChecks(); // Update List for new value
			_ConsistencyChecks = tmp.ConsistencyChecks;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_CheckInfoExtension.Refresh(this);
			OnChange();// raise an event
		}
		public static CheckInfo Get(int checkID)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a Check");
			try
			{
				CheckInfo tmp = GetCachedByPrimaryKey(checkID);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(checkID));
					AddToCache(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up CheckInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on CheckInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal CheckInfo(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] CheckInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("CheckInfo.Constructor", ex);
				throw new DbCslaException("CheckInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _CheckID;
			public int CheckID
			{ get { return _CheckID; } }
			public PKCriteria(int checkID)
			{
				_CheckID = checkID;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] CheckInfo.ReadData", GetHashCode());
			try
			{
				_CheckID = dr.GetInt32("CheckID");
				_RevisionID = dr.GetInt32("RevisionID");
				_StageID = dr.GetInt32("StageID");
				_ConsistencyChecks = dr.GetString("ConsistencyChecks");
				_DTS = dr.GetDateTime("DTS");
				_UserID = dr.GetString("UserID");
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("CheckInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("CheckInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] CheckInfo.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 = "getCheck";
						cm.Parameters.AddWithValue("@CheckID", criteria.CheckID);
						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("CheckInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("CheckInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		CheckInfoExtension _CheckInfoExtension = new CheckInfoExtension();
		[Serializable()]
		partial class CheckInfoExtension : extensionBase { }
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(CheckInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class CheckInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is CheckInfo)
			{
				// Return the ToString value
				return ((CheckInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace