// ======================================================================== // 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.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 ClearRefreshList() => _RefreshPermissions = new List(); private void BuildRefreshList() { ClearRefreshList(); AddToRefreshList(_RefreshPermissions); } private void ProcessRefreshList() { foreach (Permission tmp in _RefreshPermissions) { PermissionInfo.Refresh(tmp); if (tmp._MyRole != null) RoleInfo.Refresh(tmp._MyRole); } ClearRefreshList(); } #endregion #region Collection [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] 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 } [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")] private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Permission(s) from temporary _CacheList to _CacheByPrimaryKey { Permission tmp = _CacheList[0]; // Get the first Permission string pKey = tmp.PID.ToString(); if (!_CacheByPrimaryKey.ContainsKey(pKey)) { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey } _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheList.RemoveAt(0); // Remove the first Permission } } 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 => _ErrorMessage; private static int _nextPID = -1; public static int NextPID => _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; _RID = value.RID;// Update underlying data field 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(); // CSLATODO: 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(); // CSLATODO: 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 { if (base.IsDirty) return true; return IsDirtyList(new List()); } } public bool IsDirtyList(List list) { if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); return base.IsDirty || (_MyRole != null && _MyRole.IsDirtyList(list)); } public override bool IsValid => IsValidList(new List()); public bool IsValidList(List list) { if (list.Contains(this)) return (IsNew && !IsDirty) || base.IsValid; list.Add(this); return ((IsNew && !IsDirty) || base.IsValid) && (_MyRole == null || _MyRole.IsValidList(list)); } // CSLATODO: 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() => MyPermissionUnique; // Absolutely Unique ID #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 (Equals(hasBrokenRules)) return BrokenRulesCollection; return hasBrokenRules?.BrokenRules; } } 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); // CSLATODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _PermissionExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: 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; } #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //CSLATODO: Who can read/write which fields _PermissionExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //CSLATODO: Who can read/write which fields _PermissionExtension.AddInstanceAuthorizationRules(AuthorizationRules); } #endregion #region Factory Methods public int CurrentEditLevel => EditLevel; private static int _PermissionUnique = 0; protected static int PermissionUnique => ++_PermissionUnique; private readonly int _MyPermissionUnique = PermissionUnique; // Absolutely Unique ID - Editable public int MyPermissionUnique => _MyPermissionUnique; protected Permission() {/* require use of factory methods */ AddToCache(this); } private bool _Disposed = false; private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; private static int IncrementCountCreated => ++_CountCreated; private readonly int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated; public static int CountNotDisposed => _CountCreated - _CountDisposed; public static int CountNotFinalized => _CountCreated - _CountFinalized; ~Permission() { _CountFinalized++; } public void Dispose() { if (_Disposed) return; _CountDisposed++; _Disposed = true; 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() { 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) 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 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) 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 Permission Get(int pid) { 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) { try { DataPortal.Delete(new PKCriteria(pid)); } catch (Exception ex) { throw new DbCslaException("Error on Permission.Delete", ex); } } public override Permission Save() { 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 readonly int _PID; public int PID => _PID; public PKCriteria(int pid) => _PID = pid; } // CSLATODO: 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; // CSLATODO: 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); cm.CommandTimeout = Database.DefaultTimeout; 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 (!IsDirty) return; try { _MyRole?.Update(); using (SqlConnection cn = Database.VEPROMS_SqlConnection) { if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; 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) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_PID); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: 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.CommandTimeout = Database.SQLTimeout; 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) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_PID); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: 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 { _MyRole?.Update(); using (SqlConnection cn = Database.VEPROMS_SqlConnection) { if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; 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) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: 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 (!IsDirty) return; if (base.IsDirty) { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); 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, _RID, _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, int rid, 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.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updatePermission"; // Input All Fields - Except Calculated Columns 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", startDate); cm.Parameters.AddWithValue("@EndDate", endDate); 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) { Direction = ParameterDirection.Output }; cm.Parameters.Add(param_LastChanged); // CSLATODO: 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.CommandTimeout = Database.SQLTimeout; 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.CommandTimeout = Database.SQLTimeout; cm.CommandText = "deletePermission"; // Input PK Fields cm.Parameters.AddWithValue("@PID", pid); // CSLATODO: 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 readonly int _PID; private bool _exists; public bool Exists => _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) { if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; 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 readonly PermissionExtension _PermissionExtension = new PermissionExtension(); [Serializable()] partial class PermissionExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual int DefaultPermAD => 0; public virtual string DefaultStartDate => DateTime.Now.ToShortDateString(); public virtual DateTime DefaultDTS => DateTime.Now; public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID; // 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 perm) { // Return the ToString value return perm.ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace