// ========================================================================
// 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 ROImageInfoEvent(object sender);
	/// 
	///	ROImageInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(ROImageInfoConverter))]
	public partial class ROImageInfo : ReadOnlyBase, IDisposable
	{
		public event ROImageInfoEvent 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(ROImageInfo rOImageInfo)
		{
			if (!_CacheList.Contains(rOImageInfo)) _CacheList.Add(rOImageInfo); // In AddToCache
		}
		protected static void RemoveFromCache(ROImageInfo rOImageInfo)
		{
			while (_CacheList.Contains(rOImageInfo)) _CacheList.Remove(rOImageInfo); // In RemoveFromCache
		}
		private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
		private static void ConvertListToDictionary()
		{
			while (_CacheList.Count > 0) // Move ROImageInfo(s) from temporary _CacheList to _CacheByPrimaryKey
			{
				ROImageInfo tmp = _CacheList[0]; // Get the first ROImageInfo
				string pKey = tmp.ImageID.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 ROImageInfo
			}
		}
		internal static void AddList(ROImageInfoList lst)
		{
			foreach (ROImageInfo item in lst) AddToCache(item);
		}
		protected static ROImageInfo GetCachedByPrimaryKey(int imageID)
		{
			ConvertListToDictionary();
			string key = imageID.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 ROImage _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _ImageID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int ImageID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ImageID", true);
				return _ImageID;
			}
		}
		private int _RODbID;
		public int RODbID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RODbID", true);
				if (_MyRODb != null) _RODbID = _MyRODb.RODbID;
				return _RODbID;
			}
		}
		private RODbInfo _MyRODb;
		public RODbInfo MyRODb
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyRODb", true);
				if (_MyRODb == null && _RODbID != 0) _MyRODb = RODbInfo.Get(_RODbID);
				return _MyRODb;
			}
		}
		private string _FileName = string.Empty;
		public string FileName
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("FileName", true);
				return _FileName;
			}
		}
		private byte[] _Content;
		public byte[] Content
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Content", true);
				return _Content;
			}
		}
		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 _ROImageFigureCount = 0;
		/// 
		/// Count of ROImageFigures for this ROImage
		/// 
		public int ROImageFigureCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ROImageFigureCount", true);
				if (_ROImageFigureCount < 0)
					_ROImageFigureCount = ROImageFigures.Count;
				return _ROImageFigureCount;
			}
		}
		private FigureInfoList _ROImageFigures = null;
		[TypeConverter(typeof(FigureInfoListConverter))]
		public FigureInfoList ROImageFigures
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("ROImageFigures", true);
				if (_ROImageFigureCount < 0 || (_ROImageFigureCount > 0 && _ROImageFigures == null))
					_ROImageFigures = FigureInfoList.GetByImageID(_ImageID);
				if (_ROImageFigureCount < 0)
					_ROImageFigureCount = _ROImageFigures.Count;
				return _ROImageFigures;
			}
		}
		public void RefreshROImageFigures()
		{
			_ROImageFigureCount = -1;
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(_ImageID.ToString()))
				foreach (ROImageInfo tmp in _CacheByPrimaryKey[_ImageID.ToString()])
					tmp._ROImageFigureCount = -1; // This will cause the data to be requeried
		}
		// CSLATODO: Replace base ROImageInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current ROImageInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// CSLATODO: Check ROImageInfo.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 ROImageInfo
		protected override object GetIdValue()
		{
			return MyROImageInfoUnique; // Absolutely Unique ID
		}
		#endregion
		#region Factory Methods
		private static int _ROImageInfoUnique = 0;
		private static int ROImageInfoUnique
		{ get { return ++_ROImageInfoUnique; } }
		private int _MyROImageInfoUnique = ROImageInfoUnique;
		public int MyROImageInfoUnique // Absolutely Unique ID - Info
		{ get { return _MyROImageInfoUnique; } }
		protected ROImageInfo()
		{/* 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; } }
		~ROImageInfo()
		{
			_CountFinalized++;
		}
		public void Dispose()
		{
			if (_Disposed) return;
			_CountDisposed++;
			_Disposed = true;
			RemoveFromCache(this);
			if (!_CacheByPrimaryKey.ContainsKey(ImageID.ToString())) return;
			List listROImageInfo = _CacheByPrimaryKey[ImageID.ToString()]; // Get the list of items
			while (listROImageInfo.Contains(this)) listROImageInfo.Remove(this); // Remove the item from the list
			if (listROImageInfo.Count == 0) // If there are no items left in the list
				_CacheByPrimaryKey.Remove(ImageID.ToString()); // remove the list
		}
		public virtual ROImage Get()
		{
			return _Editable = ROImage.Get(_ImageID);
		}
		public static void Refresh(ROImage tmp)
		{
			string key = tmp.ImageID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (ROImageInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(ROImage tmp)
		{
			if (_RODbID != tmp.RODbID)
			{
				if (MyRODb != null) MyRODb.RefreshRODbROImages(); // Update List for old value
				_RODbID = tmp.RODbID; // Update the value
			}
			_MyRODb = null; // Reset list so that the next line gets a new list
			if (MyRODb != null) MyRODb.RefreshRODbROImages(); // Update List for new value
			_FileName = tmp.FileName;
			_Content = tmp.Content;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_ROImageInfoExtension.Refresh(this);
			OnChange();// raise an event
		}
		public static void Refresh(RODbROImage tmp)
		{
			string key = tmp.ImageID.ToString();
			ConvertListToDictionary();
			if (_CacheByPrimaryKey.ContainsKey(key))
				foreach (ROImageInfo tmpInfo in _CacheByPrimaryKey[key])
					tmpInfo.RefreshFields(tmp);
		}
		protected virtual void RefreshFields(RODbROImage tmp)
		{
			_FileName = tmp.FileName;
			_Content = tmp.Content;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UserID = tmp.UserID;
			_ROImageInfoExtension.Refresh(this);
			OnChange();// raise an event
		}
		public static ROImageInfo Get(int imageID)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a ROImage");
			try
			{
				ROImageInfo tmp = GetCachedByPrimaryKey(imageID);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(imageID));
					AddToCache(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found")
				{
					tmp.Dispose(); // Clean-up ROImageInfo
					tmp = null;
				}
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on ROImageInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal ROImageInfo(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImageInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("ROImageInfo.Constructor", ex);
				throw new DbCslaException("ROImageInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _ImageID;
			public int ImageID
			{ get { return _ImageID; } }
			public PKCriteria(int imageID)
			{
				_ImageID = imageID;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImageInfo.ReadData", GetHashCode());
			try
			{
				_ImageID = dr.GetInt32("ImageID");
				_RODbID = dr.GetInt32("RODbID");
				_FileName = dr.GetString("FileName");
				_Content = (byte[])dr.GetValue("Content");
				_Config = dr.GetString("Config");
				_DTS = dr.GetDateTime("DTS");
				_UserID = dr.GetString("UserID");
				_ROImageFigureCount = dr.GetInt32("FigureCount");
			}
			catch (Exception ex)
			{
				if (_MyLog.IsErrorEnabled) _MyLog.Error("ROImageInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("ROImageInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ROImageInfo.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 = "getROImage";
						cm.Parameters.AddWithValue("@ImageID", criteria.ImageID);
						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("ROImageInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("ROImageInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		ROImageInfoExtension _ROImageInfoExtension = new ROImageInfoExtension();
		[Serializable()]
		partial class ROImageInfoExtension : extensionBase { }
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(ROImageInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class ROImageInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is ROImageInfo)
			{
				// Return the ToString value
				return ((ROImageInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace