// ========================================================================
// 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 ContentInfoEvent(object sender);
	/// 
	///	ContentInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(ContentInfoConverter))]
	public partial class ContentInfo : ReadOnlyBase, IDisposable
	{
		public event ContentInfoEvent 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(ContentInfo contentInfo)
		{
			if (!_CacheList.Contains(contentInfo)) _CacheList.Add(contentInfo); // In AddToCache
		}
		protected static void RemoveFromCache(ContentInfo contentInfo)
		{
			while (_CacheList.Contains(contentInfo)) _CacheList.Remove(contentInfo); // In RemoveFromCache
		}
		private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
		private static void ConvertListToDictionary()
		{
			List remove = new List();
			foreach (ContentInfo tmp in _CacheList)
			{
				if (!_CacheByPrimaryKey.ContainsKey(tmp.ContentID.ToString()))
				{
					_CacheByPrimaryKey[tmp.ContentID.ToString()] = new List(); // Add new list for PrimaryKey
				}
				_CacheByPrimaryKey[tmp.ContentID.ToString()].Add(tmp); // Add to Primary Key list
				remove.Add(tmp);
			}
			foreach (ContentInfo tmp in remove)
				RemoveFromCache(tmp);
		}
		internal static void AddList(ContentInfoList lst)
		{
			foreach (ContentInfo item in lst) AddToCache(item);
		}
		protected static ContentInfo GetCachedByPrimaryKey(int contentID)
		{
			ConvertListToDictionary();
			string key = contentID.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 Content _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _ContentID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int ContentID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentID", true);
				return _ContentID;
			}
		}
		private string _Number = string.Empty;
		public string Number
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Number", true);
				return _Number;
			}
		}
		private string _Text = string.Empty;
		public string Text
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Text", true);
				return _Text;
			}
		}
		private int? _Type;
		/// 
		/// 0 - Procedure, 10000 - Section, 20000 Step
		/// 
		public int? Type
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Type", true);
				return _Type;
			}
		}
		private int? _FormatID;
		public int? FormatID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FormatID", true);
				if (_MyFormat != null) _FormatID = _MyFormat.FormatID;
				return _FormatID;
			}
		}
		private FormatInfo _MyFormat;
		public FormatInfo MyFormat
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyFormat", true);
				if (_MyFormat == null && _FormatID != null) _MyFormat = FormatInfo.Get((int)_FormatID);
				return _MyFormat;
			}
		}
		private string _Config = string.Empty;
		public string Config
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Config", true);
				return _Config;
			}
		}
		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 _ContentDetailCount = 0;
		/// 
		/// Count of ContentDetails for this Content
		/// 
		public int ContentDetailCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentDetailCount", true);
				if (_ContentDetailCount < 0)
					_ContentDetailCount = ContentDetails.Count;
				return _ContentDetailCount;
			}
		}
		private DetailInfoList _ContentDetails = null;
		[TypeConverter(typeof(DetailInfoListConverter))]
		public DetailInfoList ContentDetails
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentDetails", true);
				if (_ContentDetailCount < 0 || (_ContentDetailCount > 0 && _ContentDetails == null))
					_ContentDetails = DetailInfoList.GetByContentID(_ContentID);
				if (_ContentDetailCount < 0)
					_ContentDetailCount = _ContentDetails.Count;
				return _ContentDetails;
			}
		}
		public void RefreshContentDetails()
		{
			_ContentDetailCount = -1;
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_ContentID.ToString()))
				foreach (ContentInfo tmp in _CacheByPrimaryKey[_ContentID.ToString()])
					tmp._ContentDetailCount = -1; // This will cause the data to be requeried
		}
		private int _ContentEntryCount = 0;
		/// 
		/// Count of ContentEntries for this Content
		/// 
		public int ContentEntryCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentEntryCount", true);
				return _ContentEntryCount;
			}
		}
		private EntryInfo _MyEntry = null;
		[TypeConverter(typeof(EntryInfoConverter))]
		public EntryInfo MyEntry
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyEntry", true);
				if (_ContentEntryCount != 0 && _MyEntry == null)
				{
					_MyEntry = EntryInfo.Get(_ContentID);
					_ContentEntryCount = _MyEntry == null ? 0 : 1;
				}
				return _MyEntry;
			}
		}
		private int _ContentItemCount = 0;
		/// 
		/// Count of ContentItems for this Content
		/// 
		public int ContentItemCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentItemCount", true);
				if (_ContentItemCount < 0)
					_ContentItemCount = ContentItems.Count;
				return _ContentItemCount;
			}
		}
		private ItemInfoList _ContentItems = null;
		[TypeConverter(typeof(ItemInfoListConverter))]
		public ItemInfoList ContentItems
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentItems", true);
				if (_ContentItemCount < 0 || (_ContentItemCount > 0 && _ContentItems == null))
					_ContentItems = ItemInfoList.GetByContentID(_ContentID);
				if (_ContentItemCount < 0)
					_ContentItemCount = _ContentItems.Count;
				return _ContentItems;
			}
		}
		public void RefreshContentItems()
		{
			_ContentItemCount = -1;
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_ContentID.ToString()))
				foreach (ContentInfo tmp in _CacheByPrimaryKey[_ContentID.ToString()])
					tmp._ContentItemCount = -1; // This will cause the data to be requeried
		}
		private int _ContentPartCount = 0;
		/// 
		/// Count of ContentParts for this Content
		/// 
		public int ContentPartCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentPartCount", true);
				if (_ContentPartCount < 0)
					_ContentPartCount = ContentParts.Count;
				return _ContentPartCount;
			}
		}
		private PartInfoList _ContentParts = null;
		[TypeConverter(typeof(PartInfoListConverter))]
		public PartInfoList ContentParts
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentParts", true);
				if (_ContentPartCount < 0 || (_ContentPartCount > 0 && _ContentParts == null))
					_ContentParts = PartInfoList.GetByContentID(_ContentID);
				if (_ContentPartCount < 0)
					_ContentPartCount = _ContentParts.Count;
				return _ContentParts;
			}
		}
		public void RefreshContentParts()
		{
			_ContentPartCount = -1;
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_ContentID.ToString()))
				foreach (ContentInfo tmp in _CacheByPrimaryKey[_ContentID.ToString()])
					tmp._ContentPartCount = -1; // This will cause the data to be requeried
		}
		private int _ContentRoUsageCount = 0;
		/// 
		/// Count of ContentRoUsages for this Content
		/// 
		public int ContentRoUsageCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentRoUsageCount", true);
				if (_ContentRoUsageCount < 0)
					_ContentRoUsageCount = ContentRoUsages.Count;
				return _ContentRoUsageCount;
			}
		}
		private RoUsageInfoList _ContentRoUsages = null;
		[TypeConverter(typeof(RoUsageInfoListConverter))]
		public RoUsageInfoList ContentRoUsages
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentRoUsages", true);
				if (_ContentRoUsageCount < 0 || (_ContentRoUsageCount > 0 && _ContentRoUsages == null))
					_ContentRoUsages = RoUsageInfoList.GetByContentID(_ContentID);
				if (_ContentRoUsageCount < 0)
					_ContentRoUsageCount = _ContentRoUsages.Count;
				return _ContentRoUsages;
			}
		}
		public void RefreshContentRoUsages()
		{
			_ContentRoUsageCount = -1;
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_ContentID.ToString()))
				foreach (ContentInfo tmp in _CacheByPrimaryKey[_ContentID.ToString()])
					tmp._ContentRoUsageCount = -1; // This will cause the data to be requeried
		}
		private int _ContentTransitionCount = 0;
		/// 
		/// Count of ContentTransitions for this Content
		/// 
		public int ContentTransitionCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentTransitionCount", true);
				if (_ContentTransitionCount < 0)
					_ContentTransitionCount = ContentTransitions.Count;
				return _ContentTransitionCount;
			}
		}
		private TransitionInfoList _ContentTransitions = null;
		[TypeConverter(typeof(TransitionInfoListConverter))]
		public TransitionInfoList ContentTransitions
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentTransitions", true);
				if (_ContentTransitionCount < 0 || (_ContentTransitionCount > 0 && _ContentTransitions == null))
					_ContentTransitions = TransitionInfoList.GetByFromID(_ContentID);
				if (_ContentTransitionCount < 0)
					_ContentTransitionCount = _ContentTransitions.Count;
				return _ContentTransitions;
			}
		}
		public void RefreshContentTransitions()
		{
			_ContentTransitionCount = -1;
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_ContentID.ToString()))
				foreach (ContentInfo tmp in _CacheByPrimaryKey[_ContentID.ToString()])
					tmp._ContentTransitionCount = -1; // This will cause the data to be requeried
		}
		private int _ContentZContentCount = 0;
		/// 
		/// Count of ContentZContents for this Content
		/// 
		public int ContentZContentCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ContentZContentCount", true);
				return _ContentZContentCount;
			}
		}
		private ZContentInfo _MyZContent = null;
		[TypeConverter(typeof(ZContentInfoConverter))]
		public ZContentInfo MyZContent
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyZContent", true);
				if (_ContentZContentCount != 0 && _MyZContent == null)
				{
					_MyZContent = ZContentInfo.Get(_ContentID);
					_ContentZContentCount = _MyZContent == null ? 0 : 1;
				}
				return _MyZContent;
			}
		}
		// TODO: Replace base ContentInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current ContentInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// TODO: Check ContentInfo.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 ContentInfo
		protected override object GetIdValue()
		{
			return _ContentID;
		}
		#endregion
		#region Factory Methods
		private static int _ContentInfoUnique = 0;
		private static int ContentInfoUnique
		{ get { return ++_ContentInfoUnique; } }
		private int _MyContentInfoUnique = ContentInfoUnique;
		public int MyContentInfoUnique
		{ get { return _MyContentInfoUnique; } }
		protected ContentInfo()
		{/* require use of factory methods */
			AddToCache(this);
		}
		public void Dispose()
		{
			RemoveFromCache(this);
			if (!_CacheByPrimaryKey.ContainsKey(ContentID.ToString())) return;
			List listContentInfo = _CacheByPrimaryKey[ContentID.ToString()]; // Get the list of items
			while (listContentInfo.Contains(this)) listContentInfo.Remove(this); // Remove the item from the list
			if (listContentInfo.Count == 0) // If there are no items left in the list
				_CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list
		}
		public virtual Content Get()
		{
			return _Editable = Content.Get(_ContentID);
		}
		public static void Refresh(Content tmp)
		{
			string key = tmp.ContentID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (ContentInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(Content tmp)
		{
			_Number = tmp.Number;
			_Text = tmp.Text;
			_Type = tmp.Type;
			if (_FormatID != tmp.FormatID)
			{
				if (MyFormat != null) MyFormat.RefreshFormatContents(); // Update List for old value
				_FormatID = tmp.FormatID; // Update the value
			}
			_MyFormat = null; // Reset list so that the next line gets a new list
			if (MyFormat != null) MyFormat.RefreshFormatContents(); // Update List for new value
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_ContentInfoExtension.Refresh(this);
			if(_MyFormat != null)
			{
				_MyFormat.Dispose();// Dispose related value
				_MyFormat = null;// Reset related value
			}
			if(_MyEntry != null)
			{
				_MyEntry.Dispose();// Dispose related value
				_MyEntry = null;// Reset related value
			}
			_ContentEntryCount = -1;// Reset Count
			if(_MyZContent != null)
			{
				_MyZContent.Dispose();// Dispose related value
				_MyZContent = null;// Reset related value
			}
			_ContentZContentCount = -1;// Reset Count
			OnChange();// raise an event
		}
		public static void Refresh(FormatContent tmp)
		{
			string key = tmp.ContentID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (ContentInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(FormatContent tmp)
		{
			_Number = tmp.Number;
			_Text = tmp.Text;
			_Type = tmp.Type;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_ContentInfoExtension.Refresh(this);
			if(_MyFormat != null)
			{
				_MyFormat.Dispose();// Dispose related value
				_MyFormat = null;// Reset related value
			}
			if(_MyEntry != null)
			{
				_MyEntry.Dispose();// Dispose related value
				_MyEntry = null;// Reset related value
			}
			_ContentEntryCount = -1;// Reset Count
			if(_MyZContent != null)
			{
				_MyZContent.Dispose();// Dispose related value
				_MyZContent = null;// Reset related value
			}
			_ContentZContentCount = -1;// Reset Count
			OnChange();// raise an event
		}
		public static ContentInfo Get(int contentID)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a Content");
			try
			{
				ContentInfo tmp = GetCachedByPrimaryKey(contentID);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(contentID));
					AddToCache(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up ContentInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on ContentInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal ContentInfo(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentInfo.Constructor", ex);
				throw new DbCslaException("ContentInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _ContentID;
			public int ContentID
			{ get { return _ContentID; } }
			public PKCriteria(int contentID)
			{
				_ContentID = contentID;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentInfo.ReadData", GetHashCode());
			try
			{
				_ContentID = dr.GetInt32("ContentID");
				_Number = dr.GetString("Number");
				_Text = dr.GetString("Text");
				_Type = (int?)dr.GetValue("Type");
				_FormatID = (int?)dr.GetValue("FormatID");
				_Config = dr.GetString("Config");
				_DTS = dr.GetDateTime("DTS");
				_UserID = dr.GetString("UserID");
				_ContentDetailCount = dr.GetInt32("DetailCount");
				_ContentEntryCount = dr.GetInt32("EntryCount");
				_ContentItemCount = dr.GetInt32("ItemCount");
				_ContentPartCount = dr.GetInt32("PartCount");
				_ContentRoUsageCount = dr.GetInt32("RoUsageCount");
				_ContentTransitionCount = dr.GetInt32("TransitionCount");
				_ContentZContentCount = dr.GetInt32("ZContentCount");
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("ContentInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("ContentInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentInfo.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 = "getContent";
						cm.Parameters.AddWithValue("@ContentID", criteria.ContentID);
						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("ContentInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("ContentInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		ContentInfoExtension _ContentInfoExtension = new ContentInfoExtension();
		[Serializable()]
		partial class ContentInfoExtension : extensionBase { }
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(ContentInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class ContentInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is ContentInfo)
			{
				// Return the ToString value
				return ((ContentInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace