// ========================================================================
// 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;
using Csla.Validation;
namespace VEPROMS.CSLA.Library
{
	/// 
	///	Role Generated by MyGeneration using the CSLA Object Mapping template
	/// 
	[Serializable()]
	[TypeConverter(typeof(RoleConverter))]
	public partial class Role : BusinessBase, IDisposable, IVEHasBrokenRules
	{
		#region Log4Net
		private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		#endregion
		#region Refresh
		private List _RefreshRoles = new List();
		private List _RefreshRoleAssignments = new List();
		private List _RefreshRolePermissions = new List();
		private void AddToRefreshList(List refreshRoles, List refreshRoleAssignments, List refreshRolePermissions)
		{
			if (IsDirty)
				refreshRoles.Add(this);
			if (_RoleAssignments != null && _RoleAssignments.IsDirty)
			{
				foreach (RoleAssignment tmp in _RoleAssignments)
				{
					if(tmp.IsDirty)refreshRoleAssignments.Add(tmp);
				}
			}
			if (_RolePermissions != null && _RolePermissions.IsDirty)
			{
				foreach (RolePermission tmp in _RolePermissions)
				{
					if(tmp.IsDirty)refreshRolePermissions.Add(tmp);
				}
			}
		}
		private void BuildRefreshList()
		{
			_RefreshRoles = new List();
			_RefreshRoleAssignments = new List();
			_RefreshRolePermissions = new List();
			AddToRefreshList(_RefreshRoles, _RefreshRoleAssignments, _RefreshRolePermissions);
		}
		private void ProcessRefreshList()
		{
			foreach (Role tmp in _RefreshRoles)
			{
				RoleInfo.Refresh(tmp);
			}
			foreach (RoleAssignment tmp in _RefreshRoleAssignments)
			{
				AssignmentInfo.Refresh(tmp);
			}
			foreach (RolePermission tmp in _RefreshRolePermissions)
			{
				PermissionInfo.Refresh(tmp);
			}
		}
		#endregion
		#region Collection
		protected static List _AllList = new List();
		private static Dictionary _AllByPrimaryKey = new Dictionary();
		private static Dictionary _AllByName = new Dictionary();
		private static void ConvertListToDictionary()
		{
			List remove = new List();
			foreach (Role tmp in _AllList)
			{
				_AllByPrimaryKey[tmp.RID.ToString()]=tmp; // Primary Key
				_AllByName[tmp.Name.ToString()] = tmp; // Unique Index
				remove.Add(tmp);
			}
			foreach (Role tmp in remove)
				_AllList.Remove(tmp);
		}
		public static Role GetExistingByPrimaryKey(int rid)
		{
			ConvertListToDictionary();
			string key = rid.ToString();
			if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; 
			return null;
		}
		public static Role GetExistingByName(string name)
		{
			ConvertListToDictionary();
			string key = name.ToString();
			if (_AllByName.ContainsKey(key)) return _AllByName[key];
			return null;
		}
		#endregion
		#region Business Methods
		private string _ErrorMessage = string.Empty;
		public string ErrorMessage
		{
			get { return _ErrorMessage; }
		}
		private static int _nextRID = -1;
		public static int NextRID
		{
			get { return _nextRID--; }
		}
		private int _RID;
		[System.ComponentModel.DataObjectField(true, true)]
		public int RID
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RID",true);
				return _RID;
			}
		}
		private string _Name = string.Empty;
		public string Name
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Name",true);
				return _Name;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("Name",true);
				if (value == null) value = string.Empty;
				if (_Name != value)
				{
					_Name = value;
					PropertyHasChanged();
				}
			}
		}
		private string _Title = string.Empty;
		public string Title
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("Title",true);
				return _Title;
			}
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			set
			{
				CanWriteProperty("Title",true);
				if (value == null) value = string.Empty;
				if (_Title != value)
				{
					_Title = 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
		private int _RoleAssignmentCount = 0;
		/// 
		/// Count of RoleAssignments for this Role
		/// 
		public int RoleAssignmentCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RoleAssignmentCount",true);
				return _RoleAssignmentCount;
			}
		}
		private RoleAssignments _RoleAssignments = null;
		/// 
		/// Related Field
		/// 
		[TypeConverter(typeof(RoleAssignmentsConverter))]
		public RoleAssignments RoleAssignments
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RoleAssignments",true);
				if(_RoleAssignmentCount > 0 && _RoleAssignments == null)
					_RoleAssignments = RoleAssignments.GetByRID(RID);
				else if(_RoleAssignments == null)
					_RoleAssignments = RoleAssignments.New();
				return _RoleAssignments;
			}
		}
		private int _RolePermissionCount = 0;
		/// 
		/// Count of RolePermissions for this Role
		/// 
		public int RolePermissionCount
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RolePermissionCount",true);
				return _RolePermissionCount;
			}
		}
		private RolePermissions _RolePermissions = null;
		/// 
		/// Related Field
		/// 
		[TypeConverter(typeof(RolePermissionsConverter))]
		public RolePermissions RolePermissions
		{
			[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
			get
			{
				CanReadProperty("RolePermissions",true);
				if(_RolePermissionCount > 0 && _RolePermissions == null)
					_RolePermissions = RolePermissions.GetByRID(RID);
				else if(_RolePermissions == null)
					_RolePermissions = RolePermissions.New();
				return _RolePermissions;
			}
		}
		public override bool IsDirty
		{
			get { return base.IsDirty || (_RoleAssignments == null? false : _RoleAssignments.IsDirty) || (_RolePermissions == null? false : _RolePermissions.IsDirty); }
		}
		public override bool IsValid
		{
			get { return (IsNew && !IsDirty ? true : base.IsValid) && (_RoleAssignments == null? true : _RoleAssignments.IsValid) && (_RolePermissions == null? true : _RolePermissions.IsValid); }
		}
		// TODO: Replace base Role.ToString function as necessary
		/// 
		/// Overrides Base ToString
		/// 
		/// A string representation of current Role
		//public override string ToString()
		//{
		//  return base.ToString();
		//}
		// TODO: Check Role.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 Role
		protected override object GetIdValue()
		{
			return _RID;
		}
		#endregion
		#region ValidationRules
		[NonSerialized]
		private bool _CheckingBrokenRules=false;
		public IVEHasBrokenRules HasBrokenRules
		{
			get {
				if(_CheckingBrokenRules)return null;
				if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this;
				try
				{
					_CheckingBrokenRules=true;
					IVEHasBrokenRules hasBrokenRules = null;
				if (_RoleAssignments != null && (hasBrokenRules = _RoleAssignments.HasBrokenRules) != null) return hasBrokenRules;
				if (_RolePermissions != null && (hasBrokenRules = _RolePermissions.HasBrokenRules) != null) return hasBrokenRules;
					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, "Name");
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringMaxLength,
				new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 50));
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringRequired, "Title");
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringMaxLength,
				new Csla.Validation.CommonRules.MaxLengthRuleArgs("Title", 250));
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringRequired, "UsrID");
			ValidationRules.AddRule(
				Csla.Validation.CommonRules.StringMaxLength,
				new Csla.Validation.CommonRules.MaxLengthRuleArgs("UsrID", 100));
			//ValidationRules.AddDependantProperty("x", "y");
			_RoleExtension.AddValidationRules(ValidationRules);
			// TODO:  Add other validation rules
		}
		protected override void AddInstanceBusinessRules()
		{
			_RoleExtension.AddInstanceValidationRules(ValidationRules);
			// TODO:  Add other validation rules
		}
		// 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(RID, "");
			//AuthorizationRules.AllowRead(Name, "");
			//AuthorizationRules.AllowRead(Title, "");
			//AuthorizationRules.AllowRead(DTS, "");
			//AuthorizationRules.AllowRead(UsrID, "");
			//AuthorizationRules.AllowWrite(Name, "");
			//AuthorizationRules.AllowWrite(Title, "");
			//AuthorizationRules.AllowWrite(DTS, "");
			//AuthorizationRules.AllowWrite(UsrID, "");
			_RoleExtension.AddAuthorizationRules(AuthorizationRules);
		}
		protected override void AddInstanceAuthorizationRules()
		{
			//TODO: Who can read/write which fields
			_RoleExtension.AddInstanceAuthorizationRules(AuthorizationRules);
		}
		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;
		}
		/// 
		/// determines if related records (Foreign Keys) will keep this Item from being deleted
		/// 
		public bool CanDelete
		{
			get
			{
				// Check to make sure that there are not any related records
				int usedByCount = 0;
				usedByCount += _RoleAssignmentCount;
				usedByCount += _RolePermissionCount;
				return (usedByCount == 0);
			}
		}
		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; } }
		protected Role()
		{/* require use of factory methods */
			_AllList.Add(this);
		}
		public void Dispose()
		{
			_AllList.Remove(this);
			_AllByPrimaryKey.Remove(RID.ToString());
			_AllByName.Remove(Name.ToString());
		}
		public static Role New()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Role");
			try
			{
				return DataPortal.Create();
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on Role.New", ex);
			}
		}
		public static Role New(string name, string title)
		{
			Role tmp = Role.New();
			tmp.Name = name;
			tmp.Title = title;
			return tmp;
		}
		public static Role New(string name, string title, DateTime dts, string usrID)
		{
			Role tmp = Role.New();
			tmp.Name = name;
			tmp.Title = title;
			tmp.DTS = dts;
			tmp.UsrID = usrID;
			return tmp;
		}
		public static Role MakeRole(string name, string title, DateTime dts, string usrID)
		{
			Role tmp = Role.New(name, title, dts, usrID);
			if (tmp.IsSavable)
				tmp = tmp.Save();
			else
			{
				Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules();
				tmp._ErrorMessage = "Failed Validation:";
				foreach (Csla.Validation.BrokenRule br in brc)
				{
					tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName;
				}
			}
			return tmp;
		}
		public static Role Get(int rid)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Role");
			try
			{
				Role tmp = GetExistingByPrimaryKey(rid);
				if (tmp == null)
				{
					tmp = DataPortal.Fetch(new PKCriteria(rid));
					_AllList.Add(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found") tmp = null;
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on Role.Get", ex);
			}
		}
		private static Role GetByName(string name)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Role");
			try
			{
				Role tmp = GetExistingByName(name);
				if (tmp == null)
				{
					tmp=DataPortal.Fetch(new NameCriteria(name));
					_AllList.Add(tmp);
				}
				if (tmp.ErrorMessage == "No Record Found") tmp = null;
				return tmp;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on Role.GetByName", ex);
			}
		}
		public static Role Get(SafeDataReader dr)
		{
			if (dr.Read()) return new Role(dr);
			return null;
		}
		internal Role(SafeDataReader dr)
		{
			ReadData(dr);
		}
		public static void Delete(int rid)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Role");
			try
			{
				DataPortal.Delete(new PKCriteria(rid));
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on Role.Delete", ex);
			}
		}
		public override Role Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Role");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Role");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a Role");
			try
			{
				BuildRefreshList();
				Role role = base.Save();
				_AllList.Add(role);//Refresh the item in AllList
				ProcessRefreshList();
				return role;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on CSLA Save", ex);
			}
		}
		#endregion
		#region Data Access Portal
		[Serializable()]
		protected class PKCriteria
		{
			private int _RID;
			public int RID
			{ get { return _RID; } }
			public PKCriteria(int rid)
			{
				_RID = rid;
			}
		}
		[Serializable()]
		private class NameCriteria
		{
			private string _Name;
			public string Name
			{ get { return _Name; } }
			public NameCriteria(string name)
			{
				_Name = name;
			}
		}
		// TODO: If Create needs to access DB - It should not be marked RunLocal
		[RunLocal()]
		private new void DataPortal_Create()
		{
			_RID = NextRID;
			// Database Defaults
			_DTS = _RoleExtension.DefaultDTS;
			_UsrID = _RoleExtension.DefaultUsrID;
			// TODO: Add any defaults that are necessary
			ValidationRules.CheckRules();
		}
		private void ReadData(SafeDataReader dr)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.ReadData", GetHashCode());
			try
			{
				_RID = dr.GetInt32("RID");
				_Name = dr.GetString("Name");
				_Title = dr.GetString("Title");
				_DTS = dr.GetDateTime("DTS");
				_UsrID = dr.GetString("UsrID");
				dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8);
				_RoleAssignmentCount = dr.GetInt32("AssignmentCount");
				_RolePermissionCount = dr.GetInt32("PermissionCount");
				MarkOld();
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.ReadData", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("Role.ReadData", ex);
			}
		}
		private void DataPortal_Fetch(PKCriteria criteria)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.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 = "getRole";
						cm.Parameters.AddWithValue("@RID", criteria.RID);
						using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
						{
							if (!dr.Read())
							{
								_ErrorMessage = "No Record Found";
								return;
							}
							ReadData(dr);
							// load child objects
							dr.NextResult();
							_RoleAssignments = RoleAssignments.Get(dr);
							// load child objects
							dr.NextResult();
							_RolePermissions = RolePermissions.Get(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("Role.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("Role.DataPortal_Fetch", ex);
			}
		}
		private void DataPortal_Fetch(NameCriteria criteria)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.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 = "getRoleByName";
						cm.Parameters.AddWithValue("@Name", criteria.Name);
						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("Role.DataPortal_Fetch", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("Role.DataPortal_Fetch", ex);
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		protected override void DataPortal_Insert()
		{
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					SQLInsert();
					// 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("Role.DataPortal_Insert", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("Role.DataPortal_Insert", ex);
			}
			finally
			{
				if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.DataPortal_Insert", GetHashCode());
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		internal void SQLInsert()
		{
			if (!this.IsDirty) return;
			try
			{
				SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
				using (SqlCommand cm = cn.CreateCommand())
				{
					cm.CommandType = CommandType.StoredProcedure;
					cm.CommandText = "addRole";
					// Input All Fields - Except Calculated Columns
					cm.Parameters.AddWithValue("@Name", _Name);
					cm.Parameters.AddWithValue("@Title", _Title);
					if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
					cm.Parameters.AddWithValue("@UsrID", _UsrID);
					// Output Calculated Columns
					SqlParameter param_RID = new SqlParameter("@newRID", SqlDbType.Int);
					param_RID.Direction = ParameterDirection.Output;
					cm.Parameters.Add(param_RID);
					SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp);
					param_LastChanged.Direction = ParameterDirection.Output;
					cm.Parameters.Add(param_LastChanged);
					// TODO: Define any additional output parameters
					cm.ExecuteNonQuery();
					// Save all values being returned from the Procedure
					_RID = (int)cm.Parameters["@newRID"].Value;
					_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
				}
				MarkOld();
				// update child objects
				if (_RoleAssignments != null) _RoleAssignments.Update(this);
				if (_RolePermissions != null) _RolePermissions.Update(this);
				if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.SQLInsert", GetHashCode());
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.SQLInsert", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("Role.SQLInsert", ex);
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		public static byte[] Add(SqlConnection cn, ref int rid, string name, string title, DateTime dts, string usrID)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.Add", 0);
			try
			{
				using (SqlCommand cm = cn.CreateCommand())
				{
					cm.CommandType = CommandType.StoredProcedure;
					cm.CommandText = "addRole";
					// Input All Fields - Except Calculated Columns
					cm.Parameters.AddWithValue("@Name", name);
					cm.Parameters.AddWithValue("@Title", title);
					if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
					cm.Parameters.AddWithValue("@UsrID", usrID);
					// Output Calculated Columns
					SqlParameter param_RID = new SqlParameter("@newRID", SqlDbType.Int);
					param_RID.Direction = ParameterDirection.Output;
					cm.Parameters.Add(param_RID);
					SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp);
					param_LastChanged.Direction = ParameterDirection.Output;
					cm.Parameters.Add(param_LastChanged);
					// TODO: Define any additional output parameters
					cm.ExecuteNonQuery();
					// Save all values being returned from the Procedure
					rid = (int)cm.Parameters["@newRID"].Value;
					return (byte[])cm.Parameters["@newLastChanged"].Value;
				}
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.Add", ex);
				throw new DbCslaException("Role.Add", ex);
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		protected override void DataPortal_Update()
		{
			if (!IsDirty) return;	// If not dirty - nothing to do
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.DataPortal_Update", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					ApplicationContext.LocalContext["cn"] = cn;
					SQLUpdate();
					// 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("Role.DataPortal_Update", ex);
				_ErrorMessage = ex.Message;
				if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		internal void SQLUpdate()
		{
			if (!IsDirty) return;	// If not dirty - nothing to do
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.SQLUpdate", GetHashCode());
			try
			{
				SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
				if (base.IsDirty)
				{
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "updateRole";
						// All Fields including Calculated Fields
						cm.Parameters.AddWithValue("@RID", _RID);
						cm.Parameters.AddWithValue("@Name", _Name);
						cm.Parameters.AddWithValue("@Title", _Title);
						if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
						cm.Parameters.AddWithValue("@UsrID", _UsrID);
						cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
						// Output Calculated Columns
						SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp);
						param_LastChanged.Direction = ParameterDirection.Output;
						cm.Parameters.Add(param_LastChanged);
						// TODO: Define any additional output parameters
						cm.ExecuteNonQuery();
						// Save all values being returned from the Procedure
						_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
					}
				}
				MarkOld();
				// use the open connection to update child objects
				if (_RoleAssignments != null) _RoleAssignments.Update(this);
				if (_RolePermissions != null) _RolePermissions.Update(this);
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.SQLUpdate", ex);
				_ErrorMessage = ex.Message;
				if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
			}
		}
		internal void Update()
		{
			if (!this.IsDirty) return;
			if (base.IsDirty)
			{
				SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
				if (IsNew)
					_LastChanged = Role.Add(cn, ref _RID, _Name, _Title, _DTS, _UsrID);
				else
					_LastChanged = Role.Update(cn, ref _RID, _Name, _Title, _DTS, _UsrID, ref _LastChanged);
				MarkOld();
			}
			if (_RoleAssignments != null) _RoleAssignments.Update(this);
			if (_RolePermissions != null) _RolePermissions.Update(this);
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		public static byte[] Update(SqlConnection cn, ref int rid, string name, string title, DateTime dts, string usrID, ref byte[] lastChanged)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.Update", 0);
			try
			{
				using (SqlCommand cm = cn.CreateCommand())
				{
					cm.CommandType = CommandType.StoredProcedure;
					cm.CommandText = "updateRole";
					// Input All Fields - Except Calculated Columns
					cm.Parameters.AddWithValue("@RID", rid);
					cm.Parameters.AddWithValue("@Name", name);
					cm.Parameters.AddWithValue("@Title", title);
					if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
					cm.Parameters.AddWithValue("@UsrID", usrID);
					cm.Parameters.AddWithValue("@LastChanged", lastChanged);
					// Output Calculated Columns
					SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp);
					param_LastChanged.Direction = ParameterDirection.Output;
					cm.Parameters.Add(param_LastChanged);
					// TODO: Define any additional output parameters
					cm.ExecuteNonQuery();
					// Save all values being returned from the Procedure
					return (byte[])cm.Parameters["@newLastChanged"].Value;
				}
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.Update", ex);
				throw new DbCslaException("Role.Update", ex);
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new PKCriteria(_RID));
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		private void DataPortal_Delete(PKCriteria criteria)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.DataPortal_Delete", GetHashCode());
			try
			{
				using (SqlConnection cn = Database.VEPROMS_SqlConnection)
				{
					using (SqlCommand cm = cn.CreateCommand())
					{
						cm.CommandType = CommandType.StoredProcedure;
						cm.CommandText = "deleteRole";
						cm.Parameters.AddWithValue("@RID", criteria.RID);
						cm.ExecuteNonQuery();
					}
				}
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.DataPortal_Delete", ex);
				_ErrorMessage = ex.Message;
				throw new DbCslaException("Role.DataPortal_Delete", ex);
			}
		}
		[Transactional(TransactionalTypes.TransactionScope)]
		public static void Remove(SqlConnection cn, int rid)
		{
			if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.Remove", 0);
			try
			{
				using (SqlCommand cm = cn.CreateCommand())
				{
					cm.CommandType = CommandType.StoredProcedure;
					cm.CommandText = "deleteRole";
					// Input PK Fields
					cm.Parameters.AddWithValue("@RID", rid);
					// TODO: Define any additional output parameters
					cm.ExecuteNonQuery();
				}
			}
			catch (Exception ex)
			{
				if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.Remove", ex);
				throw new DbCslaException("Role.Remove", ex);
			}
		}
		#endregion
		#region Exists
		public static bool Exists(int rid)
		{
			ExistsCommand result;
			try
			{
				result = DataPortal.Execute(new ExistsCommand(rid));
				return result.Exists;
			}
			catch (Exception ex)
			{
				throw new DbCslaException("Error on Role.Exists", ex);
			}
		}
		[Serializable()]
		private class ExistsCommand : CommandBase
		{
			private int _RID;
			private bool _exists;
			public bool Exists
			{
				get { return _exists; }
			}
			public ExistsCommand(int rid)
			{
				_RID = rid;
			}
			protected override void DataPortal_Execute()
			{
				if(_MyLog.IsDebugEnabled)_MyLog.DebugFormat("[{0}] Role.DataPortal_Execute", GetHashCode());
				try
				{
					using (SqlConnection cn = Database.VEPROMS_SqlConnection)
					{
						cn.Open();
						using (SqlCommand cm = cn.CreateCommand())
						{
							cm.CommandType = CommandType.StoredProcedure;
							cm.CommandText = "existsRole";
							cm.Parameters.AddWithValue("@RID", _RID);
							int count = (int)cm.ExecuteScalar();
							_exists = (count > 0);
						}
					}
				}
				catch (Exception ex)
				{
					if(_MyLog.IsErrorEnabled)_MyLog.Error("Role.DataPortal_Execute", ex);
					throw new DbCslaException("Role.DataPortal_Execute", ex);
				}
			}
		}
		#endregion
		// Standard Default Code
		#region extension
		RoleExtension _RoleExtension = new RoleExtension();
		[Serializable()]
		partial class RoleExtension : extensionBase
		{
		}
		[Serializable()]
		class extensionBase
		{
			// Default Values
			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 RoleConverter : ExpandableObjectConverter
	{
		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
		{
			if (destType == typeof(string) && value is Role)
			{
				// Return the ToString value
				return ((Role)value).ToString();
			}
			return base.ConvertTo(context, culture, value, destType);
		}
	}
	#endregion
} // Namespace
//// The following is a sample Extension File.  You can use it to create RoleExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
//  public partial class Role
//  {
//    partial class RoleExtension : extensionBase
//    {
//      // TODO: Override automatic defaults
//      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 */);
//      }
//    }
//  }
//}