// ========================================================================
// 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 FormatInfoEvent(object sender);
	/// 
	///	FormatInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(FormatInfoConverter))]
	public partial class FormatInfo : ReadOnlyBase, IDisposable
	{
		public event FormatInfoEvent 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(FormatInfo formatInfo)
		{
			if (!_CacheList.Contains(formatInfo)) _CacheList.Add(formatInfo); // In AddToCache
		}
		protected static void RemoveFromCache(FormatInfo formatInfo)
		{
			while (_CacheList.Contains(formatInfo)) _CacheList.Remove(formatInfo); // In RemoveFromCache
		}
		private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
		private static void ConvertListToDictionary()
		{
			List remove = new List();
			foreach (FormatInfo tmp in _CacheList)
			{
				if (!_CacheByPrimaryKey.ContainsKey(tmp.FormatID.ToString()))
				{
					_CacheByPrimaryKey[tmp.FormatID.ToString()] = new List(); // Add new list for PrimaryKey
				}
				_CacheByPrimaryKey[tmp.FormatID.ToString()].Add(tmp); // Add to Primary Key list
				remove.Add(tmp);
			}
			foreach (FormatInfo tmp in remove)
				RemoveFromCache(tmp);
		}
		internal static void AddList(FormatInfoList lst)
		{
			foreach (FormatInfo item in lst) AddToCache(item);
		}
		protected static FormatInfo GetCachedByPrimaryKey(int formatID)
		{
			ConvertListToDictionary();
			string key = formatID.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 Format _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _FormatID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int FormatID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatID", true);
				return _FormatID;
			}
		}
		private int _ParentID;
		public int ParentID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ParentID", true);
				if (_MyParent != null) _ParentID = _MyParent.FormatID;
				return _ParentID;
			}
		}
		private FormatInfo _MyParent;
		public FormatInfo MyParent
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyParent", true);
				if (_MyParent == null && _ParentID != _FormatID) _MyParent = FormatInfo.Get(_ParentID);
				return _MyParent;
			}
		}
		private string _Name = string.Empty;
		public string Name
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Name", true);
				return _Name;
			}
		}
		private string _Description = string.Empty;
		public string Description
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Description", true);
				return _Description;
			}
		}
		private string _Data = string.Empty;
		public string Data
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Data", true);
				return _Data;
			}
		}
		private string _GenMac = string.Empty;
		public string GenMac
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("GenMac", true);
				return _GenMac;
			}
		}
		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;
			}
		}
		private int _FormatContentCount = 0;
		/// 
		/// Count of FormatContents for this Format
		/// 
		public int FormatContentCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatContentCount", true);
				return _FormatContentCount;
			}
		}
		private ContentInfoList _FormatContents = null;
		[TypeConverter(typeof(ContentInfoListConverter))]
		public ContentInfoList FormatContents
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatContents", true);
				if (_FormatContentCount < 0 || (_FormatContentCount > 0 && _FormatContents == null))
					_FormatContents = ContentInfoList.GetByFormatID(_FormatID);
				if (_FormatContentCount < 0)
					_FormatContentCount = _FormatContents.Count;
				return _FormatContents;
			}
		}
		public void RefreshFormatContents()
		{
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_FormatID.ToString()))
				foreach (FormatInfo tmp in _CacheByPrimaryKey[_FormatID.ToString()])
					tmp._FormatContentCount = -1; // This will cause the data to be requeried
		}
		private int _FormatDocVersionCount = 0;
		/// 
		/// Count of FormatDocVersions for this Format
		/// 
		public int FormatDocVersionCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatDocVersionCount", true);
				return _FormatDocVersionCount;
			}
		}
		private DocVersionInfoList _FormatDocVersions = null;
		[TypeConverter(typeof(DocVersionInfoListConverter))]
		public DocVersionInfoList FormatDocVersions
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatDocVersions", true);
				if (_FormatDocVersionCount < 0 || (_FormatDocVersionCount > 0 && _FormatDocVersions == null))
					_FormatDocVersions = DocVersionInfoList.GetByFormatID(_FormatID);
				if (_FormatDocVersionCount < 0)
					_FormatDocVersionCount = _FormatDocVersions.Count;
				return _FormatDocVersions;
			}
		}
		public void RefreshFormatDocVersions()
		{
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_FormatID.ToString()))
				foreach (FormatInfo tmp in _CacheByPrimaryKey[_FormatID.ToString()])
					tmp._FormatDocVersionCount = -1; // This will cause the data to be requeried
		}
		private int _FormatFolderCount = 0;
		/// 
		/// Count of FormatFolders for this Format
		/// 
		public int FormatFolderCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatFolderCount", true);
				return _FormatFolderCount;
			}
		}
		private FolderInfoList _FormatFolders = null;
		[TypeConverter(typeof(FolderInfoListConverter))]
		public FolderInfoList FormatFolders
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatFolders", true);
				if (_FormatFolderCount < 0 || (_FormatFolderCount > 0 && _FormatFolders == null))
					_FormatFolders = FolderInfoList.GetByFormatID(_FormatID);
				if (_FormatFolderCount < 0)
					_FormatFolderCount = _FormatFolders.Count;
				return _FormatFolders;
			}
		}
		public void RefreshFormatFolders()
		{
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_FormatID.ToString()))
				foreach (FormatInfo tmp in _CacheByPrimaryKey[_FormatID.ToString()])
					tmp._FormatFolderCount = -1; // This will cause the data to be requeried
		}
		private int _ChildFormatCount = 0;
		/// 
		/// Count of ChildFormats for this Format
		/// 
		public int ChildFormatCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ChildFormatCount", true);
				return _ChildFormatCount;
			}
		}
		private FormatInfoList _ChildFormats = null;
		[TypeConverter(typeof(FormatInfoListConverter))]
		public FormatInfoList ChildFormats
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ChildFormats", true);
				if (_ChildFormatCount < 0 || (_ChildFormatCount > 0 && _ChildFormats == null))
					_ChildFormats = FormatInfoList.GetChildren(_FormatID);
				if (_ChildFormatCount < 0)
					_ChildFormatCount = _ChildFormats.Count;
				return _ChildFormats;
			}
		}
		public void RefreshChildFormats()
		{
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_FormatID.ToString()))
				foreach (FormatInfo tmp in _CacheByPrimaryKey[_FormatID.ToString()])
					tmp._ChildFormatCount = -1; // This will cause the data to be requeried
		}
		// TODO: Replace base FormatInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current FormatInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// TODO: Check FormatInfo.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 FormatInfo
		protected override object GetIdValue()
		{
			return _FormatID;
		}
		#endregion
		#region Factory Methods
		private static int _FormatInfoUnique = 0;
		private static int FormatInfoUnique
		{ get { return ++_FormatInfoUnique; } }
		private int _MyFormatInfoUnique = FormatInfoUnique;
		public int MyFormatInfoUnique
		{ get { return _MyFormatInfoUnique; } }
		protected FormatInfo()
		{/* require use of factory methods */
			AddToCache(this);
		}
		public void Dispose()
		{
			RemoveFromCache(this);
			if (!_CacheByPrimaryKey.ContainsKey(FormatID.ToString())) return;
			List listFormatInfo = _CacheByPrimaryKey[FormatID.ToString()]; // Get the list of items
			while (listFormatInfo.Contains(this)) listFormatInfo.Remove(this); // Remove the item from the list
			if (listFormatInfo.Count == 0) // If there are no items left in the list
				_CacheByPrimaryKey.Remove(FormatID.ToString()); // remove the list
		}
		public virtual Format Get()
		{
			return _Editable = Format.Get(_FormatID);
		}
		public static void Refresh(Format tmp)
		{
			string key = tmp.FormatID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (FormatInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(Format tmp)
		{
			if (_ParentID != tmp.ParentID)
			{
				if (MyParent != null) MyParent.RefreshChildFormats(); // Update List for old value
				_ParentID = tmp.ParentID; // Update the value
			}
			_MyParent = null; // Reset list so that the next line gets a new list
			if (MyParent != null) MyParent.RefreshChildFormats(); // Update List for new value
			_Name = tmp.Name;
			_Description = tmp.Description;
			_Data = tmp.Data;
			_GenMac = tmp.GenMac;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_FormatInfoExtension.Refresh(this);
			if(_MyParent != null)
			{
				_MyParent.Dispose();// Dispose related value
				_MyParent = null;// Reset related value
			}
			OnChange();// raise an event
		}
		public static FormatInfo Get(int formatID)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a Format");
			try
			{
				FormatInfo tmp = GetCachedByPrimaryKey(formatID);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(formatID));
					AddToCache(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up FormatInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on FormatInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal FormatInfo(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("FormatInfo.Constructor", ex);
				throw new DbCslaException("FormatInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _FormatID;
			public int FormatID
			{ get { return _FormatID; } }
			public PKCriteria(int formatID)
			{
				_FormatID = formatID;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfo.ReadData", GetHashCode());
			try
			{
				_FormatID = dr.GetInt32("FormatID");
				_ParentID = dr.GetInt32("ParentID");
				_Name = dr.GetString("Name");
				_Description = dr.GetString("Description");
				_Data = dr.GetString("Data");
				_GenMac = dr.GetString("GenMac");
				_DTS = dr.GetDateTime("DTS");
				_UserID = dr.GetString("UserID");
				_FormatContentCount = dr.GetInt32("ContentCount");
				_FormatDocVersionCount = dr.GetInt32("DocVersionCount");
				_FormatFolderCount = dr.GetInt32("FolderCount");
				_ChildFormatCount = dr.GetInt32("ChildCount");
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("FormatInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("FormatInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] FormatInfo.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 = "getFormat";
						cm.Parameters.AddWithValue("@FormatID", criteria.FormatID);
						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("FormatInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("FormatInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		FormatInfoExtension _FormatInfoExtension = new FormatInfoExtension();
		[Serializable()]
		partial class FormatInfoExtension : extensionBase { }
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(FormatInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class FormatInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is FormatInfo)
			{
				// Return the ToString value
				return ((FormatInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace