// ========================================================================
// 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
{
    /// 
    ///	Item Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(ItemConverter))]
    public partial class Item : BusinessBase- , IDisposable, IVEHasBrokenRules
    {
        #region Log4Net
        private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion
        #region Refresh
        private List-  _RefreshItems = new List- ();
        private List _RefreshItemAnnotations = new List();
        private List _RefreshItemDocVersions = new List();
        private List _RefreshItemParts = new List();
        private List _RefreshItemTransitions_RangeID = new List();
        private List _RefreshItemTransitions_ToID = new List();
        private void AddToRefreshList(List-  refreshItems, List refreshItemAnnotations, List refreshItemDocVersions, List refreshItemParts, List refreshItemTransitions_RangeID, List refreshItemTransitions_ToID)
        {
            if (IsDirty)
                refreshItems.Add(this);
            if (_ItemAnnotations != null && _ItemAnnotations.IsDirty)
            {
                foreach (ItemAnnotation tmp in _ItemAnnotations)
                {
                    if (tmp.IsDirty) refreshItemAnnotations.Add(tmp);
                }
            }
            if (_ItemDocVersions != null && _ItemDocVersions.IsDirty)
            {
                foreach (ItemDocVersion tmp in _ItemDocVersions)
                {
                    if (tmp.IsDirty) refreshItemDocVersions.Add(tmp);
                }
            }
            if (_NextItems != null && _NextItems.IsDirty)
            {
                foreach (Item tmp in _NextItems)
                {
                    tmp.AddToRefreshList(refreshItems, refreshItemAnnotations, refreshItemDocVersions, refreshItemParts, refreshItemTransitions_RangeID, refreshItemTransitions_ToID);
                }
            }
            if (_ItemParts != null && _ItemParts.IsDirty)
            {
                foreach (ItemPart tmp in _ItemParts)
                {
                    if (tmp.IsDirty) refreshItemParts.Add(tmp);
                }
            }
            if (_ItemTransitions_RangeID != null && _ItemTransitions_RangeID.IsDirty)
            {
                foreach (ItemTransition_RangeID tmp in _ItemTransitions_RangeID)
                {
                    if (tmp.IsDirty) refreshItemTransitions_RangeID.Add(tmp);
                }
            }
            if (_ItemTransitions_ToID != null && _ItemTransitions_ToID.IsDirty)
            {
                foreach (ItemTransition_ToID tmp in _ItemTransitions_ToID)
                {
                    if (tmp.IsDirty) refreshItemTransitions_ToID.Add(tmp);
                }
            }
        }
        private void BuildRefreshList()
        {
            _RefreshItems = new List- ();
            _RefreshItemAnnotations = new List();
            _RefreshItemDocVersions = new List();
            _RefreshItemParts = new List();
            _RefreshItemTransitions_RangeID = new List();
            _RefreshItemTransitions_ToID = new List();
            AddToRefreshList(_RefreshItems, _RefreshItemAnnotations, _RefreshItemDocVersions, _RefreshItemParts, _RefreshItemTransitions_RangeID, _RefreshItemTransitions_ToID);
        }
        private void ProcessRefreshList()
        {
            foreach (Item tmp in _RefreshItems)
            {
                ItemInfo.Refresh(tmp);
                if (tmp._MyContent != null) ContentInfo.Refresh(tmp._MyContent);
            }
            foreach (ItemAnnotation tmp in _RefreshItemAnnotations)
            {
                AnnotationInfo.Refresh(tmp);
            }
            foreach (ItemDocVersion tmp in _RefreshItemDocVersions)
            {
                DocVersionInfo.Refresh(tmp);
            }
            foreach (ItemPart tmp in _RefreshItemParts)
            {
                PartInfo.Refresh(tmp);
            }
            foreach (ItemTransition_RangeID tmp in _RefreshItemTransitions_RangeID)
            {
                TransitionInfo.Refresh(tmp);
            }
            foreach (ItemTransition_ToID tmp in _RefreshItemTransitions_ToID)
            {
                TransitionInfo.Refresh(tmp);
            }
        }
        #endregion
        #region Collection
        private static List-  _CacheList = new List- ();
        protected static void AddToCache(Item item)
        {
            if (!_CacheList.Contains(item)) _CacheList.Add(item); // In AddToCache
        }
        protected static void RemoveFromCache(Item item)
        {
            while (_CacheList.Contains(item)) _CacheList.Remove(item); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List-  remove = new List- ();
            foreach (Item tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.ItemID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.ItemID.ToString()] = new List- (); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[tmp.ItemID.ToString()].Add(tmp); // Add to Primary Key list
                remove.Add(tmp);
            }
            foreach (Item tmp in remove)
                RemoveFromCache(tmp);
        }
        protected static Item GetCachedByPrimaryKey(int itemID)
        {
            ConvertListToDictionary();
            string key = itemID.ToString();
            if (_CacheByPrimaryKey.ContainsKey(key)) return _CacheByPrimaryKey[key][0];
            return null;
        }
        #endregion
        #region Business Methods
        private string _ErrorMessage = string.Empty;
        public string ErrorMessage
        {
            get { return _ErrorMessage; }
        }
        private static int _nextItemID = -1;
        public static int NextItemID
        {
            get { return _nextItemID--; }
        }
        private int _ItemID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int ItemID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemID;
            }
        }
        private int? _PreviousID;
        public int? PreviousID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyPrevious != null) _PreviousID = _MyPrevious.ItemID;
                return _PreviousID;
            }
        }
        private Item _MyPrevious;
        public Item MyPrevious
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyPrevious == null && _PreviousID != null) _MyPrevious = Item.Get((int)_PreviousID);
                return _MyPrevious;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if ((_MyPrevious == null ? _PreviousID : (int?)_MyPrevious.ItemID) != (value == null ? null : (int?)value.ItemID))
                {
                    _MyPrevious = value;
                    _PreviousID = (value == null ? null : (int?)value.ItemID);
                    PropertyHasChanged();
                }
            }
        }
        private int _ContentID;
        public int ContentID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyContent != null) _ContentID = _MyContent.ContentID;
                return _ContentID;
            }
        }
        private Content _MyContent;
        public Content MyContent
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_MyContent == null && _ContentID != 0) _MyContent = Content.Get(_ContentID);
                return _MyContent;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (_MyContent != value)
                {
                    _MyContent = value;
                    PropertyHasChanged();
                }
            }
        }
        private DateTime _DTS = new DateTime();
        public DateTime DTS
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DTS;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (_DTS != value)
                {
                    _DTS = value;
                    PropertyHasChanged();
                }
            }
        }
        private string _UserID = string.Empty;
        public string UserID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _UserID;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (value == null) value = string.Empty;
                if (_UserID != value)
                {
                    _UserID = value;
                    PropertyHasChanged();
                }
            }
        }
        private byte[] _LastChanged = new byte[8];//timestamp
        private int _ItemAnnotationCount = 0;
        /// 
        /// Count of ItemAnnotations for this Item
        /// 
        public int ItemAnnotationCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemAnnotationCount;
            }
        }
        private ItemAnnotations _ItemAnnotations = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(ItemAnnotationsConverter))]
        public ItemAnnotations ItemAnnotations
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemAnnotationCount > 0 && _ItemAnnotations == null)
                    _ItemAnnotations = ItemAnnotations.GetByItemID(ItemID);
                else if (_ItemAnnotations == null)
                    _ItemAnnotations = ItemAnnotations.New();
                return _ItemAnnotations;
            }
        }
        private int _ItemDocVersionCount = 0;
        /// 
        /// Count of ItemDocVersions for this Item
        /// 
        public int ItemDocVersionCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemDocVersionCount;
            }
        }
        private ItemDocVersions _ItemDocVersions = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(ItemDocVersionsConverter))]
        public ItemDocVersions ItemDocVersions
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemDocVersionCount > 0 && _ItemDocVersions == null)
                    _ItemDocVersions = ItemDocVersions.GetByItemID(ItemID);
                else if (_ItemDocVersions == null)
                    _ItemDocVersions = ItemDocVersions.New();
                return _ItemDocVersions;
            }
        }
        private int _NextItemCount = 0;
        /// 
        /// Count of NextItems for this Item
        /// 
        public int NextItemCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _NextItemCount;
            }
        }
        private NextItems _NextItems = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(NextItemsConverter))]
        public NextItems NextItems
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_NextItemCount > 0 && _NextItems == null)
                    _NextItems = NextItems.GetByPreviousID(ItemID);
                else if (_NextItems == null)
                    _NextItems = NextItems.New();
                return _NextItems;
            }
        }
        private int _ItemPartCount = 0;
        /// 
        /// Count of ItemParts for this Item
        /// 
        public int ItemPartCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemPartCount;
            }
        }
        private ItemParts _ItemParts = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(ItemPartsConverter))]
        public ItemParts ItemParts
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemPartCount > 0 && _ItemParts == null)
                    _ItemParts = ItemParts.GetByItemID(ItemID);
                else if (_ItemParts == null)
                    _ItemParts = ItemParts.New();
                return _ItemParts;
            }
        }
        private int _ItemTransition_RangeIDCount = 0;
        /// 
        /// Count of ItemTransitions for this Item
        /// 
        public int ItemTransition_RangeIDCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemTransition_RangeIDCount;
            }
        }
        private ItemTransitions_RangeID _ItemTransitions_RangeID = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(ItemTransitions_RangeIDConverter))]
        public ItemTransitions_RangeID ItemTransitions_RangeID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemTransition_RangeIDCount > 0 && _ItemTransitions_RangeID == null)
                    _ItemTransitions_RangeID = ItemTransitions_RangeID.GetByRangeID(ItemID);
                else if (_ItemTransitions_RangeID == null)
                    _ItemTransitions_RangeID = ItemTransitions_RangeID.New();
                return _ItemTransitions_RangeID;
            }
        }
        private int _ItemTransition_ToIDCount = 0;
        /// 
        /// Count of ItemTransitions for this Item
        /// 
        public int ItemTransition_ToIDCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _ItemTransition_ToIDCount;
            }
        }
        private ItemTransitions_ToID _ItemTransitions_ToID = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(ItemTransitions_ToIDConverter))]
        public ItemTransitions_ToID ItemTransitions_ToID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_ItemTransition_ToIDCount > 0 && _ItemTransitions_ToID == null)
                    _ItemTransitions_ToID = ItemTransitions_ToID.GetByToID(ItemID);
                else if (_ItemTransitions_ToID == null)
                    _ItemTransitions_ToID = ItemTransitions_ToID.New();
                return _ItemTransitions_ToID;
            }
        }
        public override bool IsDirty
        {
            get { return base.IsDirty || (_ItemAnnotations == null ? false : _ItemAnnotations.IsDirty) || (_ItemDocVersions == null ? false : _ItemDocVersions.IsDirty) || (_NextItems == null ? false : _NextItems.IsDirty) || (_ItemParts == null ? false : _ItemParts.IsDirty) || (_ItemTransitions_RangeID == null ? false : _ItemTransitions_RangeID.IsDirty) || (_ItemTransitions_ToID == null ? false : _ItemTransitions_ToID.IsDirty) || (_MyContent == null ? false : _MyContent.IsDirty); }
        }
        public override bool IsValid
        {
            get { return (IsNew && !IsDirty ? true : base.IsValid) && (_ItemAnnotations == null ? true : _ItemAnnotations.IsValid) && (_ItemDocVersions == null ? true : _ItemDocVersions.IsValid) && (_NextItems == null ? true : _NextItems.IsValid) && (_ItemParts == null ? true : _ItemParts.IsValid) && (_ItemTransitions_RangeID == null ? true : _ItemTransitions_RangeID.IsValid) && (_ItemTransitions_ToID == null ? true : _ItemTransitions_ToID.IsValid) && (_MyContent == null ? true : _MyContent.IsValid); }
        }
        // TODO: Replace base Item.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current Item
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // TODO: Check Item.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 Item
        protected override object GetIdValue()
        {
            return _ItemID;
        }
        #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 (_ItemAnnotations != null && (hasBrokenRules = _ItemAnnotations.HasBrokenRules) != null) return hasBrokenRules;
                    if (_ItemDocVersions != null && (hasBrokenRules = _ItemDocVersions.HasBrokenRules) != null) return hasBrokenRules;
                    if (_NextItems != null && (hasBrokenRules = _NextItems.HasBrokenRules) != null) return hasBrokenRules;
                    if (_ItemParts != null && (hasBrokenRules = _ItemParts.HasBrokenRules) != null) return hasBrokenRules;
                    if (_ItemTransitions_RangeID != null && (hasBrokenRules = _ItemTransitions_RangeID.HasBrokenRules) != null) return hasBrokenRules;
                    if (_ItemTransitions_ToID != null && (hasBrokenRules = _ItemTransitions_ToID.HasBrokenRules) != null) return hasBrokenRules;
                    if (_MyContent != null && (hasBrokenRules = _MyContent.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- (MyContentRequired, "MyContent");
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringRequired, "UserID");
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100));
            //ValidationRules.AddDependantProperty("x", "y");
            _ItemExtension.AddValidationRules(ValidationRules);
            // TODO:  Add other validation rules
        }
        protected override void AddInstanceBusinessRules()
        {
            _ItemExtension.AddInstanceValidationRules(ValidationRules);
            // TODO:  Add other validation rules
        }
        private static bool MyContentRequired(Item target, Csla.Validation.RuleArgs e)
        {
            if (target._ContentID == 0 && target._MyContent == 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(ItemID, "");
            //AuthorizationRules.AllowRead(PreviousID, "");
            //AuthorizationRules.AllowRead(ContentID, "");
            //AuthorizationRules.AllowRead(DTS, "");
            //AuthorizationRules.AllowRead(UserID, "");
            //AuthorizationRules.AllowWrite(PreviousID, "");
            //AuthorizationRules.AllowWrite(ContentID, "");
            //AuthorizationRules.AllowWrite(DTS, "");
            //AuthorizationRules.AllowWrite(UserID, "");
            _ItemExtension.AddAuthorizationRules(AuthorizationRules);
        }
        protected override void AddInstanceAuthorizationRules()
        {
            //TODO: Who can read/write which fields
            _ItemExtension.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 += _ItemAnnotationCount;
                usedByCount += _ItemDocVersionCount;
                usedByCount += _ItemPartCount;
                usedByCount += _ItemTransition_RangeIDCount;
                usedByCount += _ItemTransition_ToIDCount;
                usedByCount += _NextItemCount;
                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 _ItemUnique = 0;
        protected static int ItemUnique
        { get { return ++_ItemUnique; } }
        private int _MyItemUnique = ItemUnique;
        public int MyItemUnique
        { get { return _MyItemUnique; } }
        protected Item()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromDictionaries();
        }
        private void RemoveFromDictionaries()
        {
            RemoveFromCache(this);
            if (_CacheByPrimaryKey.ContainsKey(ItemID.ToString()))
            {
                List-  listItem = _CacheByPrimaryKey[ItemID.ToString()]; // Get the list of items
                while (listItem.Contains(this)) listItem.Remove(this); // Remove the item from the list
                if (listItem.Count == 0) //If there are no items left in the list
                    _CacheByPrimaryKey.Remove(ItemID.ToString()); // remove the list
            }
        }
        public static Item New()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Item");
            try
            {
                return DataPortal.Create- ();
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Item.New", ex);
            }
        }
        public static Item New(Content myContent)
        {
            Item tmp = Item.New();
            tmp.MyContent = myContent;
            return tmp;
        }
        public static Item New(Item myPrevious, Content myContent, DateTime dts, string userID)
        {
            Item tmp = Item.New();
            tmp.MyPrevious = myPrevious;
            tmp.MyContent = myContent;
            tmp.DTS = dts;
            tmp.UserID = userID;
            return tmp;
        }
        public static Item MakeItem(Item myPrevious, Content myContent, DateTime dts, string userID)
        {
            Item tmp = Item.New(myPrevious, myContent, dts, userID);
            if (tmp.IsSavable)
            {
                Item 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 Item New(Item myPrevious, Content myContent)
        {
            Item tmp = Item.New();
            tmp.MyPrevious = myPrevious;
            tmp.MyContent = myContent;
            return tmp;
        }
        public static Item MakeItem(Item myPrevious, Content myContent)
        {
            Item tmp = Item.New(myPrevious, myContent);
            if (tmp.IsSavable)
            {
                Item 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 Item Get(int itemID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Item");
            try
            {
                Item tmp = GetCachedByPrimaryKey(itemID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch- (new PKCriteria(itemID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up Item
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Item.Get", ex);
            }
        }
        public static Item Get(SafeDataReader dr, Item previous)
        {
            if (dr.Read()) return new Item(dr, previous);
            return null;
        }
        internal Item(SafeDataReader dr)
        {
            ReadData(dr);
        }
        private Item(SafeDataReader dr, Item previous)
        {
            ReadData(dr);
            MarkAsChild();
        }
        internal Item(SafeDataReader dr, int parentID)
        {
            ReadData(dr);
            MarkAsChild();
        }
        public static void Delete(int itemID)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Item");
            try
            {
                DataPortal.Delete(new PKCriteria(itemID));
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Item.Delete", ex);
            }
        }
        public override Item Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Item");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Item");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a Item");
            try
            {
                BuildRefreshList();
                Item item = base.Save();
                RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache
                AddToCache(item);//Refresh the item in AllList
                ProcessRefreshList();
                return item;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on CSLA Save", ex);
            }
        }
        #endregion
        #region Data Access Portal
        [Serializable()]
        protected class PKCriteria
        {
            private int _ItemID;
            public int ItemID
            { get { return _ItemID; } }
            public PKCriteria(int itemID)
            {
                _ItemID = itemID;
            }
        }
        // TODO: If Create needs to access DB - It should not be marked RunLocal
        [RunLocal()]
        private new void DataPortal_Create()
        {
            _ItemID = NextItemID;
            // Database Defaults
            _DTS = _ItemExtension.DefaultDTS;
            _UserID = _ItemExtension.DefaultUserID;
            // TODO: Add any defaults that are necessary
            ValidationRules.CheckRules();
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.ReadData", GetHashCode());
            try
            {
                _ItemID = dr.GetInt32("ItemID");
                _PreviousID = (int?)dr.GetValue("PreviousID");
                _ContentID = dr.GetInt32("ContentID");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
                dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8);
                _ItemAnnotationCount = dr.GetInt32("AnnotationCount");
                _ItemDocVersionCount = dr.GetInt32("DocVersionCount");
                _NextItemCount = dr.GetInt32("NextCount");
                _ItemPartCount = dr.GetInt32("PartCount");
                _ItemTransition_RangeIDCount = dr.GetInt32("Transition_RangeIDCount");
                _ItemTransition_ToIDCount = dr.GetInt32("Transition_ToIDCount");
                MarkOld();
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Item.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.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 = "getItem";
                        cm.Parameters.AddWithValue("@ItemID", criteria.ItemID);
                        using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                        {
                            if (!dr.Read())
                            {
                                _ErrorMessage = "No Record Found";
                                return;
                            }
                            ReadData(dr);
                            // load child objects
                            dr.NextResult();
                            _ItemAnnotations = ItemAnnotations.Get(dr);
                            // load child objects
                            dr.NextResult();
                            _ItemDocVersions = ItemDocVersions.Get(dr);
                            // load child objects
                            dr.NextResult();
                            _ItemParts = ItemParts.Get(dr);
                            // load child objects
                            dr.NextResult();
                            _ItemTransitions_RangeID = ItemTransitions_RangeID.Get(dr);
                            // load child objects
                            dr.NextResult();
                            _ItemTransitions_ToID = ItemTransitions_ToID.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("Item.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Item.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("Item.DataPortal_Insert", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Item.DataPortal_Insert", ex);
            }
            finally
            {
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Insert", GetHashCode());
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        internal void SQLInsert()
        {
            if (!this.IsDirty) return;
            try
            {
                if (_MyContent != null) _MyContent.Update();
                SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "addItem";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@PreviousID", PreviousID);
                    cm.Parameters.AddWithValue("@ContentID", ContentID);
                    if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
                    cm.Parameters.AddWithValue("@UserID", _UserID);
                    // Output Calculated Columns
                    SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int);
                    param_ItemID.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_ItemID);
                    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
                    _ItemID = (int)cm.Parameters["@newItemID"].Value;
                    _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
                }
                MarkOld();
                // update child objects
                if (_ItemAnnotations != null) _ItemAnnotations.Update(this);
                if (_ItemDocVersions != null) _ItemDocVersions.Update(this);
                if (_NextItems != null) _NextItems.Update(this);
                if (_ItemParts != null) _ItemParts.Update(this);
                if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID.Update(this);
                if (_ItemTransitions_ToID != null) _ItemTransitions_ToID.Update(this);
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.SQLInsert", GetHashCode());
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.SQLInsert", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Item.SQLInsert", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static byte[] Add(SqlConnection cn, ref int itemID, Item myPrevious, Content myContent, DateTime dts, string userID)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Add", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "addItem";
                    // Input All Fields - Except Calculated Columns
                    if (myPrevious != null) cm.Parameters.AddWithValue("@PreviousID", myPrevious.ItemID);
                    cm.Parameters.AddWithValue("@ContentID", myContent.ContentID);
                    if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
                    cm.Parameters.AddWithValue("@UserID", userID);
                    // Output Calculated Columns
                    SqlParameter param_ItemID = new SqlParameter("@newItemID", SqlDbType.Int);
                    param_ItemID.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_ItemID);
                    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
                    itemID = (int)cm.Parameters["@newItemID"].Value;
                    return (byte[])cm.Parameters["@newLastChanged"].Value;
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.Add", ex);
                throw new DbCslaException("Item.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}] Item.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("Item.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}] Item.SQLUpdate", GetHashCode());
            try
            {
                if (_MyContent != null) _MyContent.Update();
                SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
                if (base.IsDirty)
                {
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "updateItem";
                        // All Fields including Calculated Fields
                        cm.Parameters.AddWithValue("@ItemID", _ItemID);
                        cm.Parameters.AddWithValue("@PreviousID", PreviousID);
                        cm.Parameters.AddWithValue("@ContentID", ContentID);
                        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 (_ItemAnnotations != null) _ItemAnnotations.Update(this);
                if (_ItemDocVersions != null) _ItemDocVersions.Update(this);
                if (_NextItems != null) _NextItems.Update(this);
                if (_ItemParts != null) _ItemParts.Update(this);
                if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID.Update(this);
                if (_ItemTransitions_ToID != null) _ItemTransitions_ToID.Update(this);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.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 = Item.Add(cn, ref _ItemID, _MyPrevious, _MyContent, _DTS, _UserID);
                else
                    _LastChanged = Item.Update(cn, ref _ItemID, _MyPrevious, _MyContent, _DTS, _UserID, ref _LastChanged);
                MarkOld();
            }
            if (_ItemAnnotations != null) _ItemAnnotations.Update(this);
            if (_ItemDocVersions != null) _ItemDocVersions.Update(this);
            if (_NextItems != null) _NextItems.Update(this);
            if (_ItemParts != null) _ItemParts.Update(this);
            if (_ItemTransitions_RangeID != null) _ItemTransitions_RangeID.Update(this);
            if (_ItemTransitions_ToID != null) _ItemTransitions_ToID.Update(this);
        }
        internal void DeleteSelf(Item item)
        {
            // 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"];
            Item.Remove(cn, _ItemID);
            MarkNew();
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static byte[] Update(SqlConnection cn, ref int itemID, Item myPrevious, Content myContent, DateTime dts, string userID, ref byte[] lastChanged)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Update", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "updateItem";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@ItemID", itemID);
                    if (myPrevious != null) cm.Parameters.AddWithValue("@PreviousID", myPrevious.ItemID);
                    cm.Parameters.AddWithValue("@ContentID", myContent.ContentID);
                    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("Item.Update", ex);
                throw new DbCslaException("Item.Update", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new PKCriteria(_ItemID));
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode());
            try
            {
                using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                {
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "deleteItem";
                        cm.Parameters.AddWithValue("@ItemID", criteria.ItemID);
                        cm.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.DataPortal_Delete", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Item.DataPortal_Delete", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static void Remove(SqlConnection cn, int itemID)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.Remove", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "deleteItem";
                    // Input PK Fields
                    cm.Parameters.AddWithValue("@ItemID", itemID);
                    // TODO: Define any additional output parameters
                    cm.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.Remove", ex);
                throw new DbCslaException("Item.Remove", ex);
            }
        }
        #endregion
        #region Exists
        public static bool Exists(int itemID)
        {
            ExistsCommand result;
            try
            {
                result = DataPortal.Execute(new ExistsCommand(itemID));
                return result.Exists;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Item.Exists", ex);
            }
        }
        [Serializable()]
        private class ExistsCommand : CommandBase
        {
            private int _ItemID;
            private bool _exists;
            public bool Exists
            {
                get { return _exists; }
            }
            public ExistsCommand(int itemID)
            {
                _ItemID = itemID;
            }
            protected override void DataPortal_Execute()
            {
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Execute", GetHashCode());
                try
                {
                    using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                    {
                        cn.Open();
                        using (SqlCommand cm = cn.CreateCommand())
                        {
                            cm.CommandType = CommandType.StoredProcedure;
                            cm.CommandText = "existsItem";
                            cm.Parameters.AddWithValue("@ItemID", _ItemID);
                            int count = (int)cm.ExecuteScalar();
                            _exists = (count > 0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (_MyLog.IsErrorEnabled) _MyLog.Error("Item.DataPortal_Execute", ex);
                    throw new DbCslaException("Item.DataPortal_Execute", ex);
                }
            }
        }
        #endregion
        // Standard Default Code
        #region extension
        ItemExtension _ItemExtension = new ItemExtension();
        [Serializable()]
        partial class ItemExtension : extensionBase
        {
        }
        [Serializable()]
        class extensionBase
        {
            // Default Values
            public virtual DateTime DefaultDTS
            {
                get { return DateTime.Now; }
            }
            public virtual string DefaultUserID
            {
                get { return Environment.UserName.ToUpper(); }
            }
            // Authorization Rules
            public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
            {
                // Needs to be overriden to add new authorization rules
            }
            // Instance Authorization Rules
            public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
            {
                // Needs to be overriden to add new authorization rules
            }
            // Validation Rules
            public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
            {
                // Needs to be overriden to add new validation rules
            }
            // InstanceValidation Rules
            public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
            {
                // Needs to be overriden to add new validation rules
            }
        }
        #endregion
    } // Class
    #region Converter
    internal class ItemConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is Item)
            {
                // Return the ToString value
                return ((Item)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace
//// The following is a sample Extension File.  You can use it to create ItemExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
//  public partial class Item
//  {
//    partial class ItemExtension : extensionBase
//    {
//      // TODO: Override automatic defaults
//      public virtual DateTime DefaultDTS
//      {
//        get { return DateTime.Now; }
//      }
//      public virtual string DefaultUserID
//      {
//        get { return Environment.UserName.ToUpper(); }
//      }
//      public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
//      {
//        //rules.AllowRead(Dbid, "");
//      }
//      public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
//      {
//        //rules.AllowInstanceRead(Dbid, "");
//      }
//      public new void AddValidationRules(Csla.Validation.ValidationRules rules)
//      {
//        rules.AddRule(
//          Csla.Validation.CommonRules.StringMaxLength,
//          new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
//      }
//      public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
//      {
//        rules.AddInstanceRule(/* Instance Validation Rule */);
//      }
//    }
//  }
//}