// ======================================================================== // 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 { /// /// Group Generated by MyGeneration using the CSLA Object Mapping template /// [Serializable()] [TypeConverter(typeof(GroupConverter))] public partial class Group : BusinessBase, IDisposable, IVEHasBrokenRules { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Refresh private List _RefreshGroups = new List(); private List _RefreshGroupAssignments = new List(); private List _RefreshGroupMemberships = new List(); private void AddToRefreshList(List refreshGroups, List refreshGroupAssignments, List refreshGroupMemberships) { if (IsDirty) refreshGroups.Add(this); if (_GroupAssignments != null && _GroupAssignments.IsDirty) { foreach (GroupAssignment tmp in _GroupAssignments) { if (tmp.IsDirty) refreshGroupAssignments.Add(tmp); } } if (_GroupMemberships != null && _GroupMemberships.IsDirty) { foreach (GroupMembership tmp in _GroupMemberships) { if (tmp.IsDirty) refreshGroupMemberships.Add(tmp); } } } private void ClearRefreshList() { _RefreshGroups = new List(); _RefreshGroupAssignments = new List(); _RefreshGroupMemberships = new List(); } private void BuildRefreshList() { ClearRefreshList(); AddToRefreshList(_RefreshGroups, _RefreshGroupAssignments, _RefreshGroupMemberships); } private void ProcessRefreshList() { foreach (Group tmp in _RefreshGroups) { GroupInfo.Refresh(tmp); } foreach (GroupAssignment tmp in _RefreshGroupAssignments) { AssignmentInfo.Refresh(tmp); } foreach (GroupMembership tmp in _RefreshGroupMemberships) { MembershipInfo.Refresh(tmp); } ClearRefreshList(); } #endregion #region Collection private static List _CacheList = new List(); protected static void AddToCache(Group group) { if (!_CacheList.Contains(group)) _CacheList.Add(group); // In AddToCache } protected static void RemoveFromCache(Group group) { while (_CacheList.Contains(group)) _CacheList.Remove(group); // In RemoveFromCache } private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static Dictionary> _CacheByGroupName = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Group(s) from temporary _CacheList to _CacheByPrimaryKey { Group tmp = _CacheList[0]; // Get the first Group string pKey = tmp.GID.ToString(); if (!_CacheByPrimaryKey.ContainsKey(pKey)) { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey _CacheByGroupName[tmp.GroupName.ToString()] = new List(); // Add new list for GroupName } _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheByGroupName[tmp.GroupName.ToString()].Add(tmp); // Unique Index _CacheList.RemoveAt(0); // Remove the first Group } } protected static Group GetCachedByPrimaryKey(int gid) { ConvertListToDictionary(); string key = gid.ToString(); if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0]; return null; } protected static Group GetCachedByGroupName(string groupName) { ConvertListToDictionary(); string key = groupName.ToString(); if (_CacheByGroupName.ContainsKey(key)) return _CacheByGroupName[key][0]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } private static int _nextGID = -1; public static int NextGID { get { return _nextGID--; } } private int _GID; [System.ComponentModel.DataObjectField(true, true)] public int GID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _GID; } } private string _GroupName = string.Empty; public string GroupName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _GroupName; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_GroupName != value) { _GroupName = value; PropertyHasChanged(); } } } private int? _GroupType; public int? GroupType { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _GroupType; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_GroupType != value) { _GroupType = value; 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 private int _GroupAssignmentCount = 0; /// /// Count of GroupAssignments for this Group /// public int GroupAssignmentCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _GroupAssignmentCount; } } private GroupAssignments _GroupAssignments = null; /// /// Related Field /// [TypeConverter(typeof(GroupAssignmentsConverter))] public GroupAssignments GroupAssignments { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_GroupAssignmentCount < 0 || (_GroupAssignmentCount > 0 && _GroupAssignments == null)) _GroupAssignments = GroupAssignments.GetByGID(GID); if (_GroupAssignmentCount < 0) _GroupAssignmentCount = _GroupAssignments == null ? 0 : _GroupAssignments.Count; if (_GroupAssignments == null) _GroupAssignments = GroupAssignments.New(); return _GroupAssignments; } } public void Reset_GroupAssignments() { _GroupAssignmentCount = -1; } private int _GroupMembershipCount = 0; /// /// Count of GroupMemberships for this Group /// public int GroupMembershipCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _GroupMembershipCount; } } private GroupMemberships _GroupMemberships = null; /// /// Related Field /// [TypeConverter(typeof(GroupMembershipsConverter))] public GroupMemberships GroupMemberships { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_GroupMembershipCount < 0 || (_GroupMembershipCount > 0 && _GroupMemberships == null)) _GroupMemberships = GroupMemberships.GetByGID(GID); if (_GroupMembershipCount < 0) _GroupMembershipCount = _GroupMemberships == null ? 0 : _GroupMemberships.Count; if (_GroupMemberships == null) _GroupMemberships = GroupMemberships.New(); return _GroupMemberships; } } public void Reset_GroupMemberships() { _GroupMembershipCount = -1; } 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 || (_GroupAssignments == null ? false : _GroupAssignments.IsDirtyList(list)) || (_GroupMemberships == null ? false : _GroupMemberships.IsDirtyList(list)); } public override bool IsValid { get { return IsValidList(new List()); } } public bool IsValidList(List list) { if (list.Contains(this)) return (IsNew && !IsDirty) ? true : base.IsValid; list.Add(this); return ((IsNew && !IsDirty) ? true : base.IsValid) && (_GroupAssignments == null ? true : _GroupAssignments.IsValidList(list)) && (_GroupMemberships == null ? true : _GroupMemberships.IsValidList(list)); } // CSLATODO: Replace base Group.ToString function as necessary /// /// Overrides Base ToString /// /// A string representation of current Group //public override string ToString() //{ // return base.ToString(); //} // CSLATODO: Check Group.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 Group protected override object GetIdValue() { return MyGroupUnique; // 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 (_GroupAssignments != null && (hasBrokenRules = _GroupAssignments.HasBrokenRules) != null) return hasBrokenRules; if (_GroupMemberships != null && (hasBrokenRules = _GroupMemberships.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, "GroupName"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("GroupName", 100)); 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"); _GroupExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _GroupExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: 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() { //CSLATODO: Who can read/write which fields //AuthorizationRules.AllowRead(GID, ""); //AuthorizationRules.AllowRead(GroupName, ""); //AuthorizationRules.AllowRead(GroupType, ""); //AuthorizationRules.AllowRead(Config, ""); //AuthorizationRules.AllowRead(DTS, ""); //AuthorizationRules.AllowRead(UsrID, ""); //AuthorizationRules.AllowWrite(GroupName, ""); //AuthorizationRules.AllowWrite(GroupType, ""); //AuthorizationRules.AllowWrite(Config, ""); //AuthorizationRules.AllowWrite(DTS, ""); //AuthorizationRules.AllowWrite(UsrID, ""); _GroupExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //CSLATODO: Who can read/write which fields _GroupExtension.AddInstanceAuthorizationRules(AuthorizationRules); } public static bool CanAddObject() { // CSLATODO: Can Add Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } public static bool CanGetObject() { // CSLATODO: CanGet Authorization return true; } public static bool CanDeleteObject() { // CSLATODO: 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 += _GroupAssignmentCount; usedByCount += _GroupMembershipCount; return (usedByCount == 0); } } public static bool CanEditObject() { // CSLATODO: CanEdit Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } #endregion #region Factory Methods public int CurrentEditLevel { get { return EditLevel; } } private static int _GroupUnique = 0; protected static int GroupUnique { get { return ++_GroupUnique; } } private int _MyGroupUnique = GroupUnique; public int MyGroupUnique // Absolutely Unique ID - Editable { get { return _MyGroupUnique; } } protected Group() {/* 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 { get { return ++_CountCreated; } } private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated { get { return _CountCreated; } } public static int CountNotDisposed { get { return _CountCreated - _CountDisposed; } } public static int CountNotFinalized { get { return _CountCreated - _CountFinalized; } } ~Group() { _CountFinalized++; } public void Dispose() { if (_Disposed) return; _CountDisposed++; _Disposed = true; RemoveFromDictionaries(); } private void RemoveFromDictionaries() { RemoveFromCache(this); if (_CacheByPrimaryKey.ContainsKey(GID.ToString())) { List listGroup = _CacheByPrimaryKey[GID.ToString()]; // Get the list of items while (listGroup.Contains(this)) listGroup.Remove(this); // Remove the item from the list if (listGroup.Count == 0) //If there are no items left in the list _CacheByPrimaryKey.Remove(GID.ToString()); // remove the list } string myKey; myKey = null; foreach (string key in _CacheByGroupName.Keys) if (_CacheByGroupName[key].Contains(this)) myKey = key; if (myKey != null) { List listGroup = _CacheByGroupName[myKey]; // Get the list of items listGroup.Remove(this); // Remove the item from the list if (listGroup.Count == 0) //If there are no items left in the list _CacheByGroupName.Remove(myKey); // remove the list } } public static Group New() { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Group"); try { return DataPortal.Create(); } catch (Exception ex) { throw new DbCslaException("Error on Group.New", ex); } } public static Group New(string groupName) { Group tmp = Group.New(); tmp.GroupName = groupName; return tmp; } public static Group New(string groupName, int? groupType, string config, DateTime dts, string usrID) { Group tmp = Group.New(); tmp.GroupName = groupName; tmp.GroupType = groupType; tmp.Config = config; tmp.DTS = dts; tmp.UsrID = usrID; return tmp; } public static Group MakeGroup(string groupName, int? groupType, string config, DateTime dts, string usrID) { Group tmp = Group.New(groupName, groupType, 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 Group New(string groupName, int? groupType, string config) { Group tmp = Group.New(); tmp.GroupName = groupName; tmp.GroupType = groupType; tmp.Config = config; return tmp; } public static Group MakeGroup(string groupName, int? groupType, string config) { Group tmp = Group.New(groupName, groupType, 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 Group Get(int gid) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Group"); try { Group tmp = GetCachedByPrimaryKey(gid); if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(gid)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Group tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Group.Get", ex); } } public static Group GetByGroupName(string groupName) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Group"); try { Group tmp = GetCachedByGroupName(groupName); if (tmp == null) { tmp = DataPortal.Fetch(new GroupNameCriteria(groupName)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Group tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Group.GetByGroupName", ex); } } public static Group Get(SafeDataReader dr) { if (dr.Read()) return new Group(dr); return null; } internal Group(SafeDataReader dr) { ReadData(dr); } public static void Delete(int gid) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Group"); try { DataPortal.Delete(new PKCriteria(gid)); } catch (Exception ex) { throw new DbCslaException("Error on Group.Delete", ex); } } public override Group Save() { if (IsDeleted && !CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Group"); else if (IsNew && !CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Group"); else if (!CanEditObject()) throw new System.Security.SecurityException("User not authorized to update a Group"); try { BuildRefreshList(); Group group = base.Save(); RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(group);//Refresh the item in AllList ProcessRefreshList(); return group; } catch (Exception ex) { throw new DbCslaException("Error on CSLA Save", ex); } } #endregion #region Data Access Portal [Serializable()] protected class PKCriteria { private int _GID; public int GID { get { return _GID; } } public PKCriteria(int gid) { _GID = gid; } } [Serializable()] private class GroupNameCriteria { private string _GroupName; public string GroupName { get { return _GroupName; } } public GroupNameCriteria(string groupName) { _GroupName = groupName; } } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { _GID = NextGID; // Database Defaults _DTS = _GroupExtension.DefaultDTS; _UsrID = _GroupExtension.DefaultUsrID; // CSLATODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.ReadData", GetHashCode()); try { _GID = dr.GetInt32("GID"); _GroupName = dr.GetString("GroupName"); _GroupType = (int?)dr.GetValue("GroupType"); _Config = dr.GetString("Config"); _DTS = dr.GetDateTime("DTS"); _UsrID = dr.GetString("UsrID"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); _GroupAssignmentCount = dr.GetInt32("AssignmentCount"); _GroupMembershipCount = dr.GetInt32("MembershipCount"); MarkOld(); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Group.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.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 = "getGroup"; cm.Parameters.AddWithValue("@GID", criteria.GID); cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); // load child objects dr.NextResult(); _GroupAssignments = GroupAssignments.Get(dr); // load child objects dr.NextResult(); _GroupMemberships = GroupMemberships.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("Group.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Group.DataPortal_Fetch", ex); } } private void DataPortal_Fetch(GroupNameCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.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 = "getGroupByGroupName"; cm.Parameters.AddWithValue("@GroupName", criteria.GroupName); 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("Group.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Group.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("Group.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Group.DataPortal_Insert", ex); } finally { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.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.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addGroup"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@GroupName", _GroupName); cm.Parameters.AddWithValue("@GroupType", _GroupType); 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_GID = new SqlParameter("@newGID", SqlDbType.Int); param_GID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_GID); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure _GID = (int)cm.Parameters["@newGID"].Value; _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } MarkOld(); // update child objects if (_GroupAssignments != null) _GroupAssignments.Update(this); if (_GroupMemberships != null) _GroupMemberships.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.SQLInsert", GetHashCode()); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Group.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, ref int gid, string groupName, int? groupType, string config, DateTime dts, string usrID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addGroup"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@GroupName", groupName); cm.Parameters.AddWithValue("@GroupType", groupType); 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_GID = new SqlParameter("@newGID", SqlDbType.Int); param_GID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_GID); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure gid = (int)cm.Parameters["@newGID"].Value; return (byte[])cm.Parameters["@newLastChanged"].Value; } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.Add", ex); throw new DbCslaException("Group.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}] Group.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("Group.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}] Group.SQLUpdate", GetHashCode()); try { SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updateGroup"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@GID", _GID); cm.Parameters.AddWithValue("@GroupName", _GroupName); cm.Parameters.AddWithValue("@GroupType", _GroupType); 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); // 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 if (_GroupAssignments != null) _GroupAssignments.Update(this); if (_GroupMemberships != null) _GroupMemberships.Update(this); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.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 = Group.Add(cn, ref _GID, _GroupName, _GroupType, _Config, _DTS, _UsrID); else _LastChanged = Group.Update(cn, ref _GID, _GroupName, _GroupType, _Config, _DTS, _UsrID, ref _LastChanged); MarkOld(); } if (_GroupAssignments != null) _GroupAssignments.Update(this); if (_GroupMemberships != null) _GroupMemberships.Update(this); } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, ref int gid, string groupName, int? groupType, string config, DateTime dts, string usrID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updateGroup"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@GID", gid); cm.Parameters.AddWithValue("@GroupName", groupName); cm.Parameters.AddWithValue("@GroupType", groupType); 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); // 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("Group.Update", ex); throw new DbCslaException("Group.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_GID)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.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 = "deleteGroup"; cm.Parameters.AddWithValue("@GID", criteria.GID); cm.ExecuteNonQuery(); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Group.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int gid) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "deleteGroup"; // Input PK Fields cm.Parameters.AddWithValue("@GID", gid); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.Remove", ex); throw new DbCslaException("Group.Remove", ex); } } #endregion #region Exists public static bool Exists(int gid) { ExistsCommand result; try { result = DataPortal.Execute(new ExistsCommand(gid)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on Group.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private int _GID; private bool _exists; public bool Exists { get { return _exists; } } public ExistsCommand(int gid) { _GID = gid; } protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Group.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "existsGroup"; cm.Parameters.AddWithValue("@GID", _GID); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Group.DataPortal_Execute", ex); throw new DbCslaException("Group.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension GroupExtension _GroupExtension = new GroupExtension(); [Serializable()] partial class GroupExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual DateTime DefaultDTS { get { return DateTime.Now; } } public virtual string DefaultUsrID { get { return 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 GroupConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is Group) { // Return the ToString value return ((Group)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create GroupExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace VEPROMS.CSLA.Library //{ // public partial class Group // { // partial class GroupExtension : extensionBase // { // // CSLATODO: 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 */); // } // } // } //}