// ======================================================================== // 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 { /// /// Pdf Generated by MyGeneration using the CSLA Object Mapping template /// [Serializable()] [TypeConverter(typeof(PdfConverter))] public partial class Pdf : BusinessBase, IDisposable, IVEHasBrokenRules { #region Log4Net private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Refresh private List _RefreshPdfs = new List(); private void AddToRefreshList(List refreshPdfs) { if (IsDirty) refreshPdfs.Add(this); } private void ClearRefreshList() { _RefreshPdfs = new List(); } private void BuildRefreshList() { ClearRefreshList(); AddToRefreshList(_RefreshPdfs); } private void ProcessRefreshList() { foreach (Pdf tmp in _RefreshPdfs) { PdfInfo.Refresh(tmp); if (tmp._MyDocument != null) DocumentInfo.Refresh(tmp._MyDocument); } ClearRefreshList(); } #endregion #region Collection private static List _CacheList = new List(); protected static void AddToCache(Pdf pdf) { if (!_CacheList.Contains(pdf)) _CacheList.Add(pdf); // In AddToCache } protected static void RemoveFromCache(Pdf pdf) { while (_CacheList.Contains(pdf)) _CacheList.Remove(pdf); // In RemoveFromCache } private static Dictionary> _CacheByPrimaryKey = new Dictionary>(); private static void ConvertListToDictionary() { while (_CacheList.Count > 0) // Move Pdf(s) from temporary _CacheList to _CacheByPrimaryKey { Pdf tmp = _CacheList[0]; // Get the first Pdf string pKey = tmp.DocID.ToString() + "_" + tmp.DebugStatus.ToString() + "_" + tmp.TopRow.ToString() + "_" + tmp.PageLength.ToString() + "_" + tmp.LeftMargin.ToString() + "_" + tmp.PageWidth.ToString(); if (!_CacheByPrimaryKey.ContainsKey(pKey)) { _CacheByPrimaryKey[pKey] = new List(); // Add new list for PrimaryKey } _CacheByPrimaryKey[pKey].Add(tmp); // Add to Primary Key list _CacheList.RemoveAt(0); // Remove the first Pdf } } protected static Pdf GetCachedByPrimaryKey(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { ConvertListToDictionary(); string key = docID.ToString() + "_" + debugStatus.ToString() + "_" + topRow.ToString() + "_" + pageLength.ToString() + "_" + leftMargin.ToString() + "_" + pageWidth.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 int _DocID; [System.ComponentModel.DataObjectField(true, true)] public int DocID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyDocument != null) _DocID = _MyDocument.DocID; return _DocID; } } private Document _MyDocument; [System.ComponentModel.DataObjectField(true, true)] public Document MyDocument { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { if (_MyDocument == null && _DocID != 0) _MyDocument = Document.Get(_DocID); return _MyDocument; } } private int _DebugStatus; /// /// > 0 for Debug /// [System.ComponentModel.DataObjectField(true, true)] public int DebugStatus { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _DebugStatus; } } private int _TopRow; [System.ComponentModel.DataObjectField(true, true)] public int TopRow { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _TopRow; } } private int _PageLength; [System.ComponentModel.DataObjectField(true, true)] public int PageLength { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _PageLength; } } private int _LeftMargin; [System.ComponentModel.DataObjectField(true, true)] public int LeftMargin { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _LeftMargin; } } private int _PageWidth; [System.ComponentModel.DataObjectField(true, true)] public int PageWidth { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _PageWidth; } } private double _PageCount; /// /// Count of whole and partial pages /// public double PageCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _PageCount; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_PageCount != value) { _PageCount = value; PropertyHasChanged(); } } } private byte[] _DocPdf; public byte[] DocPdf { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { return _DocPdf; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { if (_DocPdf != value) { _DocPdf = 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 public override bool IsDirty { get { if (base.IsDirty) return true; return IsDirtyList(new List()); } } public bool IsDirtyList(List list) { if (base.IsDirty || list.Contains(this)) return base.IsDirty; list.Add(this); return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)); } public override bool IsValid { get { return IsValidList(new List()); } } public bool IsValidList(List list) { if (list.Contains(this)) return (IsNew && !IsDirty) ? true : base.IsValid; list.Add(this); return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)); } // CSLATODO: Replace base Pdf.ToString function as necessary /// /// Overrides Base ToString /// /// A string representation of current Pdf //public override string ToString() //{ // return base.ToString(); //} // CSLATODO: Check Pdf.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 Pdf protected override object GetIdValue() { return MyPdfUnique; // Absolutely Unique ID } #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; return hasBrokenRules; } finally { _CheckingBrokenRules = false; } } } public BrokenRulesCollection BrokenRules { get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); } } protected override void AddBusinessRules() { ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "UserID"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); //ValidationRules.AddDependantProperty("x", "y"); _PdfExtension.AddValidationRules(ValidationRules); // CSLATODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _PdfExtension.AddInstanceValidationRules(ValidationRules); // CSLATODO: 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() { //CSLATODO: Who can read/write which fields //AuthorizationRules.AllowRead(DocID, ""); //AuthorizationRules.AllowRead(DebugStatus, ""); //AuthorizationRules.AllowRead(TopRow, ""); //AuthorizationRules.AllowRead(PageLength, ""); //AuthorizationRules.AllowRead(LeftMargin, ""); //AuthorizationRules.AllowRead(PageWidth, ""); //AuthorizationRules.AllowRead(PageCount, ""); //AuthorizationRules.AllowRead(DocPdf, ""); //AuthorizationRules.AllowRead(DTS, ""); //AuthorizationRules.AllowRead(UserID, ""); //AuthorizationRules.AllowWrite(PageCount, ""); //AuthorizationRules.AllowWrite(DocPdf, ""); //AuthorizationRules.AllowWrite(DTS, ""); //AuthorizationRules.AllowWrite(UserID, ""); _PdfExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //CSLATODO: Who can read/write which fields _PdfExtension.AddInstanceAuthorizationRules(AuthorizationRules); } public static bool CanAddObject() { // CSLATODO: Can Add Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } public static bool CanGetObject() { // CSLATODO: CanGet Authorization return true; } public static bool CanDeleteObject() { // CSLATODO: 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; } public static bool CanEditObject() { // CSLATODO: CanEdit Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } #endregion #region Factory Methods public int CurrentEditLevel { get { return EditLevel; } } private static int _PdfUnique = 0; protected static int PdfUnique { get { return ++_PdfUnique; } } private int _MyPdfUnique = PdfUnique; public int MyPdfUnique // Absolutely Unique ID - Editable { get { return _MyPdfUnique; } } protected Pdf() {/* require use of factory methods */ AddToCache(this); } private bool _Disposed = false; private static int _CountCreated = 0; private static int _CountDisposed = 0; private static int _CountFinalized = 0; private static int IncrementCountCreated { get { return ++_CountCreated; } } private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated { get { return _CountCreated; } } public static int CountNotDisposed { get { return _CountCreated - _CountDisposed; } } public static int CountNotFinalized { get { return _CountCreated - _CountFinalized; } } ~Pdf() { _CountFinalized++; } public void Dispose() { if (_Disposed) return; _CountDisposed++; _Disposed = true; RemoveFromDictionaries(); } private void RemoveFromDictionaries() { RemoveFromCache(this); if (_CacheByPrimaryKey.ContainsKey(DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString())) { List listPdf = _CacheByPrimaryKey[DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString()]; // Get the list of items while (listPdf.Contains(this)) listPdf.Remove(this); // Remove the item from the list if (listPdf.Count == 0) //If there are no items left in the list _CacheByPrimaryKey.Remove(DocID.ToString() + "_" + DebugStatus.ToString() + "_" + TopRow.ToString() + "_" + PageLength.ToString() + "_" + LeftMargin.ToString() + "_" + PageWidth.ToString()); // remove the list } } public static Pdf New() { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Pdf"); try { return DataPortal.Create(); } catch (Exception ex) { throw new DbCslaException("Error on Pdf.New", ex); } } public static Pdf New(Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount) { Pdf tmp = Pdf.New(); tmp._MyDocument = myDocument; tmp._DebugStatus = debugStatus; tmp._TopRow = topRow; tmp._PageLength = pageLength; tmp._LeftMargin = leftMargin; tmp._PageWidth = pageWidth; tmp.PageCount = pageCount; return tmp; } public static Pdf New(Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf, DateTime dts, string userID) { Pdf tmp = Pdf.New(); tmp._MyDocument = myDocument; tmp._DebugStatus = debugStatus; tmp._TopRow = topRow; tmp._PageLength = pageLength; tmp._LeftMargin = leftMargin; tmp._PageWidth = pageWidth; tmp.PageCount = pageCount; tmp.DocPdf = docPdf; tmp.DTS = dts; tmp.UserID = userID; return tmp; } public static Pdf MakePdf(Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf, DateTime dts, string userID) { Pdf tmp = Pdf.New(myDocument, debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount, docPdf, dts, userID); if (tmp.IsSavable) tmp = tmp.Save(); 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 Pdf New(Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf) { Pdf tmp = Pdf.New(); tmp._MyDocument = myDocument; tmp._DebugStatus = debugStatus; tmp._TopRow = topRow; tmp._PageLength = pageLength; tmp._LeftMargin = leftMargin; tmp._PageWidth = pageWidth; tmp.PageCount = pageCount; tmp.DocPdf = docPdf; return tmp; } public static Pdf MakePdf(Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf) { Pdf tmp = Pdf.New(myDocument, debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount, docPdf); if (tmp.IsSavable) tmp = tmp.Save(); 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 Pdf Get(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Pdf"); try { Pdf tmp = GetCachedByPrimaryKey(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth); if (tmp == null) { tmp = DataPortal.Fetch(new PKCriteria(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth)); AddToCache(tmp); } if (tmp.ErrorMessage == "No Record Found") { tmp.Dispose(); // Clean-up Pdf tmp = null; } return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Pdf.Get", ex); } } public static Pdf Get(SafeDataReader dr) { if (dr.Read()) return new Pdf(dr); return null; } internal Pdf(SafeDataReader dr) { ReadData(dr); } public static void Delete(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Pdf"); try { DataPortal.Delete(new PKCriteria(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth)); } catch (Exception ex) { throw new DbCslaException("Error on Pdf.Delete", ex); } } public override Pdf Save() { if (IsDeleted && !CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Pdf"); else if (IsNew && !CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Pdf"); else if (!CanEditObject()) throw new System.Security.SecurityException("User not authorized to update a Pdf"); try { BuildRefreshList(); Pdf pdf = base.Save(); RemoveFromDictionaries(); // if save is successful remove the previous Folder from the cache AddToCache(pdf);//Refresh the item in AllList ProcessRefreshList(); return pdf; } catch (Exception ex) { if (MSWordToPDF.DocReplace != null) // if creating an Approved export then ignore the error { _MyLog.WarnFormat("here"); GC.Collect(); // memory garbage collection return this; } else 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; } } private int _DebugStatus; public int DebugStatus { get { return _DebugStatus; } } private int _TopRow; public int TopRow { get { return _TopRow; } } private int _PageLength; public int PageLength { get { return _PageLength; } } private int _LeftMargin; public int LeftMargin { get { return _LeftMargin; } } private int _PageWidth; public int PageWidth { get { return _PageWidth; } } public PKCriteria(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { _DocID = docID; _DebugStatus = debugStatus; _TopRow = topRow; _PageLength = pageLength; _LeftMargin = leftMargin; _PageWidth = pageWidth; } } // CSLATODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { // Database Defaults _DTS = _PdfExtension.DefaultDTS; _UserID = _PdfExtension.DefaultUserID; // CSLATODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.ReadData", GetHashCode()); try { _DocID = dr.GetInt32("DocID"); _DebugStatus = dr.GetInt32("DebugStatus"); _TopRow = dr.GetInt32("TopRow"); _PageLength = dr.GetInt32("PageLength"); _LeftMargin = dr.GetInt32("LeftMargin"); _PageWidth = dr.GetInt32("PageWidth"); _PageCount = dr.GetDouble("PageCount"); _DocPdf = (byte[])dr.GetValue("DocPdf"); _DTS = dr.GetDateTime("DTS"); _UserID = dr.GetString("UserID"); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); MarkOld(); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Pdf.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.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 = "getPdf"; cm.Parameters.AddWithValue("@DocID", criteria.DocID); cm.Parameters.AddWithValue("@DebugStatus", criteria.DebugStatus); cm.Parameters.AddWithValue("@TopRow", criteria.TopRow); cm.Parameters.AddWithValue("@PageLength", criteria.PageLength); cm.Parameters.AddWithValue("@LeftMargin", criteria.LeftMargin); cm.Parameters.AddWithValue("@PageWidth", criteria.PageWidth); cm.CommandTimeout = Database.DefaultTimeout; using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); } } // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Pdf.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("Pdf.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Pdf.DataPortal_Insert", ex); } finally { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Insert", GetHashCode()); } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLInsert() { if (!this.IsDirty) return; try { if (_MyDocument != null) _MyDocument.Update(); SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addPdf"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@DocID", DocID); cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); cm.Parameters.AddWithValue("@TopRow", _TopRow); cm.Parameters.AddWithValue("@PageLength", _PageLength); cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); cm.Parameters.AddWithValue("@PageWidth", _PageWidth); cm.Parameters.AddWithValue("@PageCount", _PageCount); cm.Parameters.AddWithValue("@DocPdf", _DocPdf); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserID", _UserID); // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure _LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; } MarkOld(); // update child objects if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.SQLInsert", GetHashCode()); } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Pdf.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Add(SqlConnection cn, Document myDocument, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf, DateTime dts, string userID) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "addPdf"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@DocID", myDocument.DocID); cm.Parameters.AddWithValue("@DebugStatus", debugStatus); cm.Parameters.AddWithValue("@TopRow", topRow); cm.Parameters.AddWithValue("@PageLength", pageLength); cm.Parameters.AddWithValue("@LeftMargin", leftMargin); cm.Parameters.AddWithValue("@PageWidth", pageWidth); cm.Parameters.AddWithValue("@PageCount", pageCount); cm.Parameters.AddWithValue("@DocPdf", docPdf); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); cm.Parameters.AddWithValue("@UserID", userID); // Output Calculated Columns SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.Add(param_LastChanged); // CSLATODO: 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("Pdf.Add", ex); throw new DbCslaException("Pdf.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}] Pdf.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("Pdf.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}] Pdf.SQLUpdate", GetHashCode()); try { if (_MyDocument != null) _MyDocument.Update(); SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updatePdf"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@DocID", DocID); cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); cm.Parameters.AddWithValue("@TopRow", _TopRow); cm.Parameters.AddWithValue("@PageLength", _PageLength); cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); cm.Parameters.AddWithValue("@PageWidth", _PageWidth); cm.Parameters.AddWithValue("@PageCount", _PageCount); cm.Parameters.AddWithValue("@DocPdf", _DocPdf); 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); // CSLATODO: 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 } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.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 = Pdf.Add(cn, _MyDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID); else _LastChanged = Pdf.Update(cn, _DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged); MarkOld(); } } [Transactional(TransactionalTypes.TransactionScope)] public static byte[] Update(SqlConnection cn, int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount, byte[] docPdf, DateTime dts, string userID, ref byte[] lastChanged) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "updatePdf"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@DocID", docID); cm.Parameters.AddWithValue("@DebugStatus", debugStatus); cm.Parameters.AddWithValue("@TopRow", topRow); cm.Parameters.AddWithValue("@PageLength", pageLength); cm.Parameters.AddWithValue("@LeftMargin", leftMargin); cm.Parameters.AddWithValue("@PageWidth", pageWidth); cm.Parameters.AddWithValue("@PageCount", pageCount); cm.Parameters.AddWithValue("@DocPdf", docPdf); 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); // CSLATODO: 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("Pdf.Update", ex); throw new DbCslaException("Pdf.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Delete", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "deletePdf"; cm.Parameters.AddWithValue("@DocID", criteria.DocID); cm.Parameters.AddWithValue("@DebugStatus", criteria.DebugStatus); cm.Parameters.AddWithValue("@TopRow", criteria.TopRow); cm.Parameters.AddWithValue("@PageLength", criteria.PageLength); cm.Parameters.AddWithValue("@LeftMargin", criteria.LeftMargin); cm.Parameters.AddWithValue("@PageWidth", criteria.PageWidth); cm.ExecuteNonQuery(); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Pdf.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "deletePdf"; // Input PK Fields cm.Parameters.AddWithValue("@DocID", docID); cm.Parameters.AddWithValue("@DebugStatus", debugStatus); cm.Parameters.AddWithValue("@TopRow", topRow); cm.Parameters.AddWithValue("@PageLength", pageLength); cm.Parameters.AddWithValue("@LeftMargin", leftMargin); cm.Parameters.AddWithValue("@PageWidth", pageWidth); // CSLATODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.Remove", ex); throw new DbCslaException("Pdf.Remove", ex); } } #endregion #region Exists public static bool Exists(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { ExistsCommand result; try { result = DataPortal.Execute(new ExistsCommand(docID, debugStatus, topRow, pageLength, leftMargin, pageWidth)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on Pdf.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private int _DocID; private int _DebugStatus; private int _TopRow; private int _PageLength; private int _LeftMargin; private int _PageWidth; private bool _exists; public bool Exists { get { return _exists; } } public ExistsCommand(int docID, int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth) { _DocID = docID; _DebugStatus = debugStatus; _TopRow = topRow; _PageLength = pageLength; _LeftMargin = leftMargin; _PageWidth = pageWidth; } protected override void DataPortal_Execute() { if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.VEPROMS_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandTimeout = Database.SQLTimeout; cm.CommandText = "existsPdf"; cm.Parameters.AddWithValue("@DocID", _DocID); cm.Parameters.AddWithValue("@DebugStatus", _DebugStatus); cm.Parameters.AddWithValue("@TopRow", _TopRow); cm.Parameters.AddWithValue("@PageLength", _PageLength); cm.Parameters.AddWithValue("@LeftMargin", _LeftMargin); cm.Parameters.AddWithValue("@PageWidth", _PageWidth); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { if (_MyLog.IsErrorEnabled) _MyLog.Error("Pdf.DataPortal_Execute", ex); throw new DbCslaException("Pdf.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension PdfExtension _PdfExtension = new PdfExtension(); [Serializable()] partial class PdfExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual DateTime DefaultDTS { get { return DateTime.Now; } } public virtual string DefaultUserID { get { return Volian.Base.Library.VlnSettings.UserID; } } // 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 PdfConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is Pdf) { // Return the ToString value return ((Pdf)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create PdfExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace VEPROMS.CSLA.Library //{ // public partial class Pdf // { // partial class PdfExtension : extensionBase // { // // CSLATODO: 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 */); // } // } // } //}