// ======================================================================== // 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 { /// /// Permission Generated by MyGeneration using the CSLA Object Mapping template /// [Serializable()] [TypeConverter(typeof(PermissionConverter))] public partial class Permission : BusinessBase, IDisposable, IVEHasBrokenRules { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Refresh private List _RefreshPermissions = new List(); private void AddToRefreshList(List refreshPermissions) { if (IsDirty) refreshPermissions.Add(this); } private void BuildRefreshList() { _RefreshPermissions = new List(); AddToRefreshList(_RefreshPermissions); } private void ProcessRefreshList() { foreach (Permission tmp in _RefreshPermissions) { PermissionInfo.Refresh(tmp); if (tmp._MyRole != null) RoleInfo.Refresh(tmp._MyRole); } } #endregion #region Collection private static List _CacheList = new List(); protected static void AddToCache(Permission permission) { if (!_CacheList.Contains(permission)) _CacheList.Add(permission); // In AddToCache } protected static void RemoveFromCache(Permission permission) { while (_CacheList.Contains(permission)) _CacheList.Remove(permission); // In RemoveFromCache } private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { List remove = new List(); foreach (Permission tmp in _CacheList) { if (!_CacheByPrimaryKey.ContainsKey(tmp.PID.ToString())) { _CacheByPrimaryKey[tmp.PID.ToString()] = new List(); // Add new list for PrimaryKey } _CacheByPrimaryKey[tmp.PID.ToString()].Add(tmp); // Add to Primary Key list remove.Add(tmp); } foreach (Permission tmp in remove) RemoveFromCache(tmp); } protected static Permission GetCachedByPrimaryKey(int pid) { ConvertListToDictionary(); string key = pid.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; } } private static int _nextPID = -1; public static int NextPID { get { return _nextPID--; } } private int _PID; [System.ComponentModel.DataObjectField(true, true)] public int PID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _PID; } } private int _RID; public int RID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyRole != null) _RID = _MyRole.RID; return _RID; } } private Role _MyRole; public Role MyRole { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyRole == null && _RID != 0) _MyRole = Role.Get(_RID); return _MyRole; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_MyRole != value) { _MyRole = value; PropertyHasChanged(); } } } 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 { return _PermLevel; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { 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 { return _VersionType; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { 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 { return _PermValue; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { 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 { return _PermAD; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_PermAD != value) { _PermAD = value; PropertyHasChanged(); } } } private string _StartDate = string.Empty; public string StartDate { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _StartDate; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { 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 { return _EndDate; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { 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 { return _Config; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { 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 { return _DTS; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_DTS != value) { _DTS = value; PropertyHasChanged(); } } } private string _UsrID = string.Empty; public string UsrID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _UsrID; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_UsrID != value) { _UsrID = value; PropertyHasChanged(); } } } private byte[] _LastChanged = new byte[8];//timestamp public override bool IsDirty { get { return base.IsDirty || (_MyRole == null ? false : _MyRole.IsDirty); } } public override bool IsValid { get { return (IsNew && !IsDirty ? true : base.IsValid) && (_MyRole == null ? true : _MyRole.IsValid); } } // TODO: Replace base Permission.ToString function as necessary /// /// Overrides Base ToString /// /// A string representation of current Permission //public override string ToString() //{ // return base.ToString(); //} // TODO: Check Permission.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 Permission protected override object GetIdValue() { return _PID; } #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 (_MyRole != null && (hasBrokenRules = _MyRole.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(MyRoleRequired, "MyRole"); 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)); //ValidationRules.AddDependantProperty("x", "y"); _PermissionExtension.AddValidationRules(ValidationRules); // TODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _PermissionExtension.AddInstanceValidationRules(ValidationRules); // TODO: Add other validation rules } private static bool StartDateValid(Permission 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(Permission target, Csla.Validation.RuleArgs e) { try { DateTime tmp = SmartDate.StringToDate(target._EndDate); } catch { e.Description = "Invalid Date"; return false; } return true; } private static bool MyRoleRequired(Permission target, Csla.Validation.RuleArgs e) { if (target._RID == 0 && target._MyRole == null) // Required field missing { e.Description = "Required"; 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(RID, ""); //AuthorizationRules.AllowRead(PermLevel, ""); //AuthorizationRules.AllowRead(VersionType, ""); //AuthorizationRules.AllowRead(PermValue, ""); //AuthorizationRules.AllowRead(PermAD, ""); //AuthorizationRules.AllowRead(StartDate, ""); //AuthorizationRules.AllowRead(EndDate, ""); //AuthorizationRules.AllowRead(Config, ""); //AuthorizationRules.AllowRead(DTS, ""); //AuthorizationRules.AllowRead(UsrID, ""); //AuthorizationRules.AllowWrite(RID, ""); //AuthorizationRules.AllowWrite(PermLevel, ""); //AuthorizationRules.AllowWrite(VersionType, ""); //AuthorizationRules.AllowWrite(PermValue, ""); //AuthorizationRules.AllowWrite(PermAD, ""); //AuthorizationRules.AllowWrite(StartDate, ""); //AuthorizationRules.AllowWrite(EndDate, ""); //AuthorizationRules.AllowWrite(Config, ""); //AuthorizationRules.AllowWrite(DTS, ""); //AuthorizationRules.AllowWrite(UsrID, ""); _PermissionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //TODO: Who can read/write which fields _PermissionExtension.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; } 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; } } private static int _PermissionUnique = 0; protected static int PermissionUnique { get { return ++_PermissionUnique; } } private int _MyPermissionUnique = PermissionUnique; public int MyPermissionUnique { get { return _MyPermissionUnique; } } protected Permission() {/* require use of factory methods */ AddToCache(this); } public void Dispose() { RemoveFromDictionaries(); } private void RemoveFromDictionaries() { RemoveFromCache(this); if (_CacheByPrimaryKey.ContainsKey(PID.ToString())) { List listPermission = _CacheByPrimaryKey[PID.ToString()]; // Get the list of items while (listPermission.Contains(this)) listPermission.Remove(this); // Remove the item from the list if (listPermission.Count == 0) //If there are no items left in the list _CacheByPrimaryKey.Remove(PID.ToString()); // remove the list } } public static Permission New() { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Permission"); try { return DataPortal.Create(); } catch (Exception ex) { throw new DbCslaException("Error on Permission.New", ex); } } public static Permission New(Role myRole, int permLevel, int versionType, int permValue) { Permission tmp = Permission.New(); tmp.MyRole = myRole; tmp.PermLevel = permLevel; tmp.VersionType = versionType; tmp.PermValue = permValue; return tmp; } public static Permission New(Role myRole, int permLevel, int versionType, int permValue, int permAD, string startDate, string endDate, string config, DateTime dts, string usrID) { Permission tmp = Permission.New(); tmp.MyRole = myRole; tmp.PermLevel = permLevel; tmp.VersionType = versionType; tmp.PermValue = permValue; tmp.PermAD = permAD; tmp.StartDate = startDate; tmp.EndDate = endDate; tmp.Config = config; tmp.DTS = dts; tmp.UsrID = usrID; return tmp; } public static Permission MakePermission(Role myRole, int permLevel, int versionType, int permValue, int permAD, string startDate, string endDate, string config, DateTime dts, string usrID) { Permission tmp = Permission.New(myRole, permLevel, versionType, permValue, permAD, startDate, endDate, config, dts, usrID); if (tmp.IsSavable) { Permission tmp2 = tmp; tmp = tmp2.Save(); tmp2.Dispose(); } 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 Permission New(Role myRole, int permLevel, int versionType, int permValue, string endDate, string config) { Permission tmp = Permission.New(); tmp.MyRole = myRole; tmp.PermLevel = permLevel; tmp.VersionType = versionType; tmp.PermValue = permValue; tmp.EndDate = endDate; tmp.Config = config; return tmp; } public static Permission MakePermission(Role myRole, int permLevel, int versionType, int permValue, string endDate, string config) { Permission tmp = Permission.New(myRole, permLevel, versionType, permValue, endDate, config); if (tmp.IsSavable) { Permission tmp2 = tmp; tmp = tmp2.Save(); tmp2.Dispose(); } 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 Permission Get(int pid) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Permission"); try { Permission tmp = GetCachedByPrimaryKey(pid); if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(pid)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Permission tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Permission.Get", ex); } } public static Permission Get(SafeDataReader dr) { if (dr.Read()) return new Permission(dr); return null; } internal Permission(SafeDataReader dr) { ReadData(dr); } public static void Delete(int pid) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Permission"); try { DataPortal.Delete(new PKCriteria(pid)); } catch (Exception ex) { throw new DbCslaException("Error on Permission.Delete", ex); } } public override Permission Save() { if (IsDeleted && !CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Permission"); else if (IsNew && !CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Permission"); else if (!CanEditObject()) throw new System.Security.SecurityException("User not authorized to update a Permission"); try { BuildRefreshList(); Permission permission = base.Save(); RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(permission);//Refresh the item in AllList ProcessRefreshList(); return permission; } catch (Exception ex) { throw new DbCslaException("Error on CSLA Save", ex); } } #endregion #region Data Access Portal [Serializable()] protected class PKCriteria { private int _PID; public int PID { get { return _PID; } } public PKCriteria(int pid) { _PID = pid; } } // TODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { _PID = NextPID; // Database Defaults _PermAD = _PermissionExtension.DefaultPermAD; _StartDate = _PermissionExtension.DefaultStartDate; _DTS = _PermissionExtension.DefaultDTS; _UsrID = _PermissionExtension.DefaultUsrID; // TODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.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"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); MarkOld(); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Permission.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.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("Permission.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Permission.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("Permission.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Permission.DataPortal_Insert", ex); } finally { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.DataPortal_Insert", GetHashCode()); } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLInsert() { if (!this.IsDirty) return; try { if (_MyRole != null) _MyRole.Update(); SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addPermission"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@RID", RID); cm.Parameters.AddWithValue("@PermLevel", _PermLevel); cm.Parameters.AddWithValue("@VersionType", _VersionType); cm.Parameters.AddWithValue("@PermValue", _PermValue); cm.Parameters.AddWithValue("@PermAD", _PermAD); cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); cm.Parameters.AddWithValue("@Config", _Config); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UsrID", _UsrID); // Output Calculated Columns SqlParameter param_PID = new SqlParameter("@newPID", SqlDbType.Int); param_PID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_PID); 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 _PID = (int)cm.Parameters["@newPID"].Value; _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.SQLInsert", GetHashCode()); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Permission.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, ref int pid, Role myRole, int permLevel, int versionType, int permValue, int permAD, SmartDate startDate, SmartDate endDate, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addPermission"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@RID", myRole.RID); cm.Parameters.AddWithValue("@PermLevel", permLevel); cm.Parameters.AddWithValue("@VersionType", versionType); cm.Parameters.AddWithValue("@PermValue", permValue); cm.Parameters.AddWithValue("@PermAD", permAD); cm.Parameters.AddWithValue("@StartDate", startDate.DBValue); cm.Parameters.AddWithValue("@EndDate", endDate.DBValue); cm.Parameters.AddWithValue("@Config", config); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UsrID", usrID); // Output Calculated Columns SqlParameter param_PID = new SqlParameter("@newPID", SqlDbType.Int); param_PID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_PID); 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 pid = (int)cm.Parameters["@newPID"].Value; return (byte[])cm.Parameters["@newLastChanged"].Value; } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.Add", ex); throw new DbCslaException("Permission.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}] Permission.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("Permission.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}] Permission.SQLUpdate", GetHashCode()); try { if (_MyRole != null) _MyRole.Update(); SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updatePermission"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@PID", _PID); cm.Parameters.AddWithValue("@RID", RID); cm.Parameters.AddWithValue("@PermLevel", _PermLevel); cm.Parameters.AddWithValue("@VersionType", _VersionType); cm.Parameters.AddWithValue("@PermValue", _PermValue); cm.Parameters.AddWithValue("@PermAD", _PermAD); cm.Parameters.AddWithValue("@StartDate", new SmartDate(_StartDate).DBValue); cm.Parameters.AddWithValue("@EndDate", new SmartDate(_EndDate).DBValue); cm.Parameters.AddWithValue("@Config", _Config); 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 } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.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 = Permission.Add(cn, ref _PID, _MyRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); else _LastChanged = Permission.Update(cn, ref _PID, _MyRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); MarkOld(); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, ref int pid, Role myRole, int permLevel, int versionType, int permValue, int permAD, SmartDate startDate, SmartDate endDate, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updatePermission"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@PID", pid); cm.Parameters.AddWithValue("@RID", myRole.RID); cm.Parameters.AddWithValue("@PermLevel", permLevel); cm.Parameters.AddWithValue("@VersionType", versionType); cm.Parameters.AddWithValue("@PermValue", permValue); cm.Parameters.AddWithValue("@PermAD", permAD); cm.Parameters.AddWithValue("@StartDate", startDate.DBValue); cm.Parameters.AddWithValue("@EndDate", endDate.DBValue); cm.Parameters.AddWithValue("@Config", config); 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("Permission.Update", ex); throw new DbCslaException("Permission.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_PID)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.DataPortal_Delete", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deletePermission"; cm.Parameters.AddWithValue("@PID", criteria.PID); cm.ExecuteNonQuery(); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Permission.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int pid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deletePermission"; // Input PK Fields cm.Parameters.AddWithValue("@PID", pid); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.Remove", ex); throw new DbCslaException("Permission.Remove", ex); } } #endregion #region Exists public static bool Exists(int pid) { ExistsCommand result; try { result = DataPortal.Execute(new ExistsCommand(pid)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on Permission.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private int _PID; private bool _exists; public bool Exists { get { return _exists; } } public ExistsCommand(int pid) { _PID = pid; } protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Permission.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "existsPermission"; cm.Parameters.AddWithValue("@PID", _PID); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Permission.DataPortal_Execute", ex); throw new DbCslaException("Permission.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension PermissionExtension _PermissionExtension = new PermissionExtension(); [Serializable()] partial class PermissionExtension : 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 PermissionConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is Permission) { // Return the ToString value return ((Permission)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create PermissionExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace VEPROMS.CSLA.Library //{ // public partial class Permission // { // partial class PermissionExtension : 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 */); // } // } // } //}