// ========================================================================
// 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 PermissionInfoEvent(object sender);
	/// 
	///	PermissionInfo Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(PermissionInfoConverter))]
	public partial class PermissionInfo : ReadOnlyBase, IDisposable
	{
		public event PermissionInfoEvent 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
		protected static List _AllList = new List();
		private static Dictionary _AllByPrimaryKey = new Dictionary();
		private static void ConvertListToDictionary()
		{
			List remove = new List();
			foreach (PermissionInfo tmp in _AllList)
			{
				_AllByPrimaryKey[tmp.PID.ToString()]=tmp; // Primary Key
				remove.Add(tmp);
			}
			foreach (PermissionInfo tmp in remove)
				_AllList.Remove(tmp);
		}
		internal static void AddList(PermissionInfoList lst)
		{
			foreach (PermissionInfo item in lst) _AllList.Add(item);
		}
		public static PermissionInfo GetExistingByPrimaryKey(int pid)
		{
			ConvertListToDictionary();
			string key = pid.ToString();
			if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; 
			return null;
		}
		#endregion
		#region Business Methods
		private string _ErrorMessage = string.Empty;
		public string ErrorMessage
		{
			get { return _ErrorMessage; }
		}
		protected Permission _Editable;
		private IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = null;
				if (_Editable != null)
					hasBrokenRules = _Editable.HasBrokenRules;
				return hasBrokenRules;
			}
		}
		private int _PID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int PID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PID",true);
				return _PID;
			}
		}
		private int _RID;
		public int RID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RID",true);
				if (_MyRole != null) _RID = _MyRole.RID;
				return _RID;
			}
		}
		private RoleInfo _MyRole;
		public RoleInfo MyRole
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyRole",true);
				if (_MyRole == null && _RID != 0) _MyRole = RoleInfo.Get(_RID);
				return _MyRole;
			}
		}
		private int _PermLevel;
		/// 
		/// 0 - None, 1 - Security, 2 - System, 3 - RO, 4 - Procdures, 5 - Sections, 6 - Steps, 7 - Comments
		/// 
		public int PermLevel
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PermLevel",true);
				return _PermLevel;
			}
		}
		private int _VersionType;
		/// 
		/// 0 - None, 1 - Working Draft, 2 - Approved, (3 - All)
		/// 
		public int VersionType
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("VersionType",true);
				return _VersionType;
			}
		}
		private int _PermValue;
		/// 
		/// 1 - Read, 2 - Write, 4 - Create, 8 - Delete (15 - All)
		/// 
		public int PermValue
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PermValue",true);
				return _PermValue;
			}
		}
		private int _PermAD;
		/// 
		/// 0 - Allow, 1 - Deny
		/// 
		public int PermAD
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PermAD",true);
				return _PermAD;
			}
		}
		private string _StartDate = string.Empty;
		public string StartDate
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("StartDate",true);
				return _StartDate;
			}
		}
		private string _EndDate = string.Empty;
		public string EndDate
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("EndDate",true);
				return _EndDate;
			}
		}
		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 _UsrID = string.Empty;
		public string UsrID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("UsrID",true);
				return _UsrID;
			}
		}
		// TODO: Replace base PermissionInfo.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current PermissionInfo
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// TODO: Check PermissionInfo.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 PermissionInfo
		protected override object GetIdValue()
		{
			return _PID;
		}
		#endregion
		#region Factory Methods
		private PermissionInfo()
		{/* require use of factory methods */
			_AllList.Add(this);
		}
		public void Dispose()
		{
			_AllList.Remove(this);
			_AllByPrimaryKey.Remove(PID.ToString());
		}
		public virtual Permission Get()
		{
			return _Editable = Permission.Get(_PID);
		}
		public static void Refresh(Permission tmp)
		{
			PermissionInfo tmpInfo = GetExistingByPrimaryKey(tmp.PID);
			if (tmpInfo == null) return;
			tmpInfo.RefreshFields(tmp);
		}
		private void RefreshFields(Permission tmp)
		{
			_RID = tmp.RID;
			_PermLevel = tmp.PermLevel;
			_VersionType = tmp.VersionType;
			_PermValue = tmp.PermValue;
			_PermAD = tmp.PermAD;
			_StartDate = tmp.StartDate;
			_EndDate = tmp.EndDate;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UsrID = tmp.UsrID;
			_PermissionInfoExtension.Refresh(this);
			_MyRole = null;
			OnChange();// raise an event
		}
		public static void Refresh(RolePermission tmp)
		{
			PermissionInfo tmpInfo = GetExistingByPrimaryKey(tmp.PID);
			if (tmpInfo == null) return;
			tmpInfo.RefreshFields(tmp);
		}
		private void RefreshFields(RolePermission tmp)
		{
			_PermLevel = tmp.PermLevel;
			_VersionType = tmp.VersionType;
			_PermValue = tmp.PermValue;
			_PermAD = tmp.PermAD;
			_StartDate = tmp.StartDate;
			_EndDate = tmp.EndDate;
			_Config = tmp.Config;
			_DTS = tmp.DTS;
			_UsrID = tmp.UsrID;
			_PermissionInfoExtension.Refresh(this);
			_MyRole = null;
			OnChange();// raise an event
		}
		public static PermissionInfo Get(int pid)
		{
			//if (!CanGetObject())
			//  throw new System.Security.SecurityException("User not authorized to view a Permission");
			try
			{
				PermissionInfo tmp = GetExistingByPrimaryKey(pid);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(pid));
					_AllList.Add(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found") tmp = null;
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on PermissionInfo.Get", ex);
			}
		}
		#endregion
		#region Data Access Portal
		internal PermissionInfo(SafeDataReader dr)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] PermissionInfo.Constructor", GetHashCode());
			try
			{
				ReadData(dr);
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("PermissionInfo.Constructor", ex);
				throw new DbCslaException("PermissionInfo.Constructor", ex);
			}
		}
		[Serializable()]
		protected class PKCriteria
		{
			private int _PID;
			public int PID
			{ get { return _PID; } }
			public PKCriteria(int pid)
			{
				_PID = pid;
			}
		}
		private void ReadData(SafeDataReader dr)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] PermissionInfo.ReadData", GetHashCode());
			try
			{
				_PID = dr.GetInt32("PID");
				_RID = dr.GetInt32("RID");
				_PermLevel = dr.GetInt32("PermLevel");
				_VersionType = dr.GetInt32("VersionType");
				_PermValue = dr.GetInt32("PermValue");
				_PermAD = dr.GetInt32("PermAD");
				_StartDate = dr.GetSmartDate("StartDate").Text;
				_EndDate = dr.GetSmartDate("EndDate").Text;
				_Config = dr.GetString("Config");
				_DTS = dr.GetDateTime("DTS");
				_UsrID = dr.GetString("UsrID");
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("PermissionInfo.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("PermissionInfo.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] PermissionInfo.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 = "getPermission";
						cm.Parameters.AddWithValue("@PID", criteria.PID);
						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("PermissionInfo.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("PermissionInfo.DataPortal_Fetch", ex);
			}
		}
		#endregion
		// Standard Refresh
		#region extension
		PermissionInfoExtension _PermissionInfoExtension = new PermissionInfoExtension();
		[Serializable()]
		partial class PermissionInfoExtension : extensionBase {}
		[Serializable()]
		class extensionBase
		{
			// Default Refresh
			public virtual void Refresh(PermissionInfo tmp) { }
		}
		#endregion
	} // Class
	#region Converter
	internal class PermissionInfoConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is PermissionInfo)
			{
				// Return the ToString value
				return ((PermissionInfo)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace