// ========================================================================
// 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 Csla.Validation;
namespace VEPROMS.CSLA.Library
{
	/// 
	///	RolePermission Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(RolePermissionConverter))]
	public partial class RolePermission : BusinessBase, IVEHasBrokenRules
	{
		#region Log4Net
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion
		#region Business Methods
		private string _ErrorMessage = string.Empty;
		public string ErrorMessage
		{
			get { return _ErrorMessage; }
		}
		private int _PID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int PID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("PID",true);
				if (_MyPermission != null) _PID = _MyPermission.PID;
				return _PID;
			}
		}
		private Permission _MyPermission;
		[System.ComponentModel.DataObjectField(true, true)]
		public Permission MyPermission
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("MyPermission",true);
				if (_MyPermission == null && _PID != 0) _MyPermission = Permission.Get(_PID);
				return _MyPermission;
			}
		}
		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;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("PermLevel",true);
				if (_PermLevel != value)
				{
					_PermLevel = value;
					PropertyHasChanged();
				}
			}
		}
		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;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("VersionType",true);
				if (_VersionType != value)
				{
					_VersionType = value;
					PropertyHasChanged();
				}
			}
		}
		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;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("PermValue",true);
				if (_PermValue != value)
				{
					_PermValue = value;
					PropertyHasChanged();
				}
			}
		}
		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;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("PermAD",true);
				if (_PermAD != value)
				{
					_PermAD = value;
					PropertyHasChanged();
				}
			}
		}
		private string _StartDate = string.Empty;
		public string StartDate
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("StartDate",true);
				return _StartDate;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("StartDate",true);
				if (value == null) value = string.Empty;
				_StartDate = value;
				try
				{
					SmartDate tmp = new SmartDate(value);
					if (_StartDate != tmp.ToString())
					{
						_StartDate = tmp.ToString();
						// TODO: Any Cross Property Validation
					}
				}
				catch
				{
				}
				PropertyHasChanged();
			}
		}
		private string _EndDate = string.Empty;
		public string EndDate
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("EndDate",true);
				return _EndDate;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("EndDate",true);
				if (value == null) value = string.Empty;
				_EndDate = value;
				try
				{
					SmartDate tmp = new SmartDate(value);
					if (_EndDate != tmp.ToString())
					{
						_EndDate = tmp.ToString();
						// TODO: Any Cross Property Validation
					}
				}
				catch
				{
				}
				PropertyHasChanged();
			}
		}
		private string _Config = string.Empty;
		public string Config
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Config",true);
				return _Config;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("Config",true);
				if (value == null) value = string.Empty;
				if (_Config != value)
				{
					_Config = value;
					PropertyHasChanged();
				}
			}
		}
		private DateTime _DTS = new DateTime();
		public DateTime DTS
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("DTS",true);
				return _DTS;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("DTS",true);
				if (_DTS != value)
				{
					_DTS = value;
					PropertyHasChanged();
				}
			}
		}
		private string _UsrID = string.Empty;
		public string UsrID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("UsrID",true);
				return _UsrID;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("UsrID",true);
				if (value == null) value = string.Empty;
				if (_UsrID != value)
				{
					_UsrID = value;
					PropertyHasChanged();
				}
			}
		}
		private byte[] _LastChanged = new byte[8];//timestamp
		// TODO: Check RolePermission.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 RolePermission
		protected override object GetIdValue()
		{
			return _PID;
		}
		// TODO: Replace base RolePermission.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current RolePermission
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		#endregion
		#region ValidationRules
		[NonSerialized]
		private bool _CheckingBrokenRules=false;
		public IVEHasBrokenRules HasBrokenRules
		{
			get
			{
				if(_CheckingBrokenRules)return null;
				if (BrokenRulesCollection.Count > 0) return this;
				try
				{
					_CheckingBrokenRules=true;
				 IVEHasBrokenRules hasBrokenRules = null;
				 return hasBrokenRules;
				}
				finally
				{
					_CheckingBrokenRules=false;
				}
			}
		}
		public BrokenRulesCollection BrokenRules
		{
			get
			{
				IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
				if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
				return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
			}
		}
		protected override void AddBusinessRules()
		{
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringRequired, "StartDate");
			ValidationRules.AddRule(StartDateValid, "StartDate");
			ValidationRules.AddRule(EndDateValid, "EndDate");
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringMaxLength,
				new Csla.Validation.CommonRules.MaxLengthRuleArgs("Config", 1073741823));
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringRequired, "UsrID");
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringMaxLength,
				new Csla.Validation.CommonRules.MaxLengthRuleArgs("UsrID", 100));
			// TODO:  Add other validation rules
		}
		private static bool StartDateValid(RolePermission target, Csla.Validation.RuleArgs e)
		{
			try
			{
				DateTime tmp = SmartDate.StringToDate(target._StartDate);
			}
			catch
			{
				e.Description = "Invalid Date";
				return false;
			}
			return true;
		}
		private static bool EndDateValid(RolePermission target, Csla.Validation.RuleArgs e)
		{
			try
			{
				DateTime tmp = SmartDate.StringToDate(target._EndDate);
			}
			catch
			{
				e.Description = "Invalid Date";
				return false;
			}
			return true;
		}
		// Sample data comparison validation rule
		//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
		//{
		//	if (_started > _ended)
		//	{
		//		e.Description = "Start date can't be after end date";
		//		return false;
		//	}
		//	else
		//		return true;
		//}
		#endregion
		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Who can read/write which fields
			//AuthorizationRules.AllowRead(PID, "");
			//AuthorizationRules.AllowRead(PermLevel, "");
			//AuthorizationRules.AllowWrite(PermLevel, "");
			//AuthorizationRules.AllowRead(VersionType, "");
			//AuthorizationRules.AllowWrite(VersionType, "");
			//AuthorizationRules.AllowRead(PermValue, "");
			//AuthorizationRules.AllowWrite(PermValue, "");
			//AuthorizationRules.AllowRead(PermAD, "");
			//AuthorizationRules.AllowWrite(PermAD, "");
			//AuthorizationRules.AllowRead(StartDate, "");
			//AuthorizationRules.AllowWrite(StartDate, "");
			//AuthorizationRules.AllowRead(EndDate, "");
			//AuthorizationRules.AllowWrite(EndDate, "");
			//AuthorizationRules.AllowRead(Config, "");
			//AuthorizationRules.AllowWrite(Config, "");
			//AuthorizationRules.AllowRead(DTS, "");
			//AuthorizationRules.AllowWrite(DTS, "");
			//AuthorizationRules.AllowRead(UsrID, "");
			//AuthorizationRules.AllowWrite(UsrID, "");
		}
		public static bool CanAddObject()
		{
			// TODO: Can Add Authorization
			//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
			return true;
		}
		public static bool CanGetObject()
		{
			// TODO: CanGet Authorization
			return true;
		}
		public static bool CanDeleteObject()
		{
			// TODO: CanDelete Authorization
			//bool result = false;
			//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
			//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
			//return result;
			return true;
		}
		public static bool CanEditObject()
		{
			// TODO: CanEdit Authorization
			//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
			return true;
		}
		#endregion
		#region Factory Methods
		public int CurrentEditLevel
		{ get { return EditLevel; } }
		internal static RolePermission New(int permLevel, int versionType, int permValue)
		{
			return new RolePermission(permLevel, versionType, permValue);
		}
		internal static RolePermission Get(SafeDataReader dr)
		{
			return new RolePermission(dr);
		}
		public RolePermission()
		{
			MarkAsChild();
			_PID = Permission.NextPID;
			_PermAD = _RolePermissionExtension.DefaultPermAD;
			_StartDate = _RolePermissionExtension.DefaultStartDate;
			_DTS = _RolePermissionExtension.DefaultDTS;
			_UsrID = _RolePermissionExtension.DefaultUsrID;
			ValidationRules.CheckRules();
		}
		private RolePermission(int permLevel, int versionType, int permValue)
		{
			MarkAsChild();
			// TODO: Add any initialization & defaults
			_PermAD = _RolePermissionExtension.DefaultPermAD;
			_StartDate = _RolePermissionExtension.DefaultStartDate;
			_DTS = _RolePermissionExtension.DefaultDTS;
			_UsrID = _RolePermissionExtension.DefaultUsrID;
			_PermLevel  = permLevel;
			_VersionType  = versionType;
			_PermValue  = permValue;
			ValidationRules.CheckRules();
		}
		internal RolePermission(SafeDataReader dr)
		{
			MarkAsChild();
			Fetch(dr);
		}
		#endregion
		#region Data Access Portal
		private void Fetch(SafeDataReader dr)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] RolePermission.FetchDR", GetHashCode());
			try
			{
				_PID = dr.GetInt32("PID");
				_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");
				dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8);
			}
			catch (Exception ex) // FKItem Fetch
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("RolePermission.FetchDR", ex);
				throw new DbCslaException("RolePermission.Fetch", ex);
			}
			MarkOld();
		}
		internal void Insert(Role myRole)
		{
			// if we're not dirty then don't update the database
			if (!this.IsDirty) return;
			SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
			_LastChanged = Permission.Add(cn, ref _PID, myRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID);
			MarkOld();
		}
		internal void Update(Role myRole)
		{
			// if we're not dirty then don't update the database
			if (!this.IsDirty) return;
			SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
			_LastChanged = Permission.Update(cn, ref _PID, myRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged);
			MarkOld();
		}
		internal void DeleteSelf(Role myRole)
		{
			// if we're not dirty then don't update the database
			if (!this.IsDirty) return;
			// if we're new then don't update the database
			if (this.IsNew) return;
			SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
			Permission.Remove(cn, _PID);
			MarkNew();
		}
		#endregion
		// Standard Default Code
		#region extension
		RolePermissionExtension _RolePermissionExtension = new RolePermissionExtension();
		[Serializable()]
		partial class RolePermissionExtension : extensionBase
		{
		}
		[Serializable()]
		class extensionBase
		{
			// Default Values
			public virtual int DefaultPermAD
			{
				get { return 0; }
			}
			public virtual string DefaultStartDate
			{
				get { return DateTime.Now.ToShortDateString(); }
			}
			public virtual DateTime DefaultDTS
			{
				get { return DateTime.Now; }
			}
			public virtual string DefaultUsrID
			{
				get { return Environment.UserName.ToUpper(); }
			}
			// Authorization Rules
			public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
			{
				// Needs to be overriden to add new authorization rules
			}
			// Instance Authorization Rules
			public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
			{
				// Needs to be overriden to add new authorization rules
			}
			// Validation Rules
			public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
			{
				// Needs to be overriden to add new validation rules
			}
			// InstanceValidation Rules
			public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
			{
				// Needs to be overriden to add new validation rules
			}
		}
		#endregion
	} // Class
	#region Converter
	internal class RolePermissionConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is RolePermission)
			{
				// Return the ToString value
				return ((RolePermission)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace
//// The following is a sample Extension File.  You can use it to create RolePermissionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
//  public partial class RolePermission
//  {
//    partial class RolePermissionExtension : extensionBase
//    {
//      // TODO: Override automatic defaults
//      public virtual int DefaultPermAD
//      {
//        get { return 0; }
//      }
//      public virtual SmartDate DefaultStartDate
//      {
//        get { return DateTime.Now.ToShortDateString(); }
//      }
//      public virtual DateTime DefaultDTS
//      {
//        get { return DateTime.Now; }
//      }
//      public virtual string DefaultUsrID
//      {
//        get { return Environment.UserName.ToUpper(); }
//      }
//      public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
//      {
//        //rules.AllowRead(Dbid, "");
//      }
//      public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
//      {
//        //rules.AllowInstanceRead(Dbid, "");
//      }
//      public new void AddValidationRules(Csla.Validation.ValidationRules rules)
//      {
//        rules.AddRule(
//          Csla.Validation.CommonRules.StringMaxLength,
//          new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
//      }
//      public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
//      {
//        rules.AddInstanceRule(/* Instance Validation Rule */);
//      }
//    }
//  }
//}