// ========================================================================
// 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
{
    /// 
    ///	Folder Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(FolderConverter))]
    public partial class Folder : BusinessBase, IDisposable, IVEHasBrokenRules
    {
        #region Log4Net
        private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion
        #region Refresh
        private List _RefreshFolders = new List();
        private List _RefreshFolderAssignments = new List();
        private List _RefreshFolderDocVersions = new List();
        private void AddToRefreshList(List refreshFolders, List refreshFolderAssignments, List refreshFolderDocVersions)
        {
            if (IsDirty)
                refreshFolders.Add(this);
            if (_FolderAssignments != null && _FolderAssignments.IsDirty)
            {
                foreach (FolderAssignment tmp in _FolderAssignments)
                {
                    if (tmp.IsDirty) refreshFolderAssignments.Add(tmp);
                }
            }
            if (_FolderDocVersions != null && _FolderDocVersions.IsDirty)
            {
                foreach (FolderDocVersion tmp in _FolderDocVersions)
                {
                    if (tmp.IsDirty) refreshFolderDocVersions.Add(tmp);
                }
            }
            if (_ChildFolders != null && _ChildFolders.IsDirty)
            {
                foreach (Folder tmp in _ChildFolders)
                {
                    tmp.AddToRefreshList(refreshFolders, refreshFolderAssignments, refreshFolderDocVersions);
                }
            }
        }
        private void BuildRefreshList()
        {
            _RefreshFolders = new List();
            _RefreshFolderAssignments = new List();
            _RefreshFolderDocVersions = new List();
            AddToRefreshList(_RefreshFolders, _RefreshFolderAssignments, _RefreshFolderDocVersions);
        }
        private void ProcessRefreshList()
        {
            foreach (Folder tmp in _RefreshFolders)
            {
                FolderInfo.Refresh(tmp);
                if (tmp._MyConnection != null) ConnectionInfo.Refresh(tmp._MyConnection);
                if (tmp._MyFormat != null) FormatInfo.Refresh(tmp._MyFormat);
            }
            foreach (FolderAssignment tmp in _RefreshFolderAssignments)
            {
                AssignmentInfo.Refresh(tmp);
            }
            foreach (FolderDocVersion tmp in _RefreshFolderDocVersions)
            {
                DocVersionInfo.Refresh(tmp);
            }
        }
        #endregion
        #region Collection
        private static List _CacheList = new List();
        protected static void AddToCache(Folder folder)
        {
            if (!_CacheList.Contains(folder)) _CacheList.Add(folder); // In AddToCache
        }
        protected static void RemoveFromCache(Folder folder)
        {
            while (_CacheList.Contains(folder)) _CacheList.Remove(folder); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static Dictionary> _CacheByParentID_Name = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List remove = new List();
            foreach (Folder tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.FolderID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.FolderID.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.FolderID.ToString()].Add(tmp); // Add to Primary Key list
                _CacheByParentID_Name[tmp.ParentID.ToString() + "_" + tmp.Name.ToString()].Add(tmp); // Unique Index
                remove.Add(tmp);
            }
            foreach (Folder tmp in remove)
                RemoveFromCache(tmp);
        }
        protected static Folder GetCachedByPrimaryKey(int folderID)
        {
            ConvertListToDictionary();
            string key = folderID.ToString();
            if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0];
            return null;
        }
        protected static Folder 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 _nextFolderID = -1;
        public static int NextFolderID
        {
            get { return _nextFolderID--; }
        }
        private int _FolderID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int FolderID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _FolderID;
            }
        }
        private int _ParentID;
        public int ParentID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyParent != null) _ParentID = _MyParent.FolderID;
                return _ParentID;
            }
        }
        private Folder _MyParent;
        public Folder MyParent
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyParent == null && _ParentID != _FolderID) _MyParent = Folder.Get(_ParentID);
                return _MyParent;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (_MyParent != value)
                {
                    _MyParent = value;
                    PropertyHasChanged();
                }
            }
        }
        private int _DBID;
        public int DBID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyConnection != null) _DBID = _MyConnection.DBID;
                return _DBID;
            }
        }
        private Connection _MyConnection;
        public Connection MyConnection
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyConnection == null && _DBID != 0) _MyConnection = Connection.Get(_DBID);
                return _MyConnection;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (_MyConnection != value)
                {
                    _MyConnection = value;
                    PropertyHasChanged();
                }
            }
        }
        private string _Name = string.Empty;
        public string Name
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _Name;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (value == null) value = string.Empty;
                if (_Name != value)
                {
                    _Name = value;
                    PropertyHasChanged();
                }
            }
        }
        private string _Title = string.Empty;
        public string Title
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _Title;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (value == null) value = string.Empty;
                if (_Title != value)
                {
                    _Title = value;
                    PropertyHasChanged();
                }
            }
        }
        private string _ShortName = string.Empty;
        public string ShortName
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ShortName;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (value == null) value = string.Empty;
                if (_ShortName != value)
                {
                    _ShortName = value;
                    PropertyHasChanged();
                }
            }
        }
        private int? _FormatID;
        public int? FormatID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyFormat != null) _FormatID = _MyFormat.FormatID;
                return _FormatID;
            }
        }
        private Format _MyFormat;
        public Format MyFormat
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyFormat == null && _FormatID != null) _MyFormat = Format.Get((int)_FormatID);
                return _MyFormat;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if ((_MyFormat == null ? _FormatID : (int?)_MyFormat.FormatID) != (value == null ? null : (int?)value.FormatID))
                {
                    _MyFormat = value;
                    _FormatID = (value == null ? null : (int?)value.FormatID);
                    PropertyHasChanged();
                }
            }
        }
        private double? _ManualOrder;
        public double? ManualOrder
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ManualOrder;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (_ManualOrder != value)
                {
                    _ManualOrder = 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 _FolderAssignmentCount = 0;
        /// 
        /// Count of FolderAssignments for this Folder
        /// 
        public int FolderAssignmentCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _FolderAssignmentCount;
            }
        }
        private FolderAssignments _FolderAssignments = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(FolderAssignmentsConverter))]
        public FolderAssignments FolderAssignments
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_FolderAssignmentCount > 0 && _FolderAssignments == null)
                    _FolderAssignments = FolderAssignments.GetByFolderID(FolderID);
                else if (_FolderAssignments == null)
                    _FolderAssignments = FolderAssignments.New();
                return _FolderAssignments;
            }
        }
        private int _FolderDocVersionCount = 0;
        /// 
        /// Count of FolderDocVersions for this Folder
        /// 
        public int FolderDocVersionCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _FolderDocVersionCount;
            }
        }
        private FolderDocVersions _FolderDocVersions = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(FolderDocVersionsConverter))]
        public FolderDocVersions FolderDocVersions
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_FolderDocVersionCount > 0 && _FolderDocVersions == null)
                    _FolderDocVersions = FolderDocVersions.GetByFolderID(FolderID);
                else if (_FolderDocVersions == null)
                    _FolderDocVersions = FolderDocVersions.New();
                return _FolderDocVersions;
            }
        }
        private int _ChildFolderCount = 0;
        /// 
        /// Count of ChildFolders for this Folder
        /// 
        public int ChildFolderCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ChildFolderCount;
            }
        }
        private ChildFolders _ChildFolders = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(ChildFoldersConverter))]
        public ChildFolders ChildFolders
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ChildFolderCount > 0 && _ChildFolders == null)
                    _ChildFolders = ChildFolders.GetByParentID(FolderID);
                else if (_ChildFolders == null)
                    _ChildFolders = ChildFolders.New();
                return _ChildFolders;
            }
        }
        public override bool IsDirty
        {
            get { return base.IsDirty || (_FolderAssignments == null ? false : _FolderAssignments.IsDirty) || (_FolderDocVersions == null ? false : _FolderDocVersions.IsDirty) || (_ChildFolders == null ? false : _ChildFolders.IsDirty) || (_MyConnection == null ? false : _MyConnection.IsDirty) || (_MyFormat == null ? false : _MyFormat.IsDirty); }
        }
        public override bool IsValid
        {
            get { return (IsNew && !IsDirty ? true : base.IsValid) && (_FolderAssignments == null ? true : _FolderAssignments.IsValid) && (_FolderDocVersions == null ? true : _FolderDocVersions.IsValid) && (_ChildFolders == null ? true : _ChildFolders.IsValid) && (_MyConnection == null ? true : _MyConnection.IsValid) && (_MyFormat == null ? true : _MyFormat.IsValid); }
        }
        // TODO: Replace base Folder.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current Folder
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // TODO: Check Folder.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 Folder
        protected override object GetIdValue()
        {
            return _FolderID;
        }
        #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 (_FolderAssignments != null && (hasBrokenRules = _FolderAssignments.HasBrokenRules) != null) return hasBrokenRules;
                    if (_FolderDocVersions != null && (hasBrokenRules = _FolderDocVersions.HasBrokenRules) != null) return hasBrokenRules;
                    if (_ChildFolders != null && (hasBrokenRules = _ChildFolders.HasBrokenRules) != null) return hasBrokenRules;
                    if (_MyConnection != null && (hasBrokenRules = _MyConnection.HasBrokenRules) != null) return hasBrokenRules;
                    if (_MyFormat != null && (hasBrokenRules = _MyFormat.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(MyConnectionRequired, "MyConnection");
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringRequired, "Name");
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("Title", 510));
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringRequired, "ShortName");
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShortName", 20));
            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");
            _FolderExtension.AddValidationRules(ValidationRules);
            // TODO:  Add other validation rules
        }
        protected override void AddInstanceBusinessRules()
        {
            _FolderExtension.AddInstanceValidationRules(ValidationRules);
            // TODO:  Add other validation rules
        }
        private static bool MyConnectionRequired(Folder target, Csla.Validation.RuleArgs e)
        {
            if (target._DBID == 0 && target._MyConnection == null) // Required field missing
            {
                e.Description = "Required";
                return false;
            }
            return true;
        }
        // Sample data comparison validation rule
        //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
        //{
        //	if (_started > _ended)
        //	{
        //		e.Description = "Start date can't be after end date";
        //		return false;
        //	}
        //	else
        //		return true;
        //}
        #endregion
        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Who can read/write which fields
            //AuthorizationRules.AllowRead(FolderID, "");
            //AuthorizationRules.AllowRead(ParentID, "");
            //AuthorizationRules.AllowRead(DBID, "");
            //AuthorizationRules.AllowRead(Name, "");
            //AuthorizationRules.AllowRead(Title, "");
            //AuthorizationRules.AllowRead(ShortName, "");
            //AuthorizationRules.AllowRead(FormatID, "");
            //AuthorizationRules.AllowRead(ManualOrder, "");
            //AuthorizationRules.AllowRead(Config, "");
            //AuthorizationRules.AllowRead(DTS, "");
            //AuthorizationRules.AllowRead(UsrID, "");
            //AuthorizationRules.AllowWrite(ParentID, "");
            //AuthorizationRules.AllowWrite(DBID, "");
            //AuthorizationRules.AllowWrite(Name, "");
            //AuthorizationRules.AllowWrite(Title, "");
            //AuthorizationRules.AllowWrite(ShortName, "");
            //AuthorizationRules.AllowWrite(FormatID, "");
            //AuthorizationRules.AllowWrite(ManualOrder, "");
            //AuthorizationRules.AllowWrite(Config, "");
            //AuthorizationRules.AllowWrite(DTS, "");
            //AuthorizationRules.AllowWrite(UsrID, "");
            _FolderExtension.AddAuthorizationRules(AuthorizationRules);
        }
        protected override void AddInstanceAuthorizationRules()
        {
            //TODO: Who can read/write which fields
            _FolderExtension.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 += _FolderAssignmentCount;
                usedByCount += _FolderDocVersionCount;
                usedByCount += _ChildFolderCount;
                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 _FolderUnique = 0;
        protected static int FolderUnique
        { get { return ++_FolderUnique; } }
        private int _MyFolderUnique = FolderUnique;
        public int MyFolderUnique
        { get { return _MyFolderUnique; } }
        protected Folder()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromDictionaries();
        }
        private void RemoveFromDictionaries()
        {
            RemoveFromCache(this);
            if (_CacheByPrimaryKey.ContainsKey(FolderID.ToString()))
            {
                List listFolder = _CacheByPrimaryKey[FolderID.ToString()]; // Get the list of items
                while (listFolder.Contains(this)) listFolder.Remove(this); // Remove the item from the list
                if (listFolder.Count == 0) //If there are no items left in the list
                    _CacheByPrimaryKey.Remove(FolderID.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 listFolder = _CacheByParentID_Name[myKey]; // Get the list of items
                listFolder.Remove(this); // Remove the item from the list
                if (listFolder.Count == 0) //If there are no items left in the list
                    _CacheByParentID_Name.Remove(myKey); // remove the list
            }
        }
        public static Folder New()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Folder");
            try
            {
                return DataPortal.Create();
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Folder.New", ex);
            }
        }
        public static Folder New(Folder myParent, string name, string shortName)
        {
            Folder tmp = Folder.New();
            tmp.MyParent = myParent;
            tmp.Name = name;
            tmp.ShortName = shortName;
            return tmp;
        }
        public static Folder New(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config, DateTime dts, string usrID)
        {
            Folder tmp = Folder.New();
            tmp.MyParent = myParent;
            tmp.MyConnection = myConnection;
            tmp.Name = name;
            tmp.Title = title;
            tmp.ShortName = shortName;
            tmp.MyFormat = myFormat;
            tmp.ManualOrder = manualOrder;
            tmp.Config = config;
            tmp.DTS = dts;
            tmp.UsrID = usrID;
            return tmp;
        }
        public static Folder MakeFolder(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config, DateTime dts, string usrID)
        {
            Folder tmp = Folder.New(myParent, myConnection, name, title, shortName, myFormat, manualOrder, config, dts, usrID);
            if (tmp.IsSavable)
            {
                Folder 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 Folder New(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config)
        {
            Folder tmp = Folder.New();
            tmp.MyParent = myParent;
            tmp.MyConnection = myConnection;
            tmp.Name = name;
            tmp.Title = title;
            tmp.ShortName = shortName;
            tmp.MyFormat = myFormat;
            tmp.ManualOrder = manualOrder;
            tmp.Config = config;
            return tmp;
        }
        public static Folder MakeFolder(Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config)
        {
            Folder tmp = Folder.New(myParent, myConnection, name, title, shortName, myFormat, manualOrder, config);
            if (tmp.IsSavable)
            {
                Folder 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 Folder Get(int folderID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Folder");
            try
            {
                Folder tmp = GetCachedByPrimaryKey(folderID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(folderID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up Folder
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Folder.Get", ex);
            }
        }
        public static Folder GetByParentID_Name(int parentID, string name)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Folder");
            try
            {
                Folder 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 Folder
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Folder.GetByParentID_Name", ex);
            }
        }
        public static Folder Get(SafeDataReader dr, Folder parent)
        {
            if (dr.Read()) return new Folder(dr, parent);
            return null;
        }
        internal Folder(SafeDataReader dr)
        {
            ReadData(dr);
        }
        private Folder(SafeDataReader dr, Folder parent)
        {
            ReadData(dr);
            MarkAsChild();
        }
        internal Folder(SafeDataReader dr, int parentID)
        {
            ReadData(dr);
            MarkAsChild();
        }
        public static void Delete(int folderID)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Folder");
            try
            {
                DataPortal.Delete(new PKCriteria(folderID));
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Folder.Delete", ex);
            }
        }
        public override Folder Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Folder");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Folder");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a Folder");
            try
            {
                BuildRefreshList();
                Folder folder = base.Save();
                RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache
                AddToCache(folder);//Refresh the item in AllList
                ProcessRefreshList();
                return folder;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on CSLA Save", ex);
            }
        }
        #endregion
        #region Data Access Portal
        [Serializable()]
        protected class PKCriteria
        {
            private int _FolderID;
            public int FolderID
            { get { return _FolderID; } }
            public PKCriteria(int folderID)
            {
                _FolderID = folderID;
            }
        }
        [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()
        {
            _FolderID = NextFolderID;
            // Database Defaults
            _ParentID = _FolderExtension.DefaultParentID;
            _DBID = _FolderExtension.DefaultDBID;
            _DTS = _FolderExtension.DefaultDTS;
            _UsrID = _FolderExtension.DefaultUsrID;
            // TODO: Add any defaults that are necessary
            ValidationRules.CheckRules();
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.ReadData", GetHashCode());
            try
            {
                _FolderID = dr.GetInt32("FolderID");
                _ParentID = dr.GetInt32("ParentID");
                _DBID = dr.GetInt32("DBID");
                _Name = dr.GetString("Name");
                _Title = dr.GetString("Title");
                _ShortName = dr.GetString("ShortName");
                _FormatID = (int?)dr.GetValue("FormatID");
                _ManualOrder = (double?)dr.GetValue("ManualOrder");
                _Config = dr.GetString("Config");
                _DTS = dr.GetDateTime("DTS");
                _UsrID = dr.GetString("UsrID");
                dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8);
                _FolderAssignmentCount = dr.GetInt32("AssignmentCount");
                _FolderDocVersionCount = dr.GetInt32("DocVersionCount");
                _ChildFolderCount = dr.GetInt32("ChildCount");
                MarkOld();
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Folder.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.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 = "getFolder";
                        cm.Parameters.AddWithValue("@FolderID", criteria.FolderID);
                        using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                        {
                            if (!dr.Read())
                            {
                                _ErrorMessage = "No Record Found";
                                return;
                            }
                            ReadData(dr);
                            // load child objects
                            dr.NextResult();
                            _FolderAssignments = FolderAssignments.Get(dr);
                            // load child objects
                            dr.NextResult();
                            _FolderDocVersions = FolderDocVersions.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("Folder.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Folder.DataPortal_Fetch", ex);
            }
        }
        private void DataPortal_Fetch(ParentID_NameCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.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 = "getFolderByParentID_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("Folder.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Folder.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("Folder.DataPortal_Insert", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Folder.DataPortal_Insert", ex);
            }
            finally
            {
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.DataPortal_Insert", GetHashCode());
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        internal void SQLInsert()
        {
            if (!this.IsDirty) return;
            try
            {
                if (_MyConnection != null) _MyConnection.Update();
                if (_MyFormat != null) _MyFormat.Update();
                SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "addFolder";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@ParentID", ParentID);
                    cm.Parameters.AddWithValue("@DBID", DBID);
                    cm.Parameters.AddWithValue("@Name", _Name);
                    cm.Parameters.AddWithValue("@Title", _Title);
                    cm.Parameters.AddWithValue("@ShortName", _ShortName);
                    cm.Parameters.AddWithValue("@FormatID", FormatID);
                    cm.Parameters.AddWithValue("@ManualOrder", _ManualOrder);
                    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_FolderID = new SqlParameter("@newFolderID", SqlDbType.Int);
                    param_FolderID.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_FolderID);
                    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
                    _FolderID = (int)cm.Parameters["@newFolderID"].Value;
                    _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
                }
                MarkOld();
                // update child objects
                if (_FolderAssignments != null) _FolderAssignments.Update(this);
                if (_FolderDocVersions != null) _FolderDocVersions.Update(this);
                if (_ChildFolders != null) _ChildFolders.Update(this);
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.SQLInsert", GetHashCode());
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.SQLInsert", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Folder.SQLInsert", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static byte[] Add(SqlConnection cn, ref int folderID, Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config, DateTime dts, string usrID)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Add", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "addFolder";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@ParentID", myParent.FolderID);
                    cm.Parameters.AddWithValue("@DBID", myConnection.DBID);
                    cm.Parameters.AddWithValue("@Name", name);
                    cm.Parameters.AddWithValue("@Title", title);
                    cm.Parameters.AddWithValue("@ShortName", shortName);
                    if (myFormat != null) cm.Parameters.AddWithValue("@FormatID", myFormat.FormatID);
                    cm.Parameters.AddWithValue("@ManualOrder", manualOrder);
                    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_FolderID = new SqlParameter("@newFolderID", SqlDbType.Int);
                    param_FolderID.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_FolderID);
                    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
                    folderID = (int)cm.Parameters["@newFolderID"].Value;
                    return (byte[])cm.Parameters["@newLastChanged"].Value;
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.Add", ex);
                throw new DbCslaException("Folder.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}] Folder.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("Folder.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}] Folder.SQLUpdate", GetHashCode());
            try
            {
                if (_MyConnection != null) _MyConnection.Update();
                if (_MyFormat != null) _MyFormat.Update();
                SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
                if (base.IsDirty)
                {
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "updateFolder";
                        // All Fields including Calculated Fields
                        cm.Parameters.AddWithValue("@FolderID", _FolderID);
                        cm.Parameters.AddWithValue("@ParentID", ParentID);
                        cm.Parameters.AddWithValue("@DBID", DBID);
                        cm.Parameters.AddWithValue("@Name", _Name);
                        cm.Parameters.AddWithValue("@Title", _Title);
                        cm.Parameters.AddWithValue("@ShortName", _ShortName);
                        cm.Parameters.AddWithValue("@FormatID", FormatID);
                        cm.Parameters.AddWithValue("@ManualOrder", _ManualOrder);
                        cm.Parameters.AddWithValue("@Config", _Config);
                        if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
                        cm.Parameters.AddWithValue("@UsrID", _UsrID);
                        cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
                        // Output Calculated Columns
                        SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp);
                        param_LastChanged.Direction = ParameterDirection.Output;
                        cm.Parameters.Add(param_LastChanged);
                        // TODO: Define any additional output parameters
                        cm.ExecuteNonQuery();
                        // Save all values being returned from the Procedure
                        _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
                    }
                }
                MarkOld();
                // use the open connection to update child objects
                if (_FolderAssignments != null) _FolderAssignments.Update(this);
                if (_FolderDocVersions != null) _FolderDocVersions.Update(this);
                if (_ChildFolders != null) _ChildFolders.Update(this);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.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 = Folder.Add(cn, ref _FolderID, _MyParent, _MyConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID);
                else
                    _LastChanged = Folder.Update(cn, ref _FolderID, _MyParent, _MyConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged);
                MarkOld();
            }
            if (_FolderAssignments != null) _FolderAssignments.Update(this);
            if (_FolderDocVersions != null) _FolderDocVersions.Update(this);
            if (_ChildFolders != null) _ChildFolders.Update(this);
        }
        internal void DeleteSelf(Folder folder)
        {
            // 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"];
            Folder.Remove(cn, _FolderID);
            MarkNew();
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static byte[] Update(SqlConnection cn, ref int folderID, Folder myParent, Connection myConnection, string name, string title, string shortName, Format myFormat, double? manualOrder, string config, DateTime dts, string usrID, ref byte[] lastChanged)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Update", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "updateFolder";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@FolderID", folderID);
                    cm.Parameters.AddWithValue("@ParentID", myParent.FolderID);
                    cm.Parameters.AddWithValue("@DBID", myConnection.DBID);
                    cm.Parameters.AddWithValue("@Name", name);
                    cm.Parameters.AddWithValue("@Title", title);
                    cm.Parameters.AddWithValue("@ShortName", shortName);
                    if (myFormat != null) cm.Parameters.AddWithValue("@FormatID", myFormat.FormatID);
                    cm.Parameters.AddWithValue("@ManualOrder", manualOrder);
                    cm.Parameters.AddWithValue("@Config", config);
                    if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
                    cm.Parameters.AddWithValue("@UsrID", usrID);
                    cm.Parameters.AddWithValue("@LastChanged", lastChanged);
                    // Output Calculated Columns
                    SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp);
                    param_LastChanged.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_LastChanged);
                    // TODO: Define any additional output parameters
                    cm.ExecuteNonQuery();
                    // Save all values being returned from the Procedure
                    return (byte[])cm.Parameters["@newLastChanged"].Value;
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.Update", ex);
                throw new DbCslaException("Folder.Update", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new PKCriteria(_FolderID));
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.DataPortal_Delete", GetHashCode());
            try
            {
                using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                {
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "deleteFolder";
                        cm.Parameters.AddWithValue("@FolderID", criteria.FolderID);
                        cm.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.DataPortal_Delete", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Folder.DataPortal_Delete", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static void Remove(SqlConnection cn, int folderID)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.Remove", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "deleteFolder";
                    // Input PK Fields
                    cm.Parameters.AddWithValue("@FolderID", folderID);
                    // TODO: Define any additional output parameters
                    cm.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.Remove", ex);
                throw new DbCslaException("Folder.Remove", ex);
            }
        }
        #endregion
        #region Exists
        public static bool Exists(int folderID)
        {
            ExistsCommand result;
            try
            {
                result = DataPortal.Execute(new ExistsCommand(folderID));
                return result.Exists;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Folder.Exists", ex);
            }
        }
        [Serializable()]
        private class ExistsCommand : CommandBase
        {
            private int _FolderID;
            private bool _exists;
            public bool Exists
            {
                get { return _exists; }
            }
            public ExistsCommand(int folderID)
            {
                _FolderID = folderID;
            }
            protected override void DataPortal_Execute()
            {
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Folder.DataPortal_Execute", GetHashCode());
                try
                {
                    using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                    {
                        cn.Open();
                        using (SqlCommand cm = cn.CreateCommand())
                        {
                            cm.CommandType = CommandType.StoredProcedure;
                            cm.CommandText = "existsFolder";
                            cm.Parameters.AddWithValue("@FolderID", _FolderID);
                            int count = (int)cm.ExecuteScalar();
                            _exists = (count > 0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (_MyLog.IsErrorEnabled) _MyLog.Error("Folder.DataPortal_Execute", ex);
                    throw new DbCslaException("Folder.DataPortal_Execute", ex);
                }
            }
        }
        #endregion
        // Standard Default Code
        #region extension
        FolderExtension _FolderExtension = new FolderExtension();
        [Serializable()]
        partial class FolderExtension : extensionBase
        {
        }
        [Serializable()]
        class extensionBase
        {
            // Default Values
            public virtual int DefaultParentID
            {
                get { return 1; }
            }
            public virtual int DefaultDBID
            {
                get { return 1; }
            }
            public virtual DateTime DefaultDTS
            {
                get { return DateTime.Now; }
            }
            public virtual string DefaultUsrID
            {
                get { return Environment.UserName.ToUpper(); }
            }
            // Authorization Rules
            public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
            {
                // Needs to be overriden to add new authorization rules
            }
            // Instance Authorization Rules
            public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
            {
                // Needs to be overriden to add new authorization rules
            }
            // Validation Rules
            public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
            {
                // Needs to be overriden to add new validation rules
            }
            // InstanceValidation Rules
            public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
            {
                // Needs to be overriden to add new validation rules
            }
        }
        #endregion
    } // Class
    #region Converter
    internal class FolderConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is Folder)
            {
                // Return the ToString value
                return ((Folder)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace
//// The following is a sample Extension File.  You can use it to create FolderExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
//  public partial class Folder
//  {
//    partial class FolderExtension : extensionBase
//    {
//      // TODO: Override automatic defaults
//      public virtual int DefaultParentID
//      {
//        get { return 1; }
//      }
//      public virtual int DefaultDBID
//      {
//        get { return 1; }
//      }
//      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 */);
//      }
//    }
//  }
//}