// ======================================================================== // 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 { /// /// RODb Generated by MyGeneration using the CSLA Object Mapping template /// [Serializable()] [TypeConverter(typeof(RODbConverter))] public partial class RODb : BusinessBase, IDisposable, IVEHasBrokenRules { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Refresh private List _RefreshRODbs = new List(); private List _RefreshRODbROFsts = new List(); private List _RefreshRODbROImages = new List(); private List _RefreshRODbRoUsages = new List(); private void AddToRefreshList(List refreshRODbs, List refreshRODbROFsts, List refreshRODbROImages, List refreshRODbRoUsages) { if (IsDirty) refreshRODbs.Add(this); if (_RODbROFsts != null && _RODbROFsts.IsDirty) { foreach (RODbROFst tmp in _RODbROFsts) { if (tmp.IsDirty) refreshRODbROFsts.Add(tmp); } } if (_RODbROImages != null && _RODbROImages.IsDirty) { foreach (RODbROImage tmp in _RODbROImages) { if (tmp.IsDirty) refreshRODbROImages.Add(tmp); } } if (_RODbRoUsages != null && _RODbRoUsages.IsDirty) { foreach (RODbRoUsage tmp in _RODbRoUsages) { if (tmp.IsDirty) refreshRODbRoUsages.Add(tmp); } } } private void BuildRefreshList() { _RefreshRODbs = new List(); _RefreshRODbROFsts = new List(); _RefreshRODbROImages = new List(); _RefreshRODbRoUsages = new List(); AddToRefreshList(_RefreshRODbs, _RefreshRODbROFsts, _RefreshRODbROImages, _RefreshRODbRoUsages); } private void ProcessRefreshList() { foreach (RODb tmp in _RefreshRODbs) { RODbInfo.Refresh(tmp); } foreach (RODbROFst tmp in _RefreshRODbROFsts) { ROFstInfo.Refresh(tmp); } foreach (RODbROImage tmp in _RefreshRODbROImages) { ROImageInfo.Refresh(tmp); } foreach (RODbRoUsage tmp in _RefreshRODbRoUsages) { RoUsageInfo.Refresh(tmp); } } #endregion #region Collection private static List _CacheList = new List(); protected static void AddToCache(RODb rODb) { if (!_CacheList.Contains(rODb)) _CacheList.Add(rODb); // In AddToCache } protected static void RemoveFromCache(RODb rODb) { while (_CacheList.Contains(rODb)) _CacheList.Remove(rODb); // In RemoveFromCache } private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { List remove = new List(); foreach (RODb tmp in _CacheList) { if (!_CacheByPrimaryKey.ContainsKey(tmp.RODbID.ToString())) { _CacheByPrimaryKey[tmp.RODbID.ToString()] = new List(); // Add new list for PrimaryKey } _CacheByPrimaryKey[tmp.RODbID.ToString()].Add(tmp); // Add to Primary Key list remove.Add(tmp); } foreach (RODb tmp in remove) RemoveFromCache(tmp); } protected static RODb GetCachedByPrimaryKey(int rODbID) { ConvertListToDictionary(); string key = rODbID.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 _nextRODbID = -1; public static int NextRODbID { get { return _nextRODbID--; } } private int _RODbID; [System.ComponentModel.DataObjectField(true, true)] public int RODbID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _RODbID; } } private string _ROName = string.Empty; /// /// Hook for future - to allow the user to select multiple RO Databases assocaiated with on DocVersion /// public string ROName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _ROName; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_ROName != value) { _ROName = value; PropertyHasChanged(); } } } private string _FolderPath = string.Empty; /// /// Path to the RO database /// public string FolderPath { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _FolderPath; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_FolderPath != value) { _FolderPath = value; PropertyHasChanged(); } } } private string _DBConnectionString = string.Empty; /// /// Connection String - Default could just be the full path and name of the database /// public string DBConnectionString { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _DBConnectionString; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_DBConnectionString != value) { _DBConnectionString = 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 _UserID = string.Empty; public string UserID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _UserID; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (value == null) value = string.Empty; if (_UserID != value) { _UserID = value; PropertyHasChanged(); } } } private byte[] _LastChanged = new byte[8];//timestamp private int _RODbROFstCount = 0; /// /// Count of RODbROFsts for this RODb /// public int RODbROFstCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _RODbROFstCount; } } private RODbROFsts _RODbROFsts = null; /// /// Related Field /// [TypeConverter(typeof(RODbROFstsConverter))] public RODbROFsts RODbROFsts { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_RODbROFstCount > 0 && _RODbROFsts == null) _RODbROFsts = RODbROFsts.GetByRODbID(RODbID); else if (_RODbROFsts == null) _RODbROFsts = RODbROFsts.New(); return _RODbROFsts; } } private int _RODbROImageCount = 0; /// /// Count of RODbROImages for this RODb /// public int RODbROImageCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _RODbROImageCount; } } private RODbROImages _RODbROImages = null; /// /// Related Field /// [TypeConverter(typeof(RODbROImagesConverter))] public RODbROImages RODbROImages { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_RODbROImageCount > 0 && _RODbROImages == null) _RODbROImages = RODbROImages.GetByRODbID(RODbID); else if (_RODbROImages == null) _RODbROImages = RODbROImages.New(); return _RODbROImages; } } private int _RODbRoUsageCount = 0; /// /// Count of RODbRoUsages for this RODb /// public int RODbRoUsageCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _RODbRoUsageCount; } } private RODbRoUsages _RODbRoUsages = null; /// /// Related Field /// [TypeConverter(typeof(RODbRoUsagesConverter))] public RODbRoUsages RODbRoUsages { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_RODbRoUsageCount > 0 && _RODbRoUsages == null) _RODbRoUsages = RODbRoUsages.GetByRODbID(RODbID); else if (_RODbRoUsages == null) _RODbRoUsages = RODbRoUsages.New(); return _RODbRoUsages; } } public override bool IsDirty { get { return base.IsDirty || (_RODbROFsts == null ? false : _RODbROFsts.IsDirty) || (_RODbROImages == null ? false : _RODbROImages.IsDirty) || (_RODbRoUsages == null ? false : _RODbRoUsages.IsDirty); } } public override bool IsValid { get { return (IsNew && !IsDirty ? true : base.IsValid) && (_RODbROFsts == null ? true : _RODbROFsts.IsValid) && (_RODbROImages == null ? true : _RODbROImages.IsValid) && (_RODbRoUsages == null ? true : _RODbRoUsages.IsValid); } } // TODO: Replace base RODb.ToString function as necessary /// /// Overrides Base ToString /// /// A string representation of current RODb //public override string ToString() //{ // return base.ToString(); //} // TODO: Check RODb.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 RODb protected override object GetIdValue() { return _RODbID; } #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 (_RODbRoUsages != null && (hasBrokenRules = _RODbRoUsages.HasBrokenRules) != null) return hasBrokenRules; if (_RODbROFsts != null && (hasBrokenRules = _RODbROFsts.HasBrokenRules) != null) return hasBrokenRules; if (_RODbROImages != null && (hasBrokenRules = _RODbROImages.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, "ROName"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ROName", 255)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "FolderPath"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("FolderPath", 255)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "DBConnectionString"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("DBConnectionString", 1073741823)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "UserID"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); //ValidationRules.AddDependantProperty("x", "y"); _RODbExtension.AddValidationRules(ValidationRules); // TODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _RODbExtension.AddInstanceValidationRules(ValidationRules); // TODO: Add other validation rules } // Sample data comparison validation rule //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) //{ // if (_started > _ended) // { // e.Description = "Start date can't be after end date"; // return false; // } // else // return true; //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //TODO: Who can read/write which fields //AuthorizationRules.AllowRead(RODbID, ""); //AuthorizationRules.AllowRead(ROName, ""); //AuthorizationRules.AllowRead(FolderPath, ""); //AuthorizationRules.AllowRead(DBConnectionString, ""); //AuthorizationRules.AllowRead(DTS, ""); //AuthorizationRules.AllowRead(UserID, ""); //AuthorizationRules.AllowWrite(ROName, ""); //AuthorizationRules.AllowWrite(FolderPath, ""); //AuthorizationRules.AllowWrite(DBConnectionString, ""); //AuthorizationRules.AllowWrite(DTS, ""); //AuthorizationRules.AllowWrite(UserID, ""); _RODbExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //TODO: Who can read/write which fields _RODbExtension.AddInstanceAuthorizationRules(AuthorizationRules); } public static bool CanAddObject() { // TODO: Can Add Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } public static bool CanGetObject() { // TODO: CanGet Authorization return true; } public static bool CanDeleteObject() { // TODO: CanDelete Authorization //bool result = false; //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; //return result; return true; } /// /// determines if related records (Foreign Keys) will keep this Item from being deleted /// public bool CanDelete { get { // Check to make sure that there are not any related records int usedByCount = 0; usedByCount += _RODbROFstCount; usedByCount += _RODbROImageCount; usedByCount += _RODbRoUsageCount; return (usedByCount == 0); } } public static bool CanEditObject() { // TODO: CanEdit Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } #endregion #region Factory Methods public int CurrentEditLevel { get { return EditLevel; } } private static int _RODbUnique = 0; protected static int RODbUnique { get { return ++_RODbUnique; } } private int _MyRODbUnique = RODbUnique; public int MyRODbUnique { get { return _MyRODbUnique; } } protected RODb() {/* require use of factory methods */ AddToCache(this); } public void Dispose() { RemoveFromDictionaries(); } private void RemoveFromDictionaries() { RemoveFromCache(this); if (_CacheByPrimaryKey.ContainsKey(RODbID.ToString())) { List listRODb = _CacheByPrimaryKey[RODbID.ToString()]; // Get the list of items while (listRODb.Contains(this)) listRODb.Remove(this); // Remove the item from the list if (listRODb.Count == 0) //If there are no items left in the list _CacheByPrimaryKey.Remove(RODbID.ToString()); // remove the list } } public static RODb New() { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a RODb"); try { return DataPortal.Create(); } catch (Exception ex) { throw new DbCslaException("Error on RODb.New", ex); } } public static RODb New(string rOName, string folderPath, string dBConnectionString) { RODb tmp = RODb.New(); tmp.ROName = rOName; tmp.FolderPath = folderPath; tmp.DBConnectionString = dBConnectionString; return tmp; } public static RODb MakeRODb(string rOName, string folderPath, string dBConnectionString) { RODb tmp = RODb.New(rOName, folderPath, dBConnectionString); if (tmp.IsSavable) { RODb 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 RODb New(string rOName, string folderPath, string dBConnectionString, DateTime dts, string userID) { RODb tmp = RODb.New(); tmp.ROName = rOName; tmp.FolderPath = folderPath; tmp.DBConnectionString = dBConnectionString; tmp.DTS = dts; tmp.UserID = userID; return tmp; } public static RODb MakeRODb(string rOName, string folderPath, string dBConnectionString, DateTime dts, string userID) { RODb tmp = RODb.New(rOName, folderPath, dBConnectionString, dts, userID); if (tmp.IsSavable) { RODb 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 RODb Get(int rODbID) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a RODb"); try { RODb tmp = GetCachedByPrimaryKey(rODbID); if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(rODbID)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up RODb tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on RODb.Get", ex); } } public static RODb Get(SafeDataReader dr) { if (dr.Read()) return new RODb(dr); return null; } internal RODb(SafeDataReader dr) { ReadData(dr); } public static void Delete(int rODbID) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a RODb"); try { DataPortal.Delete(new PKCriteria(rODbID)); } catch (Exception ex) { throw new DbCslaException("Error on RODb.Delete", ex); } } public override RODb Save() { if (IsDeleted && !CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a RODb"); else if (IsNew && !CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a RODb"); else if (!CanEditObject()) throw new System.Security.SecurityException("User not authorized to update a RODb"); try { BuildRefreshList(); RODb rODb = base.Save(); RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(rODb);//Refresh the item in AllList ProcessRefreshList(); return rODb; } catch (Exception ex) { throw new DbCslaException("Error on CSLA Save", ex); } } #endregion #region Data Access Portal [Serializable()] protected class PKCriteria { private int _RODbID; public int RODbID { get { return _RODbID; } } public PKCriteria(int rODbID) { _RODbID = rODbID; } } // TODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { _RODbID = NextRODbID; // Database Defaults _DTS = _RODbExtension.DefaultDTS; _UserID = _RODbExtension.DefaultUserID; // TODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.ReadData", GetHashCode()); try { _RODbID = dr.GetInt32("RODbID"); _ROName = dr.GetString("ROName"); _FolderPath = dr.GetString("FolderPath"); _DBConnectionString = dr.GetString("DBConnectionString"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); _RODbROFstCount = dr.GetInt32("ROFstCount"); _RODbROImageCount = dr.GetInt32("ROImageCount"); _RODbRoUsageCount = dr.GetInt32("RoUsageCount"); MarkOld(); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("RODb.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.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 = "getRODb"; cm.Parameters.AddWithValue("@RODbID", criteria.RODbID); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); // load child objects dr.NextResult(); _RODbROFsts = RODbROFsts.Get(dr); // load child objects dr.NextResult(); _RODbROImages = RODbROImages.Get(dr); // load child objects dr.NextResult(); _RODbRoUsages = RODbRoUsages.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("RODb.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("RODb.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("RODb.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("RODb.DataPortal_Insert", ex); } finally { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.DataPortal_Insert", GetHashCode()); } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLInsert() { if (!this.IsDirty) return; try { SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addRODb"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ROName", _ROName); cm.Parameters.AddWithValue("@FolderPath", _FolderPath); cm.Parameters.AddWithValue("@DBConnectionString", _DBConnectionString); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); // Output Calculated Columns SqlParameter param_RODbID = new SqlParameter("@newRODbID", SqlDbType.Int); param_RODbID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_RODbID); 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 _RODbID = (int)cm.Parameters["@newRODbID"].Value; _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } MarkOld(); // update child objects if (_RODbRoUsages != null) _RODbRoUsages.Update(this); if (_RODbROFsts != null) _RODbROFsts.Update(this); if (_RODbROImages != null) _RODbROImages.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.SQLInsert", GetHashCode()); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("RODb.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, ref int rODbID, string rOName, string folderPath, string dBConnectionString, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addRODb"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ROName", rOName); cm.Parameters.AddWithValue("@FolderPath", folderPath); cm.Parameters.AddWithValue("@DBConnectionString", dBConnectionString); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns SqlParameter param_RODbID = new SqlParameter("@newRODbID", SqlDbType.Int); param_RODbID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_RODbID); 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 rODbID = (int)cm.Parameters["@newRODbID"].Value; return (byte[])cm.Parameters["@newLastChanged"].Value; } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.Add", ex); throw new DbCslaException("RODb.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}] RODb.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("RODb.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}] RODb.SQLUpdate", GetHashCode()); try { SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updateRODb"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@RODbID", _RODbID); cm.Parameters.AddWithValue("@ROName", _ROName); cm.Parameters.AddWithValue("@FolderPath", _FolderPath); cm.Parameters.AddWithValue("@DBConnectionString", _DBConnectionString); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@LastChanged", _LastChanged); // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } } MarkOld(); // use the open connection to update child objects if (_RODbRoUsages != null) _RODbRoUsages.Update(this); if (_RODbROFsts != null) _RODbROFsts.Update(this); if (_RODbROImages != null) _RODbROImages.Update(this); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.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 = RODb.Add(cn, ref _RODbID, _ROName, _FolderPath, _DBConnectionString, _DTS, _UserID); else _LastChanged = RODb.Update(cn, ref _RODbID, _ROName, _FolderPath, _DBConnectionString, _DTS, _UserID, ref _LastChanged); MarkOld(); } if (_RODbRoUsages != null) _RODbRoUsages.Update(this); if (_RODbROFsts != null) _RODbROFsts.Update(this); if (_RODbROImages != null) _RODbROImages.Update(this); } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, ref int rODbID, string rOName, string folderPath, string dBConnectionString, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updateRODb"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@RODbID", rODbID); cm.Parameters.AddWithValue("@ROName", rOName); cm.Parameters.AddWithValue("@FolderPath", folderPath); cm.Parameters.AddWithValue("@DBConnectionString", dBConnectionString); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); 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("RODb.Update", ex); throw new DbCslaException("RODb.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_RODbID)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.DataPortal_Delete", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deleteRODb"; cm.Parameters.AddWithValue("@RODbID", criteria.RODbID); cm.ExecuteNonQuery(); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("RODb.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int rODbID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deleteRODb"; // Input PK Fields cm.Parameters.AddWithValue("@RODbID", rODbID); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.Remove", ex); throw new DbCslaException("RODb.Remove", ex); } } #endregion #region Exists public static bool Exists(int rODbID) { ExistsCommand result; try { result = DataPortal.Execute(new ExistsCommand(rODbID)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on RODb.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private int _RODbID; private bool _exists; public bool Exists { get { return _exists; } } public ExistsCommand(int rODbID) { _RODbID = rODbID; } protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RODb.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "existsRODb"; cm.Parameters.AddWithValue("@RODbID", _RODbID); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("RODb.DataPortal_Execute", ex); throw new DbCslaException("RODb.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension RODbExtension _RODbExtension = new RODbExtension(); [Serializable()] partial class RODbExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual DateTime DefaultDTS { get { return DateTime.Now; } } public virtual string DefaultUserID { 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 RODbConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is RODb) { // Return the ToString value return ((RODb)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create RODbExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace VEPROMS.CSLA.Library //{ // public partial class RODb // { // partial class RODbExtension : extensionBase // { // // TODO: Override automatic defaults // public virtual DateTime DefaultDTS // { // get { return DateTime.Now; } // } // public virtual string DefaultUserID // { // 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 */); // } // } // } //}