// ========================================================================
// 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
{
    /// 
    ///	Document Generated by MyGeneration using the CSLA Object Mapping template
    /// 
    [Serializable()]
    [TypeConverter(typeof(DocumentConverter))]
    public partial class Document : BusinessBase, IDisposable, IVEHasBrokenRules
    {
        #region Log4Net
        private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion
        #region Refresh
        private List _RefreshDocuments = new List();
        private List _RefreshDocumentEntries = new List();
        private void AddToRefreshList(List refreshDocuments, List refreshDocumentEntries)
        {
            if (IsDirty)
                refreshDocuments.Add(this);
            if (_DocumentEntries != null && _DocumentEntries.IsDirty)
            {
                foreach (DocumentEntry tmp in _DocumentEntries)
                {
                    if (tmp.IsDirty) refreshDocumentEntries.Add(tmp);
                }
            }
        }
        private void BuildRefreshList()
        {
            _RefreshDocuments = new List();
            _RefreshDocumentEntries = new List();
            AddToRefreshList(_RefreshDocuments, _RefreshDocumentEntries);
        }
        private void ProcessRefreshList()
        {
            foreach (Document tmp in _RefreshDocuments)
            {
                DocumentInfo.Refresh(tmp);
            }
            foreach (DocumentEntry tmp in _RefreshDocumentEntries)
            {
                EntryInfo.Refresh(tmp);
            }
        }
        #endregion
        #region Collection
        private static List _CacheList = new List();
        protected static void AddToCache(Document document)
        {
            if (!_CacheList.Contains(document)) _CacheList.Add(document); // In AddToCache
        }
        protected static void RemoveFromCache(Document document)
        {
            while (_CacheList.Contains(document)) _CacheList.Remove(document); // In RemoveFromCache
        }
        private static Dictionary> _CacheByPrimaryKey = new Dictionary>();
        private static void ConvertListToDictionary()
        {
            List remove = new List();
            foreach (Document tmp in _CacheList)
            {
                if (!_CacheByPrimaryKey.ContainsKey(tmp.DocID.ToString()))
                {
                    _CacheByPrimaryKey[tmp.DocID.ToString()] = new List(); // Add new list for PrimaryKey
                }
                _CacheByPrimaryKey[tmp.DocID.ToString()].Add(tmp); // Add to Primary Key list
                remove.Add(tmp);
            }
            foreach (Document tmp in remove)
                RemoveFromCache(tmp);
        }
        protected static Document GetCachedByPrimaryKey(int docID)
        {
            ConvertListToDictionary();
            string key = docID.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 _nextDocID = -1;
        public static int NextDocID
        {
            get { return _nextDocID--; }
        }
        private int _DocID;
        [System.ComponentModel.DataObjectField(true, true)]
        public int DocID
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DocID;
            }
        }
        private string _LibTitle = string.Empty;
        public string LibTitle
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _LibTitle;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (value == null) value = string.Empty;
                if (_LibTitle != value)
                {
                    _LibTitle = value;
                    PropertyHasChanged();
                }
            }
        }
        private byte[] _DocContent;
        /// 
        /// Actual content of a Word Document (RTF, DOC or XML Format)
        /// 
        public byte[] DocContent
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DocContent;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (_DocContent != value)
                {
                    _DocContent = value;
                    PropertyHasChanged();
                }
            }
        }
        private string _DocAscii = string.Empty;
        /// 
        /// Used for searching
        /// 
        public string DocAscii
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DocAscii;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                if (value == null) value = string.Empty;
                if (_DocAscii != value)
                {
                    _DocAscii = 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 _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 _DocumentEntryCount = 0;
        /// 
        /// Count of DocumentEntries for this Document
        /// 
        public int DocumentEntryCount
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                return _DocumentEntryCount;
            }
        }
        private DocumentEntries _DocumentEntries = null;
        /// 
        /// Related Field
        /// 
        [TypeConverter(typeof(DocumentEntriesConverter))]
        public DocumentEntries DocumentEntries
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                if (_DocumentEntryCount > 0 && _DocumentEntries == null)
                    _DocumentEntries = DocumentEntries.GetByDocID(DocID);
                else if (_DocumentEntries == null)
                    _DocumentEntries = DocumentEntries.New();
                return _DocumentEntries;
            }
        }
        public override bool IsDirty
        {
            get { return base.IsDirty || (_DocumentEntries == null ? false : _DocumentEntries.IsDirty); }
        }
        public override bool IsValid
        {
            get { return (IsNew && !IsDirty ? true : base.IsValid) && (_DocumentEntries == null ? true : _DocumentEntries.IsValid); }
        }
        // TODO: Replace base Document.ToString function as necessary
        /// 
        /// Overrides Base ToString
        /// 
        /// A string representation of current Document
        //public override string ToString()
        //{
        //  return base.ToString();
        //}
        // TODO: Check Document.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 Document
        protected override object GetIdValue()
        {
            return _DocID;
        }
        #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 (_DocumentEntries != null && (hasBrokenRules = _DocumentEntries.HasBrokenRules) != null) return hasBrokenRules;
                    return hasBrokenRules;
                }
                finally
                {
                    _CheckingBrokenRules = false;
                }
            }
        }
        public BrokenRulesCollection BrokenRules
        {
            get
            {
                IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
                if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
                return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
            }
        }
        protected override void AddBusinessRules()
        {
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("LibTitle", 1024));
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("DocAscii", 1073741823));
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("Config", 1073741823));
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringRequired, "UserID");
            ValidationRules.AddRule(
                Csla.Validation.CommonRules.StringMaxLength,
                new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100));
            //ValidationRules.AddDependantProperty("x", "y");
            _DocumentExtension.AddValidationRules(ValidationRules);
            // TODO:  Add other validation rules
        }
        protected override void AddInstanceBusinessRules()
        {
            _DocumentExtension.AddInstanceValidationRules(ValidationRules);
            // TODO:  Add other validation rules
        }
        // Sample data comparison validation rule
        //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
        //{
        //	if (_started > _ended)
        //	{
        //		e.Description = "Start date can't be after end date";
        //		return false;
        //	}
        //	else
        //		return true;
        //}
        #endregion
        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Who can read/write which fields
            //AuthorizationRules.AllowRead(DocID, "");
            //AuthorizationRules.AllowRead(LibTitle, "");
            //AuthorizationRules.AllowRead(DocContent, "");
            //AuthorizationRules.AllowRead(DocAscii, "");
            //AuthorizationRules.AllowRead(Config, "");
            //AuthorizationRules.AllowRead(DTS, "");
            //AuthorizationRules.AllowRead(UserID, "");
            //AuthorizationRules.AllowWrite(LibTitle, "");
            //AuthorizationRules.AllowWrite(DocContent, "");
            //AuthorizationRules.AllowWrite(DocAscii, "");
            //AuthorizationRules.AllowWrite(Config, "");
            //AuthorizationRules.AllowWrite(DTS, "");
            //AuthorizationRules.AllowWrite(UserID, "");
            _DocumentExtension.AddAuthorizationRules(AuthorizationRules);
        }
        protected override void AddInstanceAuthorizationRules()
        {
            //TODO: Who can read/write which fields
            _DocumentExtension.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 += _DocumentEntryCount;
                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 _DocumentUnique = 0;
        protected static int DocumentUnique
        { get { return ++_DocumentUnique; } }
        private int _MyDocumentUnique = DocumentUnique;
        public int MyDocumentUnique
        { get { return _MyDocumentUnique; } }
        protected Document()
        {/* require use of factory methods */
            AddToCache(this);
        }
        public void Dispose()
        {
            RemoveFromDictionaries();
        }
        private void RemoveFromDictionaries()
        {
            RemoveFromCache(this);
            if (_CacheByPrimaryKey.ContainsKey(DocID.ToString()))
            {
                List listDocument = _CacheByPrimaryKey[DocID.ToString()]; // Get the list of items
                while (listDocument.Contains(this)) listDocument.Remove(this); // Remove the item from the list
                if (listDocument.Count == 0) //If there are no items left in the list
                    _CacheByPrimaryKey.Remove(DocID.ToString()); // remove the list
            }
        }
        public static Document New()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Document");
            try
            {
                return DataPortal.Create();
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Document.New", ex);
            }
        }
        public static Document New(string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID)
        {
            Document tmp = Document.New();
            tmp.LibTitle = libTitle;
            tmp.DocContent = docContent;
            tmp.DocAscii = docAscii;
            tmp.Config = config;
            tmp.DTS = dts;
            tmp.UserID = userID;
            return tmp;
        }
        public static Document MakeDocument(string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID)
        {
            Document tmp = Document.New(libTitle, docContent, docAscii, config, dts, userID);
            if (tmp.IsSavable)
            {
                Document 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 Document New(string libTitle, byte[] docContent, string docAscii, string config)
        {
            Document tmp = Document.New();
            tmp.LibTitle = libTitle;
            tmp.DocContent = docContent;
            tmp.DocAscii = docAscii;
            tmp.Config = config;
            return tmp;
        }
        public static Document MakeDocument(string libTitle, byte[] docContent, string docAscii, string config)
        {
            Document tmp = Document.New(libTitle, docContent, docAscii, config);
            if (tmp.IsSavable)
            {
                Document 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 Document Get(int docID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Document");
            try
            {
                Document tmp = GetCachedByPrimaryKey(docID);
                if (tmp == null)
                {
                    tmp = DataPortal.Fetch(new PKCriteria(docID));
                    AddToCache(tmp);
                }
                if (tmp.ErrorMessage == "No Record Found")
                {
                    tmp.Dispose(); // Clean-up Document
                    tmp = null;
                }
                return tmp;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Document.Get", ex);
            }
        }
        public static Document Get(SafeDataReader dr)
        {
            if (dr.Read()) return new Document(dr);
            return null;
        }
        internal Document(SafeDataReader dr)
        {
            ReadData(dr);
        }
        public static void Delete(int docID)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Document");
            try
            {
                DataPortal.Delete(new PKCriteria(docID));
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Document.Delete", ex);
            }
        }
        public override Document Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Document");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Document");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a Document");
            try
            {
                BuildRefreshList();
                Document document = base.Save();
                RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache
                AddToCache(document);//Refresh the item in AllList
                ProcessRefreshList();
                return document;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on CSLA Save", ex);
            }
        }
        #endregion
        #region Data Access Portal
        [Serializable()]
        protected class PKCriteria
        {
            private int _DocID;
            public int DocID
            { get { return _DocID; } }
            public PKCriteria(int docID)
            {
                _DocID = docID;
            }
        }
        // TODO: If Create needs to access DB - It should not be marked RunLocal
        [RunLocal()]
        private new void DataPortal_Create()
        {
            _DocID = NextDocID;
            // Database Defaults
            _DTS = _DocumentExtension.DefaultDTS;
            _UserID = _DocumentExtension.DefaultUserID;
            // TODO: Add any defaults that are necessary
            ValidationRules.CheckRules();
        }
        private void ReadData(SafeDataReader dr)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.ReadData", GetHashCode());
            try
            {
                _DocID = dr.GetInt32("DocID");
                _LibTitle = dr.GetString("LibTitle");
                _DocContent = (byte[])dr.GetValue("DocContent");
                _DocAscii = dr.GetString("DocAscii");
                _Config = dr.GetString("Config");
                _DTS = dr.GetDateTime("DTS");
                _UserID = dr.GetString("UserID");
                dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8);
                _DocumentEntryCount = dr.GetInt32("EntryCount");
                MarkOld();
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.ReadData", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Document.ReadData", ex);
            }
        }
        private void DataPortal_Fetch(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.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 = "getDocument";
                        cm.Parameters.AddWithValue("@DocID", criteria.DocID);
                        using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                        {
                            if (!dr.Read())
                            {
                                _ErrorMessage = "No Record Found";
                                return;
                            }
                            ReadData(dr);
                            // load child objects
                            dr.NextResult();
                            _DocumentEntries = DocumentEntries.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("Document.DataPortal_Fetch", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Document.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("Document.DataPortal_Insert", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Document.DataPortal_Insert", ex);
            }
            finally
            {
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Insert", GetHashCode());
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        internal void SQLInsert()
        {
            if (!this.IsDirty) return;
            try
            {
                SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "addDocument";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@LibTitle", _LibTitle);
                    cm.Parameters.AddWithValue("@DocContent", _DocContent);
                    cm.Parameters.AddWithValue("@DocAscii", _DocAscii);
                    cm.Parameters.AddWithValue("@Config", _Config);
                    if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
                    cm.Parameters.AddWithValue("@UserID", _UserID);
                    // Output Calculated Columns
                    SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int);
                    param_DocID.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_DocID);
                    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
                    _DocID = (int)cm.Parameters["@newDocID"].Value;
                    _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
                }
                MarkOld();
                // update child objects
                if (_DocumentEntries != null) _DocumentEntries.Update(this);
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLInsert", GetHashCode());
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.SQLInsert", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Document.SQLInsert", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static byte[] Add(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Add", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "addDocument";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@LibTitle", libTitle);
                    cm.Parameters.AddWithValue("@DocContent", docContent);
                    cm.Parameters.AddWithValue("@DocAscii", docAscii);
                    cm.Parameters.AddWithValue("@Config", config);
                    if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
                    cm.Parameters.AddWithValue("@UserID", userID);
                    // Output Calculated Columns
                    SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int);
                    param_DocID.Direction = ParameterDirection.Output;
                    cm.Parameters.Add(param_DocID);
                    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
                    docID = (int)cm.Parameters["@newDocID"].Value;
                    return (byte[])cm.Parameters["@newLastChanged"].Value;
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.Add", ex);
                throw new DbCslaException("Document.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}] Document.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("Document.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}] Document.SQLUpdate", GetHashCode());
            try
            {
                SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
                if (base.IsDirty)
                {
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "updateDocument";
                        // All Fields including Calculated Fields
                        cm.Parameters.AddWithValue("@DocID", _DocID);
                        cm.Parameters.AddWithValue("@LibTitle", _LibTitle);
                        cm.Parameters.AddWithValue("@DocContent", _DocContent);
                        cm.Parameters.AddWithValue("@DocAscii", _DocAscii);
                        cm.Parameters.AddWithValue("@Config", _Config);
                        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 (_DocumentEntries != null) _DocumentEntries.Update(this);
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.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 = Document.Add(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID);
                else
                    _LastChanged = Document.Update(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, ref _LastChanged);
                MarkOld();
            }
            if (_DocumentEntries != null) _DocumentEntries.Update(this);
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static byte[] Update(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, ref byte[] lastChanged)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Update", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "updateDocument";
                    // Input All Fields - Except Calculated Columns
                    cm.Parameters.AddWithValue("@DocID", docID);
                    cm.Parameters.AddWithValue("@LibTitle", libTitle);
                    cm.Parameters.AddWithValue("@DocContent", docContent);
                    cm.Parameters.AddWithValue("@DocAscii", docAscii);
                    cm.Parameters.AddWithValue("@Config", config);
                    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("Document.Update", ex);
                throw new DbCslaException("Document.Update", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new PKCriteria(_DocID));
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        private void DataPortal_Delete(PKCriteria criteria)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Delete", GetHashCode());
            try
            {
                using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                {
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandType = CommandType.StoredProcedure;
                        cm.CommandText = "deleteDocument";
                        cm.Parameters.AddWithValue("@DocID", criteria.DocID);
                        cm.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.DataPortal_Delete", ex);
                _ErrorMessage = ex.Message;
                throw new DbCslaException("Document.DataPortal_Delete", ex);
            }
        }
        [Transactional(TransactionalTypes.TransactionScope)]
        public static void Remove(SqlConnection cn, int docID)
        {
            if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Remove", 0);
            try
            {
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.CommandText = "deleteDocument";
                    // Input PK Fields
                    cm.Parameters.AddWithValue("@DocID", docID);
                    // TODO: Define any additional output parameters
                    cm.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.Remove", ex);
                throw new DbCslaException("Document.Remove", ex);
            }
        }
        #endregion
        #region Exists
        public static bool Exists(int docID)
        {
            ExistsCommand result;
            try
            {
                result = DataPortal.Execute(new ExistsCommand(docID));
                return result.Exists;
            }
            catch (Exception ex)
            {
                throw new DbCslaException("Error on Document.Exists", ex);
            }
        }
        [Serializable()]
        private class ExistsCommand : CommandBase
        {
            private int _DocID;
            private bool _exists;
            public bool Exists
            {
                get { return _exists; }
            }
            public ExistsCommand(int docID)
            {
                _DocID = docID;
            }
            protected override void DataPortal_Execute()
            {
                if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Execute", GetHashCode());
                try
                {
                    using (SqlConnection cn = Database.VEPROMS_SqlConnection)
                    {
                        cn.Open();
                        using (SqlCommand cm = cn.CreateCommand())
                        {
                            cm.CommandType = CommandType.StoredProcedure;
                            cm.CommandText = "existsDocument";
                            cm.Parameters.AddWithValue("@DocID", _DocID);
                            int count = (int)cm.ExecuteScalar();
                            _exists = (count > 0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (_MyLog.IsErrorEnabled) _MyLog.Error("Document.DataPortal_Execute", ex);
                    throw new DbCslaException("Document.DataPortal_Execute", ex);
                }
            }
        }
        #endregion
        // Standard Default Code
        #region extension
        DocumentExtension _DocumentExtension = new DocumentExtension();
        [Serializable()]
        partial class DocumentExtension : 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 DocumentConverter : ExpandableObjectConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
        {
            if (destType == typeof(string) && value is Document)
            {
                // Return the ToString value
                return ((Document)value).ToString();
            }
            return base.ConvertTo(context, culture, value, destType);
        }
    }
    #endregion
} // Namespace
//// The following is a sample Extension File.  You can use it to create DocumentExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
//  public partial class Document
//  {
//    partial class DocumentExtension : 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 */);
//      }
//    }
//  }
//}