// ======================================================================== // 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 { /// /// Format Generated by MyGeneration using the CSLA Object Mapping template /// [Serializable()] [TypeConverter(typeof(FormatConverter))] public partial class Format : BusinessBase, IDisposable, IVEHasBrokenRules { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Refresh private List _RefreshFormats = new List(); private List _RefreshFormatContents = new List(); private List _RefreshFormatDocVersions = new List(); private List _RefreshFormatFolders = new List(); private void AddToRefreshList(List refreshFormats, List refreshFormatContents, List refreshFormatDocVersions, List refreshFormatFolders) { if (IsDirty) refreshFormats.Add(this); if (_FormatContents != null && _FormatContents.IsDirty) { foreach (FormatContent tmp in _FormatContents) { if (tmp.IsDirty) refreshFormatContents.Add(tmp); } } if (_FormatDocVersions != null && _FormatDocVersions.IsDirty) { foreach (FormatDocVersion tmp in _FormatDocVersions) { if (tmp.IsDirty) refreshFormatDocVersions.Add(tmp); } } if (_FormatFolders != null && _FormatFolders.IsDirty) { foreach (FormatFolder tmp in _FormatFolders) { if (tmp.IsDirty) refreshFormatFolders.Add(tmp); } } if (_ChildFormats != null && _ChildFormats.IsDirty) { foreach (Format tmp in _ChildFormats) { tmp.AddToRefreshList(refreshFormats, refreshFormatContents, refreshFormatDocVersions, refreshFormatFolders); } } } private void BuildRefreshList() { _RefreshFormats = new List(); _RefreshFormatContents = new List(); _RefreshFormatDocVersions = new List(); _RefreshFormatFolders = new List(); AddToRefreshList(_RefreshFormats, _RefreshFormatContents, _RefreshFormatDocVersions, _RefreshFormatFolders); } private void ProcessRefreshList() { foreach (Format tmp in _RefreshFormats) { FormatInfo.Refresh(tmp); } foreach (FormatContent tmp in _RefreshFormatContents) { ContentInfo.Refresh(tmp); } foreach (FormatDocVersion tmp in _RefreshFormatDocVersions) { DocVersionInfo.Refresh(tmp); } foreach (FormatFolder tmp in _RefreshFormatFolders) { FolderInfo.Refresh(tmp); } } #endregion #region Collection private static List _CacheList = new List(); protected static void AddToCache(Format format) { if (!_CacheList.Contains(format)) _CacheList.Add(format); // In AddToCache } protected static void RemoveFromCache(Format format) { while (_CacheList.Contains(format)) _CacheList.Remove(format); // In RemoveFromCache } private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static Dictionary> _CacheByParentID_Name = new Dictionary>(); private static void ConvertListToDictionary() { List remove = new List(); foreach (Format tmp in _CacheList) { if (!_CacheByPrimaryKey.ContainsKey(tmp.FormatID.ToString())) { _CacheByPrimaryKey[tmp.FormatID.ToString()] = new List(); // Add new list for PrimaryKey _CacheByParentID_Name[tmp.ParentID.ToString() + "_" + tmp.Name.ToString()] = new List(); // Add new list for ParentID_Name } _CacheByPrimaryKey[tmp.FormatID.ToString()].Add(tmp); // Add to Primary Key list _CacheByParentID_Name[tmp.ParentID.ToString() + "_" + tmp.Name.ToString()].Add(tmp); // Unique Index remove.Add(tmp); } foreach (Format tmp in remove) RemoveFromCache(tmp); } protected static Format GetCachedByPrimaryKey(int formatID) { ConvertListToDictionary(); string key = formatID.ToString(); if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0]; return null; } protected static Format GetCachedByParentID_Name(int parentID, string name) { ConvertListToDictionary(); string key = parentID.ToString() + "_" + name.ToString(); if (_CacheByParentID_Name.ContainsKey(key)) return _CacheByParentID_Name[key][0]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } private static int _nextFormatID = -1; public static int NextFormatID { get { return _nextFormatID--; } } private int _FormatID; [System.ComponentModel.DataObjectField(true, true)] public int FormatID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatID", true); return _FormatID; } } private int _ParentID; public int ParentID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("ParentID", true); if (_MyParent != null) _ParentID = _MyParent.FormatID; return _ParentID; } } private Format _MyParent; public Format MyParent { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("MyParent", true); if (_MyParent == null && _ParentID != _FormatID) _MyParent = Format.Get(_ParentID); return _MyParent; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("MyParent", true); if (_MyParent != value) { _MyParent = value; PropertyHasChanged(); } } } private string _Name = string.Empty; public string Name { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("Name", true); return _Name; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("Name", true); if (value == null) value = string.Empty; if (_Name != value) { _Name = value; PropertyHasChanged(); } } } private string _Description = string.Empty; public string Description { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("Description", true); return _Description; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("Description", true); if (value == null) value = string.Empty; if (_Description != value) { _Description = value; PropertyHasChanged(); } } } private string _Data = string.Empty; public string Data { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("Data", true); return _Data; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("Data", true); if (value == null) value = string.Empty; if (_Data != value) { _Data = value; PropertyHasChanged(); } } } private string _GenMac = string.Empty; public string GenMac { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("GenMac", true); return _GenMac; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("GenMac", true); if (value == null) value = string.Empty; if (_GenMac != value) { _GenMac = value; PropertyHasChanged(); } } } private DateTime _DTS = new DateTime(); public DateTime DTS { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("DTS", true); return _DTS; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("DTS", true); if (_DTS != value) { _DTS = value; PropertyHasChanged(); } } } private string _UserID = string.Empty; public string UserID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("UserID", true); return _UserID; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty("UserID", true); if (value == null) value = string.Empty; if (_UserID != value) { _UserID = value; PropertyHasChanged(); } } } private byte[] _LastChanged = new byte[8];//timestamp private int _FormatContentCount = 0; /// /// Count of FormatContents for this Format /// public int FormatContentCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatContentCount", true); return _FormatContentCount; } } private FormatContents _FormatContents = null; /// /// Related Field /// [TypeConverter(typeof(FormatContentsConverter))] public FormatContents FormatContents { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatContents", true); if (_FormatContentCount > 0 && _FormatContents == null) _FormatContents = FormatContents.GetByFormatID(FormatID); else if (_FormatContents == null) _FormatContents = FormatContents.New(); return _FormatContents; } } private int _FormatDocVersionCount = 0; /// /// Count of FormatDocVersions for this Format /// public int FormatDocVersionCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatDocVersionCount", true); return _FormatDocVersionCount; } } private FormatDocVersions _FormatDocVersions = null; /// /// Related Field /// [TypeConverter(typeof(FormatDocVersionsConverter))] public FormatDocVersions FormatDocVersions { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatDocVersions", true); if (_FormatDocVersionCount > 0 && _FormatDocVersions == null) _FormatDocVersions = FormatDocVersions.GetByFormatID(FormatID); else if (_FormatDocVersions == null) _FormatDocVersions = FormatDocVersions.New(); return _FormatDocVersions; } } private int _FormatFolderCount = 0; /// /// Count of FormatFolders for this Format /// public int FormatFolderCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatFolderCount", true); return _FormatFolderCount; } } private FormatFolders _FormatFolders = null; /// /// Related Field /// [TypeConverter(typeof(FormatFoldersConverter))] public FormatFolders FormatFolders { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("FormatFolders", true); if (_FormatFolderCount > 0 && _FormatFolders == null) _FormatFolders = FormatFolders.GetByFormatID(FormatID); else if (_FormatFolders == null) _FormatFolders = FormatFolders.New(); return _FormatFolders; } } private int _ChildFormatCount = 0; /// /// Count of ChildFormats for this Format /// public int ChildFormatCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("ChildFormatCount", true); return _ChildFormatCount; } } private ChildFormats _ChildFormats = null; /// /// Related Field /// [TypeConverter(typeof(ChildFormatsConverter))] public ChildFormats ChildFormats { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty("ChildFormats", true); if (_ChildFormatCount > 0 && _ChildFormats == null) _ChildFormats = ChildFormats.GetByParentID(FormatID); else if (_ChildFormats == null) _ChildFormats = ChildFormats.New(); return _ChildFormats; } } public override bool IsDirty { get { return base.IsDirty || (_FormatContents == null ? false : _FormatContents.IsDirty) || (_FormatDocVersions == null ? false : _FormatDocVersions.IsDirty) || (_FormatFolders == null ? false : _FormatFolders.IsDirty) || (_ChildFormats == null ? false : _ChildFormats.IsDirty); } } public override bool IsValid { get { return (IsNew && !IsDirty ? true : base.IsValid) && (_FormatContents == null ? true : _FormatContents.IsValid) && (_FormatDocVersions == null ? true : _FormatDocVersions.IsValid) && (_FormatFolders == null ? true : _FormatFolders.IsValid) && (_ChildFormats == null ? true : _ChildFormats.IsValid); } } // TODO: Replace base Format.ToString function as necessary /// /// Overrides Base ToString /// /// A string representation of current Format //public override string ToString() //{ // return base.ToString(); //} // TODO: Check Format.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 Format protected override object GetIdValue() { return _FormatID; } #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 (_FormatFolders != null && (hasBrokenRules = _FormatFolders.HasBrokenRules) != null) return hasBrokenRules; if (_FormatContents != null && (hasBrokenRules = _FormatContents.HasBrokenRules) != null) return hasBrokenRules; if (_FormatDocVersions != null && (hasBrokenRules = _FormatDocVersions.HasBrokenRules) != null) return hasBrokenRules; if (_ChildFormats != null && (hasBrokenRules = _ChildFormats.HasBrokenRules) != null) return hasBrokenRules; return hasBrokenRules; } finally { _CheckingBrokenRules = false; } } } public BrokenRulesCollection BrokenRules { get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); } } protected override void AddBusinessRules() { ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "Name"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 20)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("Description", 250)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "Data"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("Data", 1073741823)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("GenMac", 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"); _FormatExtension.AddValidationRules(ValidationRules); // TODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _FormatExtension.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(FormatID, ""); //AuthorizationRules.AllowRead(ParentID, ""); //AuthorizationRules.AllowRead(Name, ""); //AuthorizationRules.AllowRead(Description, ""); //AuthorizationRules.AllowRead(Data, ""); //AuthorizationRules.AllowRead(GenMac, ""); //AuthorizationRules.AllowRead(DTS, ""); //AuthorizationRules.AllowRead(UserID, ""); //AuthorizationRules.AllowWrite(ParentID, ""); //AuthorizationRules.AllowWrite(Name, ""); //AuthorizationRules.AllowWrite(Description, ""); //AuthorizationRules.AllowWrite(Data, ""); //AuthorizationRules.AllowWrite(GenMac, ""); //AuthorizationRules.AllowWrite(DTS, ""); //AuthorizationRules.AllowWrite(UserID, ""); _FormatExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //TODO: Who can read/write which fields _FormatExtension.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 += _FormatContentCount; usedByCount += _FormatDocVersionCount; usedByCount += _FormatFolderCount; usedByCount += _ChildFormatCount; 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 _FormatUnique = 0; protected static int FormatUnique { get { return ++_FormatUnique; } } private int _MyFormatUnique = FormatUnique; public int MyFormatUnique { get { return _MyFormatUnique; } } protected Format() {/* require use of factory methods */ AddToCache(this); } public void Dispose() { RemoveFromDictionaries(); } private void RemoveFromDictionaries() { RemoveFromCache(this); if (_CacheByPrimaryKey.ContainsKey(FormatID.ToString())) { List listFormat = _CacheByPrimaryKey[FormatID.ToString()]; // Get the list of items while (listFormat.Contains(this)) listFormat.Remove(this); // Remove the item from the list if (listFormat.Count == 0) //If there are no items left in the list _CacheByPrimaryKey.Remove(FormatID.ToString()); // remove the list } string myKey; myKey = null; foreach (string key in _CacheByParentID_Name.Keys) if (_CacheByParentID_Name[key].Contains(this)) myKey = key; if (myKey != null) { List listFormat = _CacheByParentID_Name[myKey]; // Get the list of items listFormat.Remove(this); // Remove the item from the list if (listFormat.Count == 0) //If there are no items left in the list _CacheByParentID_Name.Remove(myKey); // remove the list } } public static Format New() { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Format"); try { return DataPortal.Create(); } catch (Exception ex) { throw new DbCslaException("Error on Format.New", ex); } } public static Format New(Format myParent, string name, string data) { Format tmp = Format.New(); tmp.MyParent = myParent; tmp.Name = name; tmp.Data = data; return tmp; } public static Format New(Format myParent, string name, string description, string data, string genMac, DateTime dts, string userID) { Format tmp = Format.New(); tmp.MyParent = myParent; tmp.Name = name; tmp.Description = description; tmp.Data = data; tmp.GenMac = genMac; tmp.DTS = dts; tmp.UserID = userID; return tmp; } public static Format MakeFormat(Format myParent, string name, string description, string data, string genMac, DateTime dts, string userID) { Format tmp = Format.New(myParent, name, description, data, genMac, dts, userID); if (tmp.IsSavable) { Format 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 Format New(Format myParent, string name, string description, string data, string genMac) { Format tmp = Format.New(); tmp.MyParent = myParent; tmp.Name = name; tmp.Description = description; tmp.Data = data; tmp.GenMac = genMac; return tmp; } public static Format MakeFormat(Format myParent, string name, string description, string data, string genMac) { Format tmp = Format.New(myParent, name, description, data, genMac); if (tmp.IsSavable) { Format 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 Format Get(int formatID) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Format"); try { Format tmp = GetCachedByPrimaryKey(formatID); if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(formatID)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Format tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Format.Get", ex); } } public static Format GetByParentID_Name(int parentID, string name) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Format"); try { Format tmp = GetCachedByParentID_Name(parentID, name); if (tmp == null) { tmp = DataPortal.Fetch(new ParentID_NameCriteria(parentID, name)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Format tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Format.GetByParentID_Name", ex); } } public static Format Get(SafeDataReader dr, Format parent) { if (dr.Read()) return new Format(dr, parent); return null; } internal Format(SafeDataReader dr) { ReadData(dr); } private Format(SafeDataReader dr, Format parent) { ReadData(dr); MarkAsChild(); } internal Format(SafeDataReader dr, int parentID) { ReadData(dr); MarkAsChild(); } public static void Delete(int formatID) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Format"); try { DataPortal.Delete(new PKCriteria(formatID)); } catch (Exception ex) { throw new DbCslaException("Error on Format.Delete", ex); } } public override Format Save() { if (IsDeleted && !CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Format"); else if (IsNew && !CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Format"); else if (!CanEditObject()) throw new System.Security.SecurityException("User not authorized to update a Format"); try { BuildRefreshList(); Format format = base.Save(); RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(format);//Refresh the item in AllList ProcessRefreshList(); return format; } catch (Exception ex) { throw new DbCslaException("Error on CSLA Save", ex); } } #endregion #region Data Access Portal [Serializable()] protected class PKCriteria { private int _FormatID; public int FormatID { get { return _FormatID; } } public PKCriteria(int formatID) { _FormatID = formatID; } } [Serializable()] private class ParentID_NameCriteria { private int _ParentID; public int ParentID { get { return _ParentID; } } private string _Name; public string Name { get { return _Name; } } public ParentID_NameCriteria(int parentID, string name) { _ParentID = parentID; _Name = name; } } // TODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { _FormatID = NextFormatID; // Database Defaults _ParentID = _FormatExtension.DefaultParentID; _DTS = _FormatExtension.DefaultDTS; _UserID = _FormatExtension.DefaultUserID; // TODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.ReadData", GetHashCode()); try { _FormatID = dr.GetInt32("FormatID"); _ParentID = dr.GetInt32("ParentID"); _Name = dr.GetString("Name"); _Description = dr.GetString("Description"); _Data = dr.GetString("Data"); _GenMac = dr.GetString("GenMac"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); _FormatContentCount = dr.GetInt32("ContentCount"); _FormatDocVersionCount = dr.GetInt32("DocVersionCount"); _FormatFolderCount = dr.GetInt32("FolderCount"); _ChildFormatCount = dr.GetInt32("ChildCount"); MarkOld(); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Format.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.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 = "getFormat"; cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); // load child objects dr.NextResult(); _FormatContents = FormatContents.Get(dr); // load child objects dr.NextResult(); _FormatDocVersions = FormatDocVersions.Get(dr); // load child objects dr.NextResult(); _FormatFolders = FormatFolders.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("Format.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Format.DataPortal_Fetch", ex); } } private void DataPortal_Fetch(ParentID_NameCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.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 = "getFormatByParentID_Name"; cm.Parameters.AddWithValue("@ParentID", criteria.ParentID); cm.Parameters.AddWithValue("@Name", criteria.Name); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); } } // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Format.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("Format.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Format.DataPortal_Insert", ex); } finally { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.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 = "addFormat"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ParentID", ParentID); cm.Parameters.AddWithValue("@Name", _Name); cm.Parameters.AddWithValue("@Description", _Description); cm.Parameters.AddWithValue("@Data", _Data); cm.Parameters.AddWithValue("@GenMac", _GenMac); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); // Output Calculated Columns SqlParameter param_FormatID = new SqlParameter("@newFormatID", SqlDbType.Int); param_FormatID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_FormatID); 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 _FormatID = (int)cm.Parameters["@newFormatID"].Value; _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } MarkOld(); // update child objects if (_FormatFolders != null) _FormatFolders.Update(this); if (_FormatContents != null) _FormatContents.Update(this); if (_FormatDocVersions != null) _FormatDocVersions.Update(this); if (_ChildFormats != null) _ChildFormats.Update(this); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.SQLInsert", GetHashCode()); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Format.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, ref int formatID, Format myParent, string name, string description, string data, string genMac, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addFormat"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ParentID", myParent.FormatID); cm.Parameters.AddWithValue("@Name", name); cm.Parameters.AddWithValue("@Description", description); cm.Parameters.AddWithValue("@Data", data); cm.Parameters.AddWithValue("@GenMac", genMac); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns SqlParameter param_FormatID = new SqlParameter("@newFormatID", SqlDbType.Int); param_FormatID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_FormatID); 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 formatID = (int)cm.Parameters["@newFormatID"].Value; return (byte[])cm.Parameters["@newLastChanged"].Value; } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.Add", ex); throw new DbCslaException("Format.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}] Format.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("Format.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}] Format.SQLUpdate", GetHashCode()); try { SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updateFormat"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@FormatID", _FormatID); cm.Parameters.AddWithValue("@ParentID", ParentID); cm.Parameters.AddWithValue("@Name", _Name); cm.Parameters.AddWithValue("@Description", _Description); cm.Parameters.AddWithValue("@Data", _Data); cm.Parameters.AddWithValue("@GenMac", _GenMac); 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 (_FormatFolders != null) _FormatFolders.Update(this); if (_FormatContents != null) _FormatContents.Update(this); if (_FormatDocVersions != null) _FormatDocVersions.Update(this); if (_ChildFormats != null) _ChildFormats.Update(this); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.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 = Format.Add(cn, ref _FormatID, _MyParent, _Name, _Description, _Data, _GenMac, _DTS, _UserID); else _LastChanged = Format.Update(cn, ref _FormatID, _MyParent, _Name, _Description, _Data, _GenMac, _DTS, _UserID, ref _LastChanged); MarkOld(); } if (_FormatFolders != null) _FormatFolders.Update(this); if (_FormatContents != null) _FormatContents.Update(this); if (_FormatDocVersions != null) _FormatDocVersions.Update(this); if (_ChildFormats != null) _ChildFormats.Update(this); } internal void DeleteSelf(Format format) { // if we're not dirty then don't update the database if (!this.IsDirty) return; // if we're new then don't update the database if (this.IsNew) return; SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; Format.Remove(cn, _FormatID); MarkNew(); } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, ref int formatID, Format myParent, string name, string description, string data, string genMac, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updateFormat"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@FormatID", formatID); cm.Parameters.AddWithValue("@ParentID", myParent.FormatID); cm.Parameters.AddWithValue("@Name", name); cm.Parameters.AddWithValue("@Description", description); cm.Parameters.AddWithValue("@Data", data); cm.Parameters.AddWithValue("@GenMac", genMac); 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("Format.Update", ex); throw new DbCslaException("Format.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_FormatID)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.DataPortal_Delete", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deleteFormat"; cm.Parameters.AddWithValue("@FormatID", criteria.FormatID); cm.ExecuteNonQuery(); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Format.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int formatID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deleteFormat"; // Input PK Fields cm.Parameters.AddWithValue("@FormatID", formatID); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.Remove", ex); throw new DbCslaException("Format.Remove", ex); } } #endregion #region Exists public static bool Exists(int formatID) { ExistsCommand result; try { result = DataPortal.Execute(new ExistsCommand(formatID)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on Format.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private int _FormatID; private bool _exists; public bool Exists { get { return _exists; } } public ExistsCommand(int formatID) { _FormatID = formatID; } protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Format.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "existsFormat"; cm.Parameters.AddWithValue("@FormatID", _FormatID); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Format.DataPortal_Execute", ex); throw new DbCslaException("Format.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension FormatExtension _FormatExtension = new FormatExtension(); [Serializable()] partial class FormatExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual int DefaultParentID { get { return 1; } } 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 FormatConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is Format) { // Return the ToString value return ((Format)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create FormatExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace VEPROMS.CSLA.Library //{ // public partial class Format // { // partial class FormatExtension : extensionBase // { // // TODO: Override automatic defaults // public virtual int DefaultParentID // { // get { return 1; } // } // 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 */); // } // } // } //}