CSLA - R to Z

This commit is contained in:
2026-09-14 15:30:10 -04:00
parent d238d6aed2
commit 1c6f3e3e3c
32 changed files with 1978 additions and 4455 deletions
+123 -268
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshRoUsages.Add(this); refreshRoUsages.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshRoUsages = new List<RoUsage>();
{
_RefreshRoUsages = new List<RoUsage>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<RoUsage> _CacheList = new List<RoUsage>(); private static List<RoUsage> _CacheList = new List<RoUsage>();
protected static void AddToCache(RoUsage roUsage) protected static void AddToCache(RoUsage roUsage)
{ {
@@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(roUsage)) _CacheList.Remove(roUsage); // In RemoveFromCache while (_CacheList.Contains(roUsage)) _CacheList.Remove(roUsage); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<RoUsage>> _CacheByPrimaryKey = new Dictionary<string, List<RoUsage>>(); private static Dictionary<string, List<RoUsage>> _CacheByPrimaryKey = new Dictionary<string, List<RoUsage>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -92,15 +89,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextROUsageID = -1; private static int _nextROUsageID = -1;
public static int NextROUsageID public static int NextROUsageID => _nextROUsageID--;
{
get { return _nextROUsageID--; }
}
private int _ROUsageID; private int _ROUsageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ROUsageID public int ROUsageID
@@ -261,37 +252,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)) || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list)) || (_MyRODb != null && _MyRODb.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list)) && (_MyRODb == null || _MyRODb.IsValidList(list));
} }
// CSLATODO: Replace base RoUsage.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current RoUsage</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check RoUsage.GetIdValue to assure that the ID returned is unique // CSLATODO: Check RoUsage.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current RoUsage</returns> /// <returns>A Unique ID for the current RoUsage</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyRoUsageUnique; // Absolutely Unique ID
{
return MyRoUsageUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -321,8 +297,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -369,35 +345,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(ROUsageID, "<Role(s)>");
//AuthorizationRules.AllowRead(ContentID, "<Role(s)>");
//AuthorizationRules.AllowRead(ROID, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(RODbID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ContentID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ROID, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RODbID, "<Role(s)>");
_RoUsageExtension.AddAuthorizationRules(AuthorizationRules); _RoUsageExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -405,42 +357,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_RoUsageExtension.AddInstanceAuthorizationRules(AuthorizationRules); _RoUsageExtension.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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _RoUsageUnique = 0; private static int _RoUsageUnique = 0;
protected static int RoUsageUnique protected static int RoUsageUnique => ++_RoUsageUnique;
{ get { return ++_RoUsageUnique; } } private readonly int _MyRoUsageUnique = RoUsageUnique;
private int _MyRoUsageUnique = RoUsageUnique; // Absolutely Unique ID - Editable
public int MyRoUsageUnique // Absolutely Unique ID - Editable public int MyRoUsageUnique => _MyRoUsageUnique;
{ get { return _MyRoUsageUnique; } }
protected RoUsage() protected RoUsage()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -449,15 +373,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RoUsage() ~RoUsage()
{ {
_CountFinalized++; _CountFinalized++;
@@ -482,8 +402,6 @@ namespace VEPROMS.CSLA.Library
} }
public static RoUsage New() public static RoUsage New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a RoUsage");
try try
{ {
return DataPortal.Create<RoUsage>(); return DataPortal.Create<RoUsage>();
@@ -554,8 +472,6 @@ namespace VEPROMS.CSLA.Library
} }
public static RoUsage Get(int rOUsageID) public static RoUsage Get(int rOUsageID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a RoUsage");
try try
{ {
RoUsage tmp = GetCachedByPrimaryKey(rOUsageID); RoUsage tmp = GetCachedByPrimaryKey(rOUsageID);
@@ -576,19 +492,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on RoUsage.Get", ex); throw new DbCslaException("Error on RoUsage.Get", ex);
} }
} }
public static RoUsage Get(SafeDataReader dr) public static RoUsage Get(SafeDataReader dr) => dr.Read() ? new RoUsage(dr) : null;
{ internal RoUsage(SafeDataReader dr) => ReadData(dr);
if (dr.Read()) return new RoUsage(dr);
return null;
}
internal RoUsage(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int rOUsageID) public static void Delete(int rOUsageID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a RoUsage");
try try
{ {
DataPortal.Delete(new PKCriteria(rOUsageID)); DataPortal.Delete(new PKCriteria(rOUsageID));
@@ -600,12 +507,6 @@ namespace VEPROMS.CSLA.Library
} }
public override RoUsage Save() public override RoUsage Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a RoUsage");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a RoUsage");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a RoUsage");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -625,13 +526,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _ROUsageID; private readonly int _ROUsageID;
public int ROUsageID public int ROUsageID => _ROUsageID;
{ get { return _ROUsageID; } } public PKCriteria(int rOUsageID) => _ROUsageID = rOUsageID;
public PKCriteria(int rOUsageID)
{
_ROUsageID = rOUsageID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -731,37 +628,44 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyContent != null) _MyContent.Update(); _MyContent?.Update();
if (_MyRODb != null) _MyRODb.Update(); _MyRODb?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addRoUsage"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ContentID", ContentID); cm.CommandText = "addRoUsage";
cm.Parameters.AddWithValue("@ROID", _ROID); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@ContentID", ContentID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ROID", _ROID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@RODbID", RODbID); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int); cm.Parameters.AddWithValue("@RODbID", RODbID);
param_ROUsageID.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_ROUsageID); SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int)
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); {
param_LastChanged.Direction = ParameterDirection.Output; Direction = ParameterDirection.Output
cm.Parameters.Add(param_LastChanged); };
// CSLATODO: Define any additional output parameters cm.Parameters.Add(param_ROUsageID);
cm.ExecuteNonQuery(); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// Save all values being returned from the Procedure {
_ROUsageID = (int)cm.Parameters["@newROUsageID"].Value; Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_ROUsageID = (int)cm.Parameters["@newROUsageID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.SQLInsert", GetHashCode());
@@ -792,11 +696,15 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID); cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int); SqlParameter param_ROUsageID = new SqlParameter("@newROUsageID", SqlDbType.Int)
param_ROUsageID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_ROUsageID); cm.Parameters.Add(param_ROUsageID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -841,35 +749,40 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.SQLUpdate", GetHashCode());
try try
{ {
if (_MyContent != null) _MyContent.Update(); _MyContent?.Update();
if (_MyRODb != null) _MyRODb.Update(); _MyRODb?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateRoUsage"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID); cm.CommandText = "updateRoUsage";
cm.Parameters.AddWithValue("@ContentID", ContentID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@ROID", _ROID); cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@ContentID", ContentID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ROID", _ROID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
cm.Parameters.AddWithValue("@RODbID", RODbID); cm.Parameters.AddWithValue("@UserID", _UserID);
// Output Calculated Columns cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@RODbID", RODbID);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -882,14 +795,17 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = RoUsage.Add(cn, ref _ROUsageID, _MyContent, _ROID, _Config, _DTS, _UserID, _MyRODb); if (IsNew)
else _LastChanged = RoUsage.Add(cn, ref _ROUsageID, _MyContent, _ROID, _Config, _DTS, _UserID, _MyRODb);
_LastChanged = RoUsage.Update(cn, ref _ROUsageID, _ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); else
_LastChanged = RoUsage.Update(cn, ref _ROUsageID, _ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID);
}
MarkOld(); MarkOld();
} }
} }
@@ -914,8 +830,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
cm.Parameters.AddWithValue("@RODbID", rODbID); cm.Parameters.AddWithValue("@RODbID", rODbID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1000,16 +918,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _ROUsageID; private readonly int _ROUsageID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int rOUsageID) => _ROUsageID = rOUsageID;
get { return _exists; }
}
public ExistsCommand(int rOUsageID)
{
_ROUsageID = rOUsageID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsage.DataPortal_Execute", GetHashCode());
@@ -1025,7 +937,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsRoUsage"; cm.CommandText = "existsRoUsage";
cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID); cm.Parameters.AddWithValue("@ROUsageID", _ROUsageID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -1039,7 +951,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
RoUsageExtension _RoUsageExtension = new RoUsageExtension(); readonly RoUsageExtension _RoUsageExtension = new RoUsageExtension();
[Serializable()] [Serializable()]
partial class RoUsageExtension : extensionBase partial class RoUsageExtension : extensionBase
{ {
@@ -1048,18 +960,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultContentID public virtual int DefaultContentID => 0;
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return 0; } public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1088,61 +991,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RoUsage) if (destType == typeof(string) && value is RoUsage usage)
{ {
// Return the ToString value // Return the ToString value
return ((RoUsage)value).ToString(); return usage.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create RoUsageExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class RoUsage
// {
// partial class RoUsageExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultContentID
// {
// get { return 0; }
// }
// 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, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class RoUsageInfo : ReadOnlyBase<RoUsageInfo>, IDisposable public partial class RoUsageInfo : ReadOnlyBase<RoUsageInfo>, IDisposable
{ {
public event RoUsageInfoEvent Changed; public event RoUsageInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<RoUsageInfo> _CacheList = new List<RoUsageInfo>(); private static List<RoUsageInfo> _CacheList = new List<RoUsageInfo>();
protected static void AddToCache(RoUsageInfo roUsageInfo) protected static void AddToCache(RoUsageInfo roUsageInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(roUsageInfo)) _CacheList.Remove(roUsageInfo); // In RemoveFromCache while (_CacheList.Contains(roUsageInfo)) _CacheList.Remove(roUsageInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<RoUsageInfo>> _CacheByPrimaryKey = new Dictionary<string, List<RoUsageInfo>>(); private static Dictionary<string, List<RoUsageInfo>> _CacheByPrimaryKey = new Dictionary<string, List<RoUsageInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected RoUsage _Editable; protected RoUsage _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _ROUsageID; private int _ROUsageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ROUsageID public int ROUsageID
@@ -175,32 +159,19 @@ namespace VEPROMS.CSLA.Library
return _MyRODb; return _MyRODb;
} }
} }
// CSLATODO: Replace base RoUsageInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current RoUsageInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check RoUsageInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check RoUsageInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current RoUsageInfo</returns> /// <returns>A Unique ID for the current RoUsageInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyRoUsageInfoUnique; // Absolutely Unique ID
{
return MyRoUsageInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _RoUsageInfoUnique = 0; private static int _RoUsageInfoUnique = 0;
private static int RoUsageInfoUnique private static int RoUsageInfoUnique => ++_RoUsageInfoUnique;
{ get { return ++_RoUsageInfoUnique; } } private readonly int _MyRoUsageInfoUnique = RoUsageInfoUnique;
private int _MyRoUsageInfoUnique = RoUsageInfoUnique; // Absolutely Unique ID - Info
public int MyRoUsageInfoUnique // Absolutely Unique ID - Info public int MyRoUsageInfoUnique => _MyRoUsageInfoUnique;
{ get { return _MyRoUsageInfoUnique; } }
protected RoUsageInfo() protected RoUsageInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -209,15 +180,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RoUsageInfo() ~RoUsageInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -234,10 +201,7 @@ namespace VEPROMS.CSLA.Library
if (listRoUsageInfo.Count == 0) // If there are no items left in the list if (listRoUsageInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(ROUsageID.ToString()); // remove the list _CacheByPrimaryKey.Remove(ROUsageID.ToString()); // remove the list
} }
public virtual RoUsage Get() public virtual RoUsage Get() => _Editable = RoUsage.Get(_ROUsageID);
{
return _Editable = RoUsage.Get(_ROUsageID);
}
public static void Refresh(RoUsage tmp) public static void Refresh(RoUsage tmp)
{ {
string key = tmp.ROUsageID.ToString(); string key = tmp.ROUsageID.ToString();
@@ -250,22 +214,22 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ContentID != tmp.ContentID) if (_ContentID != tmp.ContentID)
{ {
if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for old value MyContent?.RefreshContentRoUsages(); // Update List for old value
_ContentID = tmp.ContentID; // Update the value _ContentID = tmp.ContentID; // Update the value
} }
_MyContent = null; // Reset list so that the next line gets a new list _MyContent = null; // Reset list so that the next line gets a new list
if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for new value MyContent?.RefreshContentRoUsages(); // Update List for new value
_ROID = tmp.ROID; _ROID = tmp.ROID;
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
if (_RODbID != tmp.RODbID) if (_RODbID != tmp.RODbID)
{ {
if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for old value MyRODb?.RefreshRODbRoUsages(); // Update List for old value
_RODbID = tmp.RODbID; // Update the value _RODbID = tmp.RODbID; // Update the value
} }
_MyRODb = null; // Reset list so that the next line gets a new list _MyRODb = null; // Reset list so that the next line gets a new list
if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for new value MyRODb?.RefreshRODbRoUsages(); // Update List for new value
_RoUsageInfoExtension.Refresh(this); _RoUsageInfoExtension.Refresh(this);
OnChange();// raise an event OnChange();// raise an event
} }
@@ -285,11 +249,11 @@ namespace VEPROMS.CSLA.Library
_UserID = tmp.UserID; _UserID = tmp.UserID;
if (_RODbID != tmp.RODbID) if (_RODbID != tmp.RODbID)
{ {
if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for old value MyRODb?.RefreshRODbRoUsages(); // Update List for old value
_RODbID = tmp.RODbID; // Update the value _RODbID = tmp.RODbID; // Update the value
} }
_MyRODb = null; // Reset list so that the next line gets a new list _MyRODb = null; // Reset list so that the next line gets a new list
if (MyRODb != null) MyRODb.RefreshRODbRoUsages(); // Update List for new value MyRODb?.RefreshRODbRoUsages(); // Update List for new value
_RoUsageInfoExtension.Refresh(this); _RoUsageInfoExtension.Refresh(this);
OnChange();// raise an event OnChange();// raise an event
} }
@@ -305,11 +269,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ContentID != tmp.ContentID) if (_ContentID != tmp.ContentID)
{ {
if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for old value MyContent?.RefreshContentRoUsages(); // Update List for old value
_ContentID = tmp.ContentID; // Update the value _ContentID = tmp.ContentID; // Update the value
} }
_MyContent = null; // Reset list so that the next line gets a new list _MyContent = null; // Reset list so that the next line gets a new list
if (MyContent != null) MyContent.RefreshContentRoUsages(); // Update List for new value MyContent?.RefreshContentRoUsages(); // Update List for new value
_ROID = tmp.ROID; _ROID = tmp.ROID;
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
@@ -319,8 +283,6 @@ namespace VEPROMS.CSLA.Library
} }
public static RoUsageInfo Get(int rOUsageID) public static RoUsageInfo Get(int rOUsageID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a RoUsage");
try try
{ {
RoUsageInfo tmp = GetCachedByPrimaryKey(rOUsageID); RoUsageInfo tmp = GetCachedByPrimaryKey(rOUsageID);
@@ -359,13 +321,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _ROUsageID; private readonly int _ROUsageID;
public int ROUsageID public int ROUsageID => _ROUsageID;
{ get { return _ROUsageID; } } public PKCriteria(int rOUsageID) => _ROUsageID = rOUsageID;
public PKCriteria(int rOUsageID)
{
_ROUsageID = rOUsageID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -426,7 +384,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
RoUsageInfoExtension _RoUsageInfoExtension = new RoUsageInfoExtension(); readonly RoUsageInfoExtension _RoUsageInfoExtension = new RoUsageInfoExtension();
[Serializable()] [Serializable()]
partial class RoUsageInfoExtension : extensionBase { } partial class RoUsageInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -442,10 +400,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RoUsageInfo) if (destType == typeof(string) && value is RoUsageInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((RoUsageInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<RoUsageInfo> Items internal new IList<RoUsageInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (RoUsageInfo tmp in this) foreach (RoUsageInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~RoUsageInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RoUsageInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,15 +90,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on RoUsageInfoList.Get", ex); throw new DbCslaException("Error on RoUsageInfoList.Get", ex);
} }
} }
//public static RoUsageInfoList GetByFolder(FolderInfo fi)
//{
//}
public static RoUsageInfoList GetByDocVersion(DocVersionInfo dvi) public static RoUsageInfoList GetByDocVersion(DocVersionInfo dvi)
{ {
try try
{ {
//if (_RoUsageInfoList != null)
// return _RoUsageInfoList;
RoUsageInfoList tmp = DataPortal.Fetch<RoUsageInfoList>(new VersionIDCriteria(dvi.VersionID)); RoUsageInfoList tmp = DataPortal.Fetch<RoUsageInfoList>(new VersionIDCriteria(dvi.VersionID));
RoUsageInfo.AddList(tmp); RoUsageInfo.AddList(tmp);
tmp.AddEvents(); tmp.AddEvents();
@@ -121,8 +109,6 @@ namespace VEPROMS.CSLA.Library
{ {
try try
{ {
//if (_RoUsageInfoList != null)
// return _RoUsageInfoList;
RoUsageInfoList tmp = DataPortal.Fetch<RoUsageInfoList>(new ItemIDCriteria(pi.ItemID)); RoUsageInfoList tmp = DataPortal.Fetch<RoUsageInfoList>(new ItemIDCriteria(pi.ItemID));
RoUsageInfo.AddList(tmp); RoUsageInfo.AddList(tmp);
tmp.AddEvents(); tmp.AddEvents();
@@ -134,27 +120,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on RoUsageInfoList.Get", ex); throw new DbCslaException("Error on RoUsageInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all RoUsageInfo. /// Reset the list of all RoUsageInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _RoUsageInfoList = null;
{ public static RoUsageInfoList GetByContentID(int contentID)
_RoUsageInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static RoUsageInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<RoUsageInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on RoUsageInfoList.Get", ex);
// }
//}
public static RoUsageInfoList GetByContentID(int contentID)
{ {
try try
{ {
@@ -189,11 +160,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class VersionIDCriteria private class VersionIDCriteria
{ {
public VersionIDCriteria(int versionID) public VersionIDCriteria(int versionID) => _VersionID = versionID;
{ private int _VersionID;
_VersionID = versionID;
}
private int _VersionID;
public int VersionID public int VersionID
{ {
get { return _VersionID; } get { return _VersionID; }
@@ -202,7 +170,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(VersionIDCriteria criteria) private void DataPortal_Fetch(VersionIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -217,7 +185,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new RoUsageInfo(dr)); while (dr.Read()) Add(new RoUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -228,16 +196,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class ItemIDCriteria private class ItemIDCriteria
{ {
public ItemIDCriteria(int itemID) public ItemIDCriteria(int itemID) => _ItemID = itemID;
{ private int _ItemID;
_ItemID = itemID;
}
private int _ItemID;
public int ItemID public int ItemID
{ {
get { return _ItemID; } get { return _ItemID; }
@@ -246,7 +211,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(ItemIDCriteria criteria) private void DataPortal_Fetch(ItemIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -261,7 +226,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new RoUsageInfo(dr)); while (dr.Read()) Add(new RoUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -272,11 +237,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -290,7 +255,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new RoUsageInfo(dr)); while (dr.Read()) Add(new RoUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -301,16 +266,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class ContentIDCriteria private class ContentIDCriteria
{ {
public ContentIDCriteria(int contentID) public ContentIDCriteria(int contentID) => _ContentID = contentID;
{ private int _ContentID;
_ContentID = contentID;
}
private int _ContentID;
public int ContentID public int ContentID
{ {
get { return _ContentID; } get { return _ContentID; }
@@ -319,7 +281,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(ContentIDCriteria criteria) private void DataPortal_Fetch(ContentIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_FetchContentID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_FetchContentID", GetHashCode());
try try
{ {
@@ -334,7 +296,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new RoUsageInfo(dr)); while (dr.Read()) Add(new RoUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -345,16 +307,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_FetchContentID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_FetchContentID", ex);
throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class RODbIDCriteria private class RODbIDCriteria
{ {
public RODbIDCriteria(int rODbID) public RODbIDCriteria(int rODbID) => _RODbID = rODbID;
{ private int _RODbID;
_RODbID = rODbID;
}
private int _RODbID;
public int RODbID public int RODbID
{ {
get { return _RODbID; } get { return _RODbID; }
@@ -363,7 +322,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(RODbIDCriteria criteria) private void DataPortal_Fetch(RODbIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_FetchRODbID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RoUsageInfoList.DataPortal_FetchRODbID", GetHashCode());
try try
{ {
@@ -378,7 +337,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new RoUsageInfo(dr)); while (dr.Read()) Add(new RoUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -389,48 +348,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_FetchRODbID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("RoUsageInfoList.DataPortal_FetchRODbID", ex);
throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("RoUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
RoUsageInfoListPropertyDescriptor pd = new RoUsageInfoListPropertyDescriptor(this, i); RoUsageInfoListPropertyDescriptor pd = new RoUsageInfoListPropertyDescriptor(this, i);
@@ -447,7 +395,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class RoUsageInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class RoUsageInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private RoUsageInfo Item { get { return (RoUsageInfo)_Item; } }
public RoUsageInfoListPropertyDescriptor(RoUsageInfoList collection, int index) : base(collection, index) { ;} public RoUsageInfoListPropertyDescriptor(RoUsageInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -456,10 +403,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RoUsageInfoList) if (destType == typeof(string) && value is RoUsageInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((RoUsageInfoList)value).Items.Count.ToString() + " RoUsages"; return $"{list.Items.Count} RoUsages";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class RoleInfo : ReadOnlyBase<RoleInfo>, IDisposable public partial class RoleInfo : ReadOnlyBase<RoleInfo>, IDisposable
{ {
public event RoleInfoEvent Changed; public event RoleInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<RoleInfo> _CacheList = new List<RoleInfo>(); private static List<RoleInfo> _CacheList = new List<RoleInfo>();
protected static void AddToCache(RoleInfo roleInfo) protected static void AddToCache(RoleInfo roleInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(roleInfo)) _CacheList.Remove(roleInfo); // In RemoveFromCache while (_CacheList.Contains(roleInfo)) _CacheList.Remove(roleInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<RoleInfo>> _CacheByPrimaryKey = new Dictionary<string, List<RoleInfo>>(); private static Dictionary<string, List<RoleInfo>> _CacheByPrimaryKey = new Dictionary<string, List<RoleInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Role _Editable; protected Role _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _RID; private int _RID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int RID public int RID
@@ -207,32 +191,19 @@ namespace VEPROMS.CSLA.Library
foreach (RoleInfo tmp in _CacheByPrimaryKey[_RID.ToString()]) foreach (RoleInfo tmp in _CacheByPrimaryKey[_RID.ToString()])
tmp._RolePermissionCount = -1; // This will cause the data to be requeried tmp._RolePermissionCount = -1; // This will cause the data to be requeried
} }
// CSLATODO: Replace base RoleInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current RoleInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check RoleInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check RoleInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current RoleInfo</returns> /// <returns>A Unique ID for the current RoleInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyRoleInfoUnique; // Absolutely Unique ID
{
return MyRoleInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _RoleInfoUnique = 0; private static int _RoleInfoUnique = 0;
private static int RoleInfoUnique private static int RoleInfoUnique => ++_RoleInfoUnique;
{ get { return ++_RoleInfoUnique; } } private readonly int _MyRoleInfoUnique = RoleInfoUnique;
private int _MyRoleInfoUnique = RoleInfoUnique; // Absolutely Unique ID - Info
public int MyRoleInfoUnique // Absolutely Unique ID - Info public int MyRoleInfoUnique => _MyRoleInfoUnique;
{ get { return _MyRoleInfoUnique; } }
protected RoleInfo() protected RoleInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -241,15 +212,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RoleInfo() ~RoleInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -266,10 +233,7 @@ namespace VEPROMS.CSLA.Library
if (listRoleInfo.Count == 0) // If there are no items left in the list if (listRoleInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(RID.ToString()); // remove the list _CacheByPrimaryKey.Remove(RID.ToString()); // remove the list
} }
public virtual Role Get() public virtual Role Get() => _Editable = Role.Get(_RID);
{
return _Editable = Role.Get(_RID);
}
public static void Refresh(Role tmp) public static void Refresh(Role tmp)
{ {
string key = tmp.RID.ToString(); string key = tmp.RID.ToString();
@@ -289,8 +253,6 @@ namespace VEPROMS.CSLA.Library
} }
public static RoleInfo Get(int rid) public static RoleInfo Get(int rid)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Role");
try try
{ {
RoleInfo tmp = GetCachedByPrimaryKey(rid); RoleInfo tmp = GetCachedByPrimaryKey(rid);
@@ -329,13 +291,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _RID; private readonly int _RID;
public int RID public int RID => _RID;
{ get { return _RID; } } public PKCriteria(int rid) => _RID = rid;
public PKCriteria(int rid)
{
_RID = rid;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -396,7 +354,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
RoleInfoExtension _RoleInfoExtension = new RoleInfoExtension(); readonly RoleInfoExtension _RoleInfoExtension = new RoleInfoExtension();
[Serializable()] [Serializable()]
partial class RoleInfoExtension : extensionBase { } partial class RoleInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -412,10 +370,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RoleInfo) if (destType == typeof(string) && value is RoleInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((RoleInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<RoleInfo> Items internal new IList<RoleInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (RoleInfo tmp in this) foreach (RoleInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~RoleInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RoleInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on RoleInfoList.Get", ex); throw new DbCslaException("Error on RoleInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all RoleInfo. /// Reset the list of all RoleInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _RoleInfoList = null;
{ private RoleInfoList()
_RoleInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static RoleInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<RoleInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on RoleInfoList.Get", ex);
// }
//}
private RoleInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
@@ -149,35 +127,25 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return TypeDescriptor.GetEvents(this, true); }
public object GetPropertyOwner(PropertyDescriptor pd)
{ return this; }
/// <summary>
/// Called to get the properties of this type. Returns properties with certain
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); } { return GetProperties(); }
/// <summary> /// <summary>
/// Called to get the properties of this type. /// Called to get the properties of this type.
@@ -205,7 +173,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class RoleInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class RoleInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private RoleInfo Item { get { return (RoleInfo)_Item; } }
public RoleInfoListPropertyDescriptor(RoleInfoList collection, int index) : base(collection, index) { ;} public RoleInfoListPropertyDescriptor(RoleInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -214,10 +181,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RoleInfoList) if (destType == typeof(string) && value is RoleInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((RoleInfoList)value).Items.Count.ToString() + " Roles"; return $"{list.Items.Count} Roles";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _PID; private int _PID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int PID public int PID
@@ -260,35 +254,13 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current RolePermission</returns> /// <returns>A Unique ID for the current RolePermission</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyRolePermissionUnique; // Absolutely Unique ID
{ public override bool IsDirty => base.IsDirty;
return MyRolePermissionUnique; // Absolutely Unique ID [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
} public bool IsDirtyList(List<object> list) => base.IsDirty;
// CSLATODO: Replace base RolePermission.ToString function as necessary public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
/// <summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
/// Overrides Base ToString public bool IsValidList(List<object> list) => (IsNew && !IsDirty) || base.IsValid;
/// </summary>
/// <returns>A string representation of current RolePermission</returns>
//public override string ToString()
//{
// return base.ToString();
//}
public override bool IsDirty
{
get { return base.IsDirty; }
}
public bool IsDirtyList(List<object> list)
{
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -316,8 +288,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -362,86 +334,22 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(PID, "<Role(s)>");
//AuthorizationRules.AllowRead(PermLevel, "<Role(s)>");
//AuthorizationRules.AllowWrite(PermLevel, "<Role(s)>");
//AuthorizationRules.AllowRead(VersionType, "<Role(s)>");
//AuthorizationRules.AllowWrite(VersionType, "<Role(s)>");
//AuthorizationRules.AllowRead(PermValue, "<Role(s)>");
//AuthorizationRules.AllowWrite(PermValue, "<Role(s)>");
//AuthorizationRules.AllowRead(PermAD, "<Role(s)>");
//AuthorizationRules.AllowWrite(PermAD, "<Role(s)>");
//AuthorizationRules.AllowRead(StartDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(StartDate, "<Role(s)>");
//AuthorizationRules.AllowRead(EndDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(EndDate, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UsrID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UsrID, "<Role(s)>");
}
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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _RolePermissionUnique = 0; private static int _RolePermissionUnique = 0;
private static int RolePermissionUnique private static int RolePermissionUnique => ++_RolePermissionUnique;
{ get { return ++_RolePermissionUnique; } } private readonly int _MyRolePermissionUnique = RolePermissionUnique;
private int _MyRolePermissionUnique = RolePermissionUnique; // Absolutely Unique ID - Editable FK
public int MyRolePermissionUnique // Absolutely Unique ID - Editable FK public int MyRolePermissionUnique => _MyRolePermissionUnique;
{ get { return _MyRolePermissionUnique; } } internal static RolePermission New(int permLevel, int versionType, int permValue) => new RolePermission(permLevel, versionType, permValue);
internal static RolePermission New(int permLevel, int versionType, int permValue) internal static RolePermission Get(SafeDataReader dr) => new RolePermission(dr);
{
return new RolePermission(permLevel, versionType, permValue);
}
internal static RolePermission Get(SafeDataReader dr)
{
return new RolePermission(dr);
}
public RolePermission() public RolePermission()
{ {
MarkAsChild(); MarkAsChild();
@@ -475,15 +383,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RolePermission() ~RolePermission()
{ {
_CountFinalized++; _CountFinalized++;
@@ -523,33 +427,43 @@ namespace VEPROMS.CSLA.Library
internal void Insert(Role myRole) internal void Insert(Role myRole)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Permission.Add(cn, ref _PID, myRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); {
_LastChanged = Permission.Add(cn, ref _PID, myRole, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID);
}
MarkOld(); MarkOld();
} }
internal void Update(Role myRole) internal void Update(Role myRole)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Permission.Update(cn, ref _PID, myRole.RID, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); {
_LastChanged = Permission.Update(cn, ref _PID, myRole.RID, _PermLevel, _VersionType, _PermValue, _PermAD, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(Role myRole) internal void DeleteSelf(Role myRole)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
Permission.Remove(cn, _PID); {
Permission.Remove(cn, _PID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
RolePermissionExtension _RolePermissionExtension = new RolePermissionExtension(); readonly RolePermissionExtension _RolePermissionExtension = new RolePermissionExtension();
[Serializable()] [Serializable()]
partial class RolePermissionExtension : extensionBase partial class RolePermissionExtension : extensionBase
{ {
@@ -558,22 +472,10 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultPermAD public virtual int DefaultPermAD => 0;
{ public virtual string DefaultStartDate => DateTime.Now.ToShortDateString();
get { return 0; } public virtual DateTime DefaultDTS => DateTime.Now;
} public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID;
public virtual string DefaultStartDate
{
get { return DateTime.Now.ToShortDateString(); }
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUsrID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -602,65 +504,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RolePermission) if (destType == typeof(string) && value is RolePermission permission)
{ {
// Return the ToString value // Return the ToString value
return ((RolePermission)value).ToString(); return permission.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create RolePermissionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class RolePermission
// {
// partial class RolePermissionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultPermAD
// {
// get { return 0; }
// }
// public virtual SmartDate DefaultStartDate
// {
// get { return DateTime.Now.ToShortDateString(); }
// }
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUsrID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public RolePermission this[Permission myPermission]
}
// One To Many
public RolePermission this[Permission myPermission]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<RolePermission> Items public new System.Collections.Generic.IList<RolePermission> Items => base.Items;
{ public RolePermission GetItem(Permission myPermission)
get { return base.Items; }
}
public RolePermission GetItem(Permission myPermission)
{ {
foreach (RolePermission permission in this) foreach (RolePermission permission in this)
if (permission.PID == myPermission.PID) if (permission.PID == myPermission.PID)
@@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library
public RolePermission Add(int permLevel, int versionType, int permValue) // One to Many public RolePermission Add(int permLevel, int versionType, int permValue) // One to Many
{ {
RolePermission permission = RolePermission.New(permLevel, versionType, permValue); RolePermission permission = RolePermission.New(permLevel, versionType, permValue);
this.Add(permission); Add(permission);
return permission; return permission;
} }
public void Remove(Permission myPermission) public void Remove(Permission myPermission)
@@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (RolePermission child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (RolePermission child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static RolePermissions New() internal static RolePermissions New() => new RolePermissions();
{ internal static RolePermissions Get(SafeDataReader dr) => new RolePermissions(dr);
return new RolePermissions(); public static RolePermissions GetByRID(int rid)
}
internal static RolePermissions Get(SafeDataReader dr)
{
return new RolePermissions(dr);
}
public static RolePermissions GetByRID(int rid)
{ {
try try
{ {
@@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on RolePermissions.GetByRID", ex); throw new DbCslaException("Error on RolePermissions.GetByRID", ex);
} }
} }
private RolePermissions() private RolePermissions() => MarkAsChild();
{ internal RolePermissions(SafeDataReader dr)
MarkAsChild();
}
internal RolePermissions(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~RolePermissions()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~RolePermissions()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(RolePermission.Get(dr)); Add(RolePermission.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class RIDCriteria private class RIDCriteria
{ {
public RIDCriteria(int rid) public RIDCriteria(int rid) => _RID = rid;
{ private int _RID;
_RID = rid;
}
private int _RID;
public int RID public int RID
{ {
get { return _RID; } get { return _RID; }
@@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(RIDCriteria criteria) private void DataPortal_Fetch(RIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RolePermissions.DataPortal_FetchRID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] RolePermissions.DataPortal_FetchRID", GetHashCode());
try try
{ {
@@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new RolePermission(dr)); while (dr.Read()) Add(new RolePermission(dr));
} }
} }
} }
@@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("RolePermissions.DataPortal_FetchRID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("RolePermissions.DataPortal_FetchRID", ex);
throw new DbCslaException("RolePermissions.DataPortal_Fetch", ex); throw new DbCslaException("RolePermissions.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(Role role) internal void Update(Role role)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
RolePermissionsPropertyDescriptor pd = new RolePermissionsPropertyDescriptor(this, i); RolePermissionsPropertyDescriptor pd = new RolePermissionsPropertyDescriptor(this, i);
@@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class RolePermissionsPropertyDescriptor : vlnListPropertyDescriptor public partial class RolePermissionsPropertyDescriptor : vlnListPropertyDescriptor
{ {
private RolePermission Item { get { return (RolePermission)_Item; } }
public RolePermissionsPropertyDescriptor(RolePermissions collection, int index) : base(collection, index) { ;} public RolePermissionsPropertyDescriptor(RolePermissions collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is RolePermissions) if (destType == typeof(string) && value is RolePermissions permissions)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((RolePermissions)value).Items.Count.ToString() + " Permissions"; return $"{permissions.Items.Count} Permissions";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+116 -272
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshSessions.Add(this); refreshSessions.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshSessions = new List<Session>();
{
_RefreshSessions = new List<Session>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Session> _CacheList = new List<Session>(); private static List<Session> _CacheList = new List<Session>();
protected static void AddToCache(Session session) protected static void AddToCache(Session session)
{ {
@@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(session)) _CacheList.Remove(session); // In RemoveFromCache while (_CacheList.Contains(session)) _CacheList.Remove(session); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Session>> _CacheByPrimaryKey = new Dictionary<string, List<Session>>(); private static Dictionary<string, List<Session>> _CacheByPrimaryKey = new Dictionary<string, List<Session>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextSessionID = -1; private static int _nextSessionID = -1;
public static int NextSessionID public static int NextSessionID => _nextSessionID--;
{
get { return _nextSessionID--; }
}
private int _SessionID; private int _SessionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int SessionID public int SessionID
@@ -220,40 +211,14 @@ namespace VEPROMS.CSLA.Library
} }
} }
} }
public override bool IsDirty public override bool IsDirty => base.IsDirty;
{ public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
get { return base.IsDirty; }
}
public bool IsDirtyList(List<object> list)
{
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
// CSLATODO: Replace base Session.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Session</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Session.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Session.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Session</returns> /// <returns>A Unique ID for the current Session</returns>
protected override object GetIdValue() protected override object GetIdValue() => MySessionUnique; // Absolutely Unique ID
{
return MySessionUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -281,8 +246,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -306,35 +271,11 @@ namespace VEPROMS.CSLA.Library
_SessionExtension.AddInstanceValidationRules(ValidationRules); _SessionExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(SessionID, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(DTSDtart, "<Role(s)>");
//AuthorizationRules.AllowRead(DTSEnd, "<Role(s)>");
//AuthorizationRules.AllowRead(DTSActivity, "<Role(s)>");
//AuthorizationRules.AllowRead(MachineName, "<Role(s)>");
//AuthorizationRules.AllowRead(ProcessID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTSDtart, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTSEnd, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTSActivity, "<Role(s)>");
//AuthorizationRules.AllowWrite(MachineName, "<Role(s)>");
//AuthorizationRules.AllowWrite(ProcessID, "<Role(s)>");
_SessionExtension.AddAuthorizationRules(AuthorizationRules); _SessionExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -342,42 +283,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_SessionExtension.AddInstanceAuthorizationRules(AuthorizationRules); _SessionExtension.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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _SessionUnique = 0; private static int _SessionUnique = 0;
protected static int SessionUnique protected static int SessionUnique => ++_SessionUnique;
{ get { return ++_SessionUnique; } } private readonly int _MySessionUnique = SessionUnique;
private int _MySessionUnique = SessionUnique; // Absolutely Unique ID - Editable
public int MySessionUnique // Absolutely Unique ID - Editable public int MySessionUnique => _MySessionUnique;
{ get { return _MySessionUnique; } }
protected Session() protected Session()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -386,15 +299,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Session() ~Session()
{ {
_CountFinalized++; _CountFinalized++;
@@ -419,8 +328,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Session New() public static Session New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Session");
try try
{ {
return DataPortal.Create<Session>(); return DataPortal.Create<Session>();
@@ -490,8 +397,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Session Get(int sessionID) public static Session Get(int sessionID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Session");
try try
{ {
Session tmp = GetCachedByPrimaryKey(sessionID); Session tmp = GetCachedByPrimaryKey(sessionID);
@@ -512,19 +417,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on Session.Get", ex); throw new DbCslaException("Error on Session.Get", ex);
} }
} }
public static Session Get(SafeDataReader dr) public static Session Get(SafeDataReader dr) => dr.Read() ? new Session(dr) : null;
{ internal Session(SafeDataReader dr) => ReadData(dr);
if (dr.Read()) return new Session(dr);
return null;
}
internal Session(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int sessionID) public static void Delete(int sessionID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Session");
try try
{ {
DataPortal.Delete(new PKCriteria(sessionID)); DataPortal.Delete(new PKCriteria(sessionID));
@@ -536,12 +432,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Session Save() public override Session Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Session");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Session");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Session");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -561,13 +451,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _SessionID; private readonly int _SessionID;
public int SessionID public int SessionID => _SessionID;
{ get { return _SessionID; } } public PKCriteria(int sessionID) => _SessionID = sessionID;
public PKCriteria(int sessionID)
{
_SessionID = sessionID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -667,35 +553,42 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addSession"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@UserID", _UserID); cm.CommandText = "addSession";
if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart); // Input All Fields - Except Calculated Columns
if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd); cm.Parameters.AddWithValue("@UserID", _UserID);
if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity); if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart);
cm.Parameters.AddWithValue("@MachineName", _MachineName); if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd);
cm.Parameters.AddWithValue("@ProcessID", _ProcessID); if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity);
// Output Calculated Columns cm.Parameters.AddWithValue("@MachineName", _MachineName);
SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int); cm.Parameters.AddWithValue("@ProcessID", _ProcessID);
param_SessionID.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_SessionID); SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int)
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); {
param_LastChanged.Direction = ParameterDirection.Output; Direction = ParameterDirection.Output
cm.Parameters.Add(param_LastChanged); };
// CSLATODO: Define any additional output parameters cm.Parameters.Add(param_SessionID);
cm.ExecuteNonQuery(); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// Save all values being returned from the Procedure {
_SessionID = (int)cm.Parameters["@newSessionID"].Value; Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_SessionID = (int)cm.Parameters["@newSessionID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.SQLInsert", GetHashCode());
@@ -726,11 +619,15 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@MachineName", machineName); cm.Parameters.AddWithValue("@MachineName", machineName);
cm.Parameters.AddWithValue("@ProcessID", processID); cm.Parameters.AddWithValue("@ProcessID", processID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int); SqlParameter param_SessionID = new SqlParameter("@newSessionID", SqlDbType.Int)
param_SessionID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_SessionID); cm.Parameters.Add(param_SessionID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -775,33 +672,38 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateSession"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@SessionID", _SessionID); cm.CommandText = "updateSession";
cm.Parameters.AddWithValue("@UserID", _UserID); // All Fields including Calculated Fields
if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart); cm.Parameters.AddWithValue("@SessionID", _SessionID);
if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd); cm.Parameters.AddWithValue("@UserID", _UserID);
if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity); if (_DTSDtart.Year >= 1753 && _DTSDtart.Year <= 9999) cm.Parameters.AddWithValue("@DTSDtart", _DTSDtart);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTSEnd != null && ((DateTime)_DTSEnd).Year >= 1753 && ((DateTime)_DTSEnd).Year <= 9999) cm.Parameters.AddWithValue("@DTSEnd", _DTSEnd);
cm.Parameters.AddWithValue("@MachineName", _MachineName); if (_DTSActivity.Year >= 1753 && _DTSActivity.Year <= 9999) cm.Parameters.AddWithValue("@DTSActivity", _DTSActivity);
cm.Parameters.AddWithValue("@ProcessID", _ProcessID); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
// Output Calculated Columns cm.Parameters.AddWithValue("@MachineName", _MachineName);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@ProcessID", _ProcessID);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -814,14 +716,17 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = Session.Add(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, _MachineName, _ProcessID); if (IsNew)
else _LastChanged = Session.Add(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, _MachineName, _ProcessID);
_LastChanged = Session.Update(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, ref _LastChanged, _MachineName, _ProcessID); else
_LastChanged = Session.Update(cn, ref _SessionID, _UserID, _DTSDtart, _DTSEnd, _DTSActivity, ref _LastChanged, _MachineName, _ProcessID);
}
MarkOld(); MarkOld();
} }
} }
@@ -846,8 +751,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@MachineName", machineName); cm.Parameters.AddWithValue("@MachineName", machineName);
cm.Parameters.AddWithValue("@ProcessID", processID); cm.Parameters.AddWithValue("@ProcessID", processID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -932,16 +839,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _SessionID; private readonly int _SessionID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int sessionID) => _SessionID = sessionID;
get { return _exists; }
}
public ExistsCommand(int sessionID)
{
_SessionID = sessionID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Session.DataPortal_Execute", GetHashCode());
@@ -957,7 +858,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsSession"; cm.CommandText = "existsSession";
cm.Parameters.AddWithValue("@SessionID", _SessionID); cm.Parameters.AddWithValue("@SessionID", _SessionID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -971,7 +872,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
SessionExtension _SessionExtension = new SessionExtension(); readonly SessionExtension _SessionExtension = new SessionExtension();
[Serializable()] [Serializable()]
partial class SessionExtension : extensionBase partial class SessionExtension : extensionBase
{ {
@@ -980,18 +881,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual string DefaultUserID public virtual string DefaultUserID => Environment.UserName.ToUpper();
{ public virtual DateTime DefaultDTSDtart => DateTime.Now;
get { return Environment.UserName.ToUpper(); } public virtual DateTime DefaultDTSActivity => DateTime.Now;
}
public virtual DateTime DefaultDTSDtart
{
get { return DateTime.Now; }
}
public virtual DateTime DefaultDTSActivity
{
get { return DateTime.Now; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1020,61 +912,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Session) if (destType == typeof(string) && value is Session mysession)
{ {
// Return the ToString value // Return the ToString value
return ((Session)value).ToString(); return mysession.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create SessionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Session
// {
// partial class SessionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public virtual DateTime DefaultDTSDtart
// {
// get { return DateTime.Now; }
// }
// public virtual DateTime DefaultDTSActivity
// {
// get { return DateTime.Now; }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class SessionInfo : ReadOnlyBase<SessionInfo>, IDisposable public partial class SessionInfo : ReadOnlyBase<SessionInfo>, IDisposable
{ {
public event SessionInfoEvent Changed; public event SessionInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<SessionInfo> _CacheList = new List<SessionInfo>(); private static List<SessionInfo> _CacheList = new List<SessionInfo>();
protected static void AddToCache(SessionInfo sessionInfo) protected static void AddToCache(SessionInfo sessionInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(sessionInfo)) _CacheList.Remove(sessionInfo); // In RemoveFromCache while (_CacheList.Contains(sessionInfo)) _CacheList.Remove(sessionInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<SessionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<SessionInfo>>(); private static Dictionary<string, List<SessionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<SessionInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Session _Editable; protected Session _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _SessionID; private int _SessionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int SessionID public int SessionID
@@ -153,32 +137,19 @@ namespace VEPROMS.CSLA.Library
return _ProcessID; return _ProcessID;
} }
} }
// CSLATODO: Replace base SessionInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current SessionInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check SessionInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check SessionInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current SessionInfo</returns> /// <returns>A Unique ID for the current SessionInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MySessionInfoUnique; // Absolutely Unique ID
{
return MySessionInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _SessionInfoUnique = 0; private static int _SessionInfoUnique = 0;
private static int SessionInfoUnique private static int SessionInfoUnique => ++_SessionInfoUnique;
{ get { return ++_SessionInfoUnique; } } private readonly int _MySessionInfoUnique = SessionInfoUnique;
private int _MySessionInfoUnique = SessionInfoUnique; // Absolutely Unique ID - Info
public int MySessionInfoUnique // Absolutely Unique ID - Info public int MySessionInfoUnique => _MySessionInfoUnique;
{ get { return _MySessionInfoUnique; } }
protected SessionInfo() protected SessionInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -187,15 +158,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~SessionInfo() ~SessionInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -212,10 +179,7 @@ namespace VEPROMS.CSLA.Library
if (listSessionInfo.Count == 0) // If there are no items left in the list if (listSessionInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(SessionID.ToString()); // remove the list _CacheByPrimaryKey.Remove(SessionID.ToString()); // remove the list
} }
public virtual Session Get() public virtual Session Get() => _Editable = Session.Get(_SessionID);
{
return _Editable = Session.Get(_SessionID);
}
public static void Refresh(Session tmp) public static void Refresh(Session tmp)
{ {
string key = tmp.SessionID.ToString(); string key = tmp.SessionID.ToString();
@@ -237,8 +201,6 @@ namespace VEPROMS.CSLA.Library
} }
public static SessionInfo Get(int sessionID) public static SessionInfo Get(int sessionID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Session");
try try
{ {
SessionInfo tmp = GetCachedByPrimaryKey(sessionID); SessionInfo tmp = GetCachedByPrimaryKey(sessionID);
@@ -277,13 +239,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _SessionID; private readonly int _SessionID;
public int SessionID public int SessionID => _SessionID;
{ get { return _SessionID; } } public PKCriteria(int sessionID) => _SessionID = sessionID;
public PKCriteria(int sessionID)
{
_SessionID = sessionID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -346,7 +304,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
SessionInfoExtension _SessionInfoExtension = new SessionInfoExtension(); readonly SessionInfoExtension _SessionInfoExtension = new SessionInfoExtension();
[Serializable()] [Serializable()]
partial class SessionInfoExtension : extensionBase { } partial class SessionInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -362,10 +320,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is SessionInfo) if (destType == typeof(string) && value is SessionInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((SessionInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<SessionInfo> Items internal new IList<SessionInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (SessionInfo tmp in this) foreach (SessionInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~SessionInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~SessionInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on SessionInfoList.Get", ex); throw new DbCslaException("Error on SessionInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all SessionInfo. /// Reset the list of all SessionInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _SessionInfoList = null;
{ private SessionInfoList()
_SessionInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static SessionInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<SessionInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on SessionInfoList.Get", ex);
// }
//}
private SessionInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] SessionInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new SessionInfo(dr)); while (dr.Read()) Add(new SessionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("SessionInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("SessionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("SessionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
SessionInfoListPropertyDescriptor pd = new SessionInfoListPropertyDescriptor(this, i); SessionInfoListPropertyDescriptor pd = new SessionInfoListPropertyDescriptor(this, i);
@@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class SessionInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class SessionInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private SessionInfo Item { get { return (SessionInfo)_Item; } }
public SessionInfoListPropertyDescriptor(SessionInfoList collection, int index) : base(collection, index) { ;} public SessionInfoListPropertyDescriptor(SessionInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is SessionInfoList) if (destType == typeof(string) && value is SessionInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((SessionInfoList)value).Items.Count.ToString() + " Sessions"; return $"{list.Items.Count} Sessions";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+123 -283
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -82,6 +80,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Stage> _CacheList = new List<Stage>(); private static List<Stage> _CacheList = new List<Stage>();
protected static void AddToCache(Stage stage) protected static void AddToCache(Stage stage)
{ {
@@ -91,6 +90,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(stage)) _CacheList.Remove(stage); // In RemoveFromCache while (_CacheList.Contains(stage)) _CacheList.Remove(stage); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Stage>> _CacheByPrimaryKey = new Dictionary<string, List<Stage>>(); private static Dictionary<string, List<Stage>> _CacheByPrimaryKey = new Dictionary<string, List<Stage>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -116,15 +116,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextStageID = -1; private static int _nextStageID = -1;
public static int NextStageID public static int NextStageID => _nextStageID--;
{
get { return _nextStageID--; }
}
private int _StageID; private int _StageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int StageID public int StageID
@@ -260,10 +254,7 @@ namespace VEPROMS.CSLA.Library
return _StageChecks; return _StageChecks;
} }
} }
public void Reset_StageChecks() public void Reset_StageChecks() => _StageCheckCount = -1;
{
_StageCheckCount = -1;
}
private int _StageVersionCount = 0; private int _StageVersionCount = 0;
/// <summary> /// <summary>
/// Count of StageVersions for this Stage /// Count of StageVersions for this Stage
@@ -295,10 +286,7 @@ namespace VEPROMS.CSLA.Library
return _StageVersions; return _StageVersions;
} }
} }
public void Reset_StageVersions() public void Reset_StageVersions() => _StageVersionCount = -1;
{
_StageVersionCount = -1;
}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -313,37 +301,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_StageChecks == null ? false : _StageChecks.IsDirtyList(list)) || (_StageVersions == null ? false : _StageVersions.IsDirtyList(list)); return base.IsDirty || (_StageChecks != null && _StageChecks.IsDirtyList(list)) || (_StageVersions != null && _StageVersions.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_StageChecks == null ? true : _StageChecks.IsValidList(list)) && (_StageVersions == null ? true : _StageVersions.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_StageChecks == null || _StageChecks.IsValidList(list)) && (_StageVersions == null || _StageVersions.IsValidList(list));
} }
// CSLATODO: Replace base Stage.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Stage</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Stage.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Stage.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Stage</returns> /// <returns>A Unique ID for the current Stage</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyStageUnique; // Absolutely Unique ID
{
return MyStageUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -373,8 +346,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -401,33 +374,11 @@ namespace VEPROMS.CSLA.Library
_StageExtension.AddInstanceValidationRules(ValidationRules); _StageExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(StageID, "<Role(s)>");
//AuthorizationRules.AllowRead(Name, "<Role(s)>");
//AuthorizationRules.AllowRead(Description, "<Role(s)>");
//AuthorizationRules.AllowRead(IsApproved, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(Name, "<Role(s)>");
//AuthorizationRules.AllowWrite(Description, "<Role(s)>");
//AuthorizationRules.AllowWrite(IsApproved, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_StageExtension.AddAuthorizationRules(AuthorizationRules); _StageExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -435,56 +386,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_StageExtension.AddInstanceAuthorizationRules(AuthorizationRules); _StageExtension.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;
}
/// <summary>
/// determines if related records (Foreign Keys) will keep this Item from being deleted
/// </summary>
public bool CanDelete
{
get
{
// Check to make sure that there are not any related records
int usedByCount = 0;
usedByCount += _StageCheckCount;
usedByCount += _StageVersionCount;
return (usedByCount == 0);
}
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _StageUnique = 0; private static int _StageUnique = 0;
protected static int StageUnique protected static int StageUnique => ++_StageUnique;
{ get { return ++_StageUnique; } } private readonly int _MyStageUnique = StageUnique;
private int _MyStageUnique = StageUnique; // Absolutely Unique ID - Editable
public int MyStageUnique // Absolutely Unique ID - Editable public int MyStageUnique => _MyStageUnique;
{ get { return _MyStageUnique; } }
protected Stage() protected Stage()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -493,15 +402,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Stage() ~Stage()
{ {
_CountFinalized++; _CountFinalized++;
@@ -526,8 +431,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Stage New() public static Stage New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Stage");
try try
{ {
return DataPortal.Create<Stage>(); return DataPortal.Create<Stage>();
@@ -594,8 +497,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Stage Get(int stageID) public static Stage Get(int stageID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Stage");
try try
{ {
Stage tmp = GetCachedByPrimaryKey(stageID); Stage tmp = GetCachedByPrimaryKey(stageID);
@@ -616,19 +517,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on Stage.Get", ex); throw new DbCslaException("Error on Stage.Get", ex);
} }
} }
public static Stage Get(SafeDataReader dr) public static Stage Get(SafeDataReader dr) => dr.Read() ? new Stage(dr) : null;
{ internal Stage(SafeDataReader dr) => ReadData(dr);
if (dr.Read()) return new Stage(dr);
return null;
}
internal Stage(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int stageID) public static void Delete(int stageID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Stage");
try try
{ {
DataPortal.Delete(new PKCriteria(stageID)); DataPortal.Delete(new PKCriteria(stageID));
@@ -640,12 +532,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Stage Save() public override Stage Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Stage");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Stage");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Stage");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -665,13 +551,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _StageID; private readonly int _StageID;
public int StageID public int StageID => _StageID;
{ get { return _StageID; } } public PKCriteria(int stageID) => _StageID = stageID;
public PKCriteria(int stageID)
{
_StageID = stageID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -778,38 +660,45 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addStage"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@Name", _Name); cm.CommandText = "addStage";
cm.Parameters.AddWithValue("@Description", _Description); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@IsApproved", _IsApproved); cm.Parameters.AddWithValue("@Name", _Name);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@Description", _Description);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@IsApproved", _IsApproved);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int); cm.Parameters.AddWithValue("@UserID", _UserID);
param_StageID.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_StageID); SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int)
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); {
param_LastChanged.Direction = ParameterDirection.Output; Direction = ParameterDirection.Output
cm.Parameters.Add(param_LastChanged); };
// CSLATODO: Define any additional output parameters cm.Parameters.Add(param_StageID);
cm.ExecuteNonQuery(); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// Save all values being returned from the Procedure {
_StageID = (int)cm.Parameters["@newStageID"].Value; Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_StageID = (int)cm.Parameters["@newStageID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_StageChecks != null) _StageChecks.Update(this); _StageChecks?.Update(this);
if (_StageVersions != null) _StageVersions.Update(this); _StageVersions?.Update(this);
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.SQLInsert", GetHashCode());
} }
catch (Exception ex) catch (Exception ex)
@@ -837,11 +726,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int); SqlParameter param_StageID = new SqlParameter("@newStageID", SqlDbType.Int)
param_StageID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_StageID); cm.Parameters.Add(param_StageID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -886,36 +779,41 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateStage"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@StageID", _StageID); cm.CommandText = "updateStage";
cm.Parameters.AddWithValue("@Name", _Name); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@Description", _Description); cm.Parameters.AddWithValue("@StageID", _StageID);
cm.Parameters.AddWithValue("@IsApproved", _IsApproved); cm.Parameters.AddWithValue("@Name", _Name);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@Description", _Description);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@IsApproved", _IsApproved);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
if (_StageChecks != null) _StageChecks.Update(this); _StageChecks?.Update(this);
if (_StageVersions != null) _StageVersions.Update(this); _StageVersions?.Update(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -926,18 +824,21 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = Stage.Add(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID); if (IsNew)
else _LastChanged = Stage.Add(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID);
_LastChanged = Stage.Update(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID, ref _LastChanged); else
_LastChanged = Stage.Update(cn, ref _StageID, _Name, _Description, _IsApproved, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
if (_StageChecks != null) _StageChecks.Update(this); _StageChecks?.Update(this);
if (_StageVersions != null) _StageVersions.Update(this); _StageVersions?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int stageID, string name, string description, int isApproved, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int stageID, string name, string description, int isApproved, DateTime dts, string userID, ref byte[] lastChanged)
@@ -959,8 +860,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1045,16 +948,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _StageID; private readonly int _StageID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int stageID) => _StageID = stageID;
get { return _exists; }
}
public ExistsCommand(int stageID)
{
_StageID = stageID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Stage.DataPortal_Execute", GetHashCode());
@@ -1070,7 +967,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsStage"; cm.CommandText = "existsStage";
cm.Parameters.AddWithValue("@StageID", _StageID); cm.Parameters.AddWithValue("@StageID", _StageID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -1084,7 +981,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
StageExtension _StageExtension = new StageExtension(); readonly StageExtension _StageExtension = new StageExtension();
[Serializable()] [Serializable()]
partial class StageExtension : extensionBase partial class StageExtension : extensionBase
{ {
@@ -1093,18 +990,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultIsApproved public virtual int DefaultIsApproved => 0;
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return 0; } public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1133,61 +1021,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Stage) if (destType == typeof(string) && value is Stage stage)
{ {
// Return the ToString value // Return the ToString value
return ((Stage)value).ToString(); return stage.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create StageExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Stage
// {
// partial class StageExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultIsApproved
// {
// get { return 0; }
// }
// 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, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _CheckID; private int _CheckID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int CheckID public int CheckID
@@ -222,19 +216,7 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current StageCheck</returns> /// <returns>A Unique ID for the current StageCheck</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyStageCheckUnique; // Absolutely Unique ID
{
return MyStageCheckUnique; // Absolutely Unique ID
}
// CSLATODO: Replace base StageCheck.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current StageCheck</returns>
//public override string ToString()
//{
// return base.ToString();
//}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -249,18 +231,15 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)); return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list));
} }
#endregion #endregion
#region ValidationRules #region ValidationRules
@@ -290,8 +269,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -316,76 +295,22 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(CheckID, "<Role(s)>");
//AuthorizationRules.AllowRead(RevisionID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RevisionID, "<Role(s)>");
//AuthorizationRules.AllowRead(ConsistencyChecks, "<Role(s)>");
//AuthorizationRules.AllowWrite(ConsistencyChecks, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
}
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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _StageCheckUnique = 0; private static int _StageCheckUnique = 0;
private static int StageCheckUnique private static int StageCheckUnique => ++_StageCheckUnique;
{ get { return ++_StageCheckUnique; } } private readonly int _MyStageCheckUnique = StageCheckUnique;
private int _MyStageCheckUnique = StageCheckUnique; // Absolutely Unique ID - Editable FK
public int MyStageCheckUnique // Absolutely Unique ID - Editable FK public int MyStageCheckUnique => _MyStageCheckUnique;
{ get { return _MyStageCheckUnique; } } internal static StageCheck New(Revision myRevision) => new StageCheck(myRevision);
internal static StageCheck New(Revision myRevision) internal static StageCheck Get(SafeDataReader dr) => new StageCheck(dr);
{
return new StageCheck(myRevision);
}
internal static StageCheck Get(SafeDataReader dr)
{
return new StageCheck(dr);
}
public StageCheck() public StageCheck()
{ {
MarkAsChild(); MarkAsChild();
@@ -413,15 +338,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~StageCheck() ~StageCheck()
{ {
_CountFinalized++; _CountFinalized++;
@@ -464,33 +385,43 @@ namespace VEPROMS.CSLA.Library
internal void Insert(Stage myStage) internal void Insert(Stage myStage)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, myStage, _ConsistencyChecks, _DTS, _UserID); {
_LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, myStage, _ConsistencyChecks, _DTS, _UserID);
}
MarkOld(); MarkOld();
} }
internal void Update(Stage myStage) internal void Update(Stage myStage)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Check.Update(cn, ref _CheckID, _RevisionID, myStage.StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged); {
_LastChanged = Check.Update(cn, ref _CheckID, _RevisionID, myStage.StageID, _ConsistencyChecks, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(Stage myStage) internal void DeleteSelf(Stage myStage)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
Check.Remove(cn, _CheckID); {
Check.Remove(cn, _CheckID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
StageCheckExtension _StageCheckExtension = new StageCheckExtension(); readonly StageCheckExtension _StageCheckExtension = new StageCheckExtension();
[Serializable()] [Serializable()]
partial class StageCheckExtension : extensionBase partial class StageCheckExtension : extensionBase
{ {
@@ -499,14 +430,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -535,57 +460,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is StageCheck) if (destType == typeof(string) && value is StageCheck check)
{ {
// Return the ToString value // Return the ToString value
return ((StageCheck)value).ToString(); return check.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create StageCheckExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class StageCheck
// {
// partial class StageCheckExtension : 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, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public StageCheck this[Check myCheck]
}
// One To Many
public StageCheck this[Check myCheck]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<StageCheck> Items public new System.Collections.Generic.IList<StageCheck> Items => base.Items;
{ public StageCheck GetItem(Check myCheck)
get { return base.Items; }
}
public StageCheck GetItem(Check myCheck)
{ {
foreach (StageCheck check in this) foreach (StageCheck check in this)
if (check.CheckID == myCheck.CheckID) if (check.CheckID == myCheck.CheckID)
@@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library
public StageCheck Add(Revision myRevision) // One to Many public StageCheck Add(Revision myRevision) // One to Many
{ {
StageCheck check = StageCheck.New(myRevision); StageCheck check = StageCheck.New(myRevision);
this.Add(check); Add(check);
return check; return check;
} }
public void Remove(Check myCheck) public void Remove(Check myCheck)
@@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (StageCheck child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (StageCheck child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static StageChecks New() internal static StageChecks New() => new StageChecks();
{ internal static StageChecks Get(SafeDataReader dr) => new StageChecks(dr);
return new StageChecks(); public static StageChecks GetByStageID(int stageID)
}
internal static StageChecks Get(SafeDataReader dr)
{
return new StageChecks(dr);
}
public static StageChecks GetByStageID(int stageID)
{ {
try try
{ {
@@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on StageChecks.GetByStageID", ex); throw new DbCslaException("Error on StageChecks.GetByStageID", ex);
} }
} }
private StageChecks() private StageChecks() => MarkAsChild();
{ internal StageChecks(SafeDataReader dr)
MarkAsChild();
}
internal StageChecks(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~StageChecks()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~StageChecks()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(StageCheck.Get(dr)); Add(StageCheck.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class StageIDCriteria private class StageIDCriteria
{ {
public StageIDCriteria(int stageID) public StageIDCriteria(int stageID) => _StageID = stageID;
{ private int _StageID;
_StageID = stageID;
}
private int _StageID;
public int StageID public int StageID
{ {
get { return _StageID; } get { return _StageID; }
@@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(StageIDCriteria criteria) private void DataPortal_Fetch(StageIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageChecks.DataPortal_FetchStageID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageChecks.DataPortal_FetchStageID", GetHashCode());
try try
{ {
@@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new StageCheck(dr)); while (dr.Read()) Add(new StageCheck(dr));
} }
} }
} }
@@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("StageChecks.DataPortal_FetchStageID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("StageChecks.DataPortal_FetchStageID", ex);
throw new DbCslaException("StageChecks.DataPortal_Fetch", ex); throw new DbCslaException("StageChecks.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(Stage stage) internal void Update(Stage stage)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
StageChecksPropertyDescriptor pd = new StageChecksPropertyDescriptor(this, i); StageChecksPropertyDescriptor pd = new StageChecksPropertyDescriptor(this, i);
@@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class StageChecksPropertyDescriptor : vlnListPropertyDescriptor public partial class StageChecksPropertyDescriptor : vlnListPropertyDescriptor
{ {
private StageCheck Item { get { return (StageCheck)_Item; } }
public StageChecksPropertyDescriptor(StageChecks collection, int index) : base(collection, index) { ;} public StageChecksPropertyDescriptor(StageChecks collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is StageChecks) if (destType == typeof(string) && value is StageChecks checks)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((StageChecks)value).Items.Count.ToString() + " Checks"; return $"{checks.Items.Count} Checks";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class StageInfo : ReadOnlyBase<StageInfo>, IDisposable public partial class StageInfo : ReadOnlyBase<StageInfo>, IDisposable
{ {
public event StageInfoEvent Changed; public event StageInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<StageInfo> _CacheList = new List<StageInfo>(); private static List<StageInfo> _CacheList = new List<StageInfo>();
protected static void AddToCache(StageInfo stageInfo) protected static void AddToCache(StageInfo stageInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(stageInfo)) _CacheList.Remove(stageInfo); // In RemoveFromCache while (_CacheList.Contains(stageInfo)) _CacheList.Remove(stageInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<StageInfo>> _CacheByPrimaryKey = new Dictionary<string, List<StageInfo>>(); private static Dictionary<string, List<StageInfo>> _CacheByPrimaryKey = new Dictionary<string, List<StageInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Stage _Editable; protected Stage _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _StageID; private int _StageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int StageID public int StageID
@@ -216,32 +200,19 @@ namespace VEPROMS.CSLA.Library
foreach (StageInfo tmp in _CacheByPrimaryKey[_StageID.ToString()]) foreach (StageInfo tmp in _CacheByPrimaryKey[_StageID.ToString()])
tmp._StageVersionCount = -1; // This will cause the data to be requeried tmp._StageVersionCount = -1; // This will cause the data to be requeried
} }
// CSLATODO: Replace base StageInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current StageInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check StageInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check StageInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current StageInfo</returns> /// <returns>A Unique ID for the current StageInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyStageInfoUnique; // Absolutely Unique ID
{
return MyStageInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _StageInfoUnique = 0; private static int _StageInfoUnique = 0;
private static int StageInfoUnique private static int StageInfoUnique => ++_StageInfoUnique;
{ get { return ++_StageInfoUnique; } } private readonly int _MyStageInfoUnique = StageInfoUnique;
private int _MyStageInfoUnique = StageInfoUnique; // Absolutely Unique ID - Info
public int MyStageInfoUnique // Absolutely Unique ID - Info public int MyStageInfoUnique => _MyStageInfoUnique;
{ get { return _MyStageInfoUnique; } }
protected StageInfo() protected StageInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -250,15 +221,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~StageInfo() ~StageInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -275,10 +242,7 @@ namespace VEPROMS.CSLA.Library
if (listStageInfo.Count == 0) // If there are no items left in the list if (listStageInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(StageID.ToString()); // remove the list _CacheByPrimaryKey.Remove(StageID.ToString()); // remove the list
} }
public virtual Stage Get() public virtual Stage Get() => _Editable = Stage.GetJustStage(_StageID);
{
return _Editable = Stage.GetJustStage(_StageID);
}
public static void Refresh(Stage tmp) public static void Refresh(Stage tmp)
{ {
string key = tmp.StageID.ToString(); string key = tmp.StageID.ToString();
@@ -299,8 +263,6 @@ namespace VEPROMS.CSLA.Library
} }
public static StageInfo Get(int stageID) public static StageInfo Get(int stageID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Stage");
try try
{ {
StageInfo tmp = GetCachedByPrimaryKey(stageID); StageInfo tmp = GetCachedByPrimaryKey(stageID);
@@ -339,13 +301,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _StageID; private readonly int _StageID;
public int StageID public int StageID => _StageID;
{ get { return _StageID; } } public PKCriteria(int stageID) => _StageID = stageID;
public PKCriteria(int stageID)
{
_StageID = stageID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -408,7 +366,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
StageInfoExtension _StageInfoExtension = new StageInfoExtension(); readonly StageInfoExtension _StageInfoExtension = new StageInfoExtension();
[Serializable()] [Serializable()]
partial class StageInfoExtension : extensionBase { } partial class StageInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -424,10 +382,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is StageInfo) if (destType == typeof(string) && value is StageInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((StageInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -27,14 +25,10 @@ namespace VEPROMS.CSLA.Library
[TypeConverter(typeof(StageInfoListConverter))] [TypeConverter(typeof(StageInfoListConverter))]
public partial class StageInfoList : ReadOnlyListBase<StageInfoList, StageInfo>, ICustomTypeDescriptor, IDisposable public partial class StageInfoList : ReadOnlyListBase<StageInfoList, StageInfo>, ICustomTypeDescriptor, IDisposable
{ {
public static event StageInfoListEvent ListChanged; public new static event StageInfoListEvent ListChanged;
private static void OnListChanged() private static void OnListChanged() => ListChanged?.Invoke();
{ #region Log4Net
if (ListChanged != null) private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
ListChanged();
}
#region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<StageInfo> Items internal new IList<StageInfo> Items
@@ -58,16 +52,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~StageInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~StageInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -105,26 +95,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on StageInfoList.Get", ex); throw new DbCslaException("Error on StageInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all StageInfo. /// Reset the list of all StageInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _StageInfoList = null;
{ private StageInfoList()
_StageInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static StageInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<StageInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on StageInfoList.Get", ex);
// }
//}
private StageInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
@@ -157,41 +132,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -213,7 +177,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class StageInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class StageInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private StageInfo Item { get { return (StageInfo)_Item; } }
public StageInfoListPropertyDescriptor(StageInfoList collection, int index) : base(collection, index) { ;} public StageInfoListPropertyDescriptor(StageInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -222,10 +185,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is StageInfoList) if (destType == typeof(string) && value is StageInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((StageInfoList)value).Items.Count.ToString() + " Stages"; return $"{list.Items.Count} Stages";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _VersionID; private int _VersionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int VersionID public int VersionID
@@ -257,19 +251,7 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current StageVersion</returns> /// <returns>A Unique ID for the current StageVersion</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyStageVersionUnique; // Absolutely Unique ID
{
return MyStageVersionUnique; // Absolutely Unique ID
}
// CSLATODO: Replace base StageVersion.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current StageVersion</returns>
//public override string ToString()
//{
// return base.ToString();
//}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -284,18 +266,15 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)); return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list));
} }
#endregion #endregion
#region ValidationRules #region ValidationRules
@@ -325,8 +304,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -348,78 +327,22 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(VersionID, "<Role(s)>");
//AuthorizationRules.AllowRead(RevisionID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RevisionID, "<Role(s)>");
//AuthorizationRules.AllowRead(PDF, "<Role(s)>");
//AuthorizationRules.AllowWrite(PDF, "<Role(s)>");
//AuthorizationRules.AllowRead(SummaryPDF, "<Role(s)>");
//AuthorizationRules.AllowWrite(SummaryPDF, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
}
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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _StageVersionUnique = 0; private static int _StageVersionUnique = 0;
private static int StageVersionUnique private static int StageVersionUnique => ++_StageVersionUnique;
{ get { return ++_StageVersionUnique; } } private readonly int _MyStageVersionUnique = StageVersionUnique;
private int _MyStageVersionUnique = StageVersionUnique; // Absolutely Unique ID - Editable FK
public int MyStageVersionUnique // Absolutely Unique ID - Editable FK public int MyStageVersionUnique => _MyStageVersionUnique;
{ get { return _MyStageVersionUnique; } } internal static StageVersion New(Revision myRevision, DateTime dts, string userID) => new StageVersion(myRevision, dts, userID);
internal static StageVersion New(Revision myRevision, DateTime dts, string userID) internal static StageVersion Get(SafeDataReader dr) => new StageVersion(dr);
{
return new StageVersion(myRevision, dts, userID);
}
internal static StageVersion Get(SafeDataReader dr)
{
return new StageVersion(dr);
}
public StageVersion() public StageVersion()
{ {
MarkAsChild(); MarkAsChild();
@@ -447,15 +370,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~StageVersion() ~StageVersion()
{ {
_CountFinalized++; _CountFinalized++;
@@ -499,33 +418,43 @@ namespace VEPROMS.CSLA.Library
internal void Insert(Stage myStage) internal void Insert(Stage myStage)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, myStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); {
_LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, myStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID);
}
MarkOld(); MarkOld();
} }
internal void Update(Stage myStage) internal void Update(Stage myStage)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, myStage.StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); {
_LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, myStage.StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(Stage myStage) internal void DeleteSelf(Stage myStage)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
Version.Remove(cn, _VersionID); {
Version.Remove(cn, _VersionID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
StageVersionExtension _StageVersionExtension = new StageVersionExtension(); readonly StageVersionExtension _StageVersionExtension = new StageVersionExtension();
[Serializable()] [Serializable()]
partial class StageVersionExtension : extensionBase partial class StageVersionExtension : extensionBase
{ {
@@ -562,49 +491,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is StageVersion) if (destType == typeof(string) && value is StageVersion version)
{ {
// Return the ToString value // Return the ToString value
return ((StageVersion)value).ToString(); return version.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create StageVersionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class StageVersion
// {
// partial class StageVersionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public StageVersion this[Version myVersion]
}
// One To Many
public StageVersion this[Version myVersion]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<StageVersion> Items public new System.Collections.Generic.IList<StageVersion> Items => base.Items;
{ public StageVersion GetItem(Version myVersion)
get { return base.Items; }
}
public StageVersion GetItem(Version myVersion)
{ {
foreach (StageVersion version in this) foreach (StageVersion version in this)
if (version.VersionID == myVersion.VersionID) if (version.VersionID == myVersion.VersionID)
@@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library
public StageVersion Add(Revision myRevision, DateTime dts, string userID) // One to Many public StageVersion Add(Revision myRevision, DateTime dts, string userID) // One to Many
{ {
StageVersion version = StageVersion.New(myRevision, dts, userID); StageVersion version = StageVersion.New(myRevision, dts, userID);
this.Add(version); Add(version);
return version; return version;
} }
public void Remove(Version myVersion) public void Remove(Version myVersion)
@@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (StageVersion child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (StageVersion child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static StageVersions New() internal static StageVersions New() => new StageVersions();
{ internal static StageVersions Get(SafeDataReader dr) => new StageVersions(dr);
return new StageVersions(); public static StageVersions GetByStageID(int stageID)
}
internal static StageVersions Get(SafeDataReader dr)
{
return new StageVersions(dr);
}
public static StageVersions GetByStageID(int stageID)
{ {
try try
{ {
@@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on StageVersions.GetByStageID", ex); throw new DbCslaException("Error on StageVersions.GetByStageID", ex);
} }
} }
private StageVersions() private StageVersions() => MarkAsChild();
{ internal StageVersions(SafeDataReader dr)
MarkAsChild();
}
internal StageVersions(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~StageVersions()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~StageVersions()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(StageVersion.Get(dr)); Add(StageVersion.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class StageIDCriteria private class StageIDCriteria
{ {
public StageIDCriteria(int stageID) public StageIDCriteria(int stageID) => _StageID = stageID;
{ private int _StageID;
_StageID = stageID;
}
private int _StageID;
public int StageID public int StageID
{ {
get { return _StageID; } get { return _StageID; }
@@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(StageIDCriteria criteria) private void DataPortal_Fetch(StageIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageVersions.DataPortal_FetchStageID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] StageVersions.DataPortal_FetchStageID", GetHashCode());
try try
{ {
@@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new StageVersion(dr)); while (dr.Read()) Add(new StageVersion(dr));
} }
} }
} }
@@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("StageVersions.DataPortal_FetchStageID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("StageVersions.DataPortal_FetchStageID", ex);
throw new DbCslaException("StageVersions.DataPortal_Fetch", ex); throw new DbCslaException("StageVersions.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(Stage stage) internal void Update(Stage stage)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
StageVersionsPropertyDescriptor pd = new StageVersionsPropertyDescriptor(this, i); StageVersionsPropertyDescriptor pd = new StageVersionsPropertyDescriptor(this, i);
@@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class StageVersionsPropertyDescriptor : vlnListPropertyDescriptor public partial class StageVersionsPropertyDescriptor : vlnListPropertyDescriptor
{ {
private StageVersion Item { get { return (StageVersion)_Item; } }
public StageVersionsPropertyDescriptor(StageVersions collection, int index) : base(collection, index) { ;} public StageVersionsPropertyDescriptor(StageVersions collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is StageVersions) if (destType == typeof(string) && value is StageVersions versions)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((StageVersions)value).Items.Count.ToString() + " Versions"; return $"{versions.Items.Count} Versions";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+131 -302
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshTransitions.Add(this); refreshTransitions.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshTransitions = new List<Transition>();
{
_RefreshTransitions = new List<Transition>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -59,6 +54,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Transition> _CacheList = new List<Transition>(); private static List<Transition> _CacheList = new List<Transition>();
protected static void AddToCache(Transition transition) protected static void AddToCache(Transition transition)
{ {
@@ -68,6 +64,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(transition)) _CacheList.Remove(transition); // In RemoveFromCache while (_CacheList.Contains(transition)) _CacheList.Remove(transition); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Transition>> _CacheByPrimaryKey = new Dictionary<string, List<Transition>>(); private static Dictionary<string, List<Transition>> _CacheByPrimaryKey = new Dictionary<string, List<Transition>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -93,15 +90,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextTransitionID = -1; private static int _nextTransitionID = -1;
public static int NextTransitionID public static int NextTransitionID => _nextTransitionID--;
{
get { return _nextTransitionID--; }
}
private int _TransitionID; private int _TransitionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int TransitionID public int TransitionID
@@ -341,37 +332,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyZTransition == null ? false : _MyZTransition.IsDirtyList(list)) || (_MyContent == null ? false : _MyContent.IsDirtyList(list)) || (_MyItemRangeID == null ? false : _MyItemRangeID.IsDirtyList(list)) || (_MyItemToID == null ? false : _MyItemToID.IsDirtyList(list)); return base.IsDirty || (_MyZTransition != null && _MyZTransition.IsDirtyList(list)) || (_MyContent != null && _MyContent.IsDirtyList(list)) || (_MyItemRangeID != null && _MyItemRangeID.IsDirtyList(list)) || (_MyItemToID != null && _MyItemToID.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyZTransition == null ? true : _MyZTransition.IsValidList(list)) && (_MyContent == null ? true : _MyContent.IsValidList(list)) && (_MyItemRangeID == null ? true : _MyItemRangeID.IsValidList(list)) && (_MyItemToID == null ? true : _MyItemToID.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyZTransition == null || _MyZTransition.IsValidList(list)) && (_MyContent == null || _MyContent.IsValidList(list)) && (_MyItemRangeID == null || _MyItemRangeID.IsValidList(list)) && (_MyItemToID == null || _MyItemToID.IsValidList(list));
} }
// CSLATODO: Replace base Transition.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Transition</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Transition.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Transition.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Transition</returns> /// <returns>A Unique ID for the current Transition</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyTransitionUnique; // Absolutely Unique ID
{
return MyTransitionUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -403,8 +379,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -456,39 +432,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(TransitionID, "<Role(s)>");
//AuthorizationRules.AllowRead(FromID, "<Role(s)>");
//AuthorizationRules.AllowRead(ToID, "<Role(s)>");
//AuthorizationRules.AllowRead(RangeID, "<Role(s)>");
//AuthorizationRules.AllowRead(IsRange, "<Role(s)>");
//AuthorizationRules.AllowRead(TranType, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(FromID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ToID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RangeID, "<Role(s)>");
//AuthorizationRules.AllowWrite(IsRange, "<Role(s)>");
//AuthorizationRules.AllowWrite(TranType, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_TransitionExtension.AddAuthorizationRules(AuthorizationRules); _TransitionExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -496,55 +444,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_TransitionExtension.AddInstanceAuthorizationRules(AuthorizationRules); _TransitionExtension.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;
}
/// <summary>
/// determines if related records (Foreign Keys) will keep this Item from being deleted
/// </summary>
public bool CanDelete
{
get
{
// Check to make sure that there are not any related records
int usedByCount = 0;
usedByCount += _TransitionZTransitionCount;
return (usedByCount == 0);
}
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _TransitionUnique = 0; private static int _TransitionUnique = 0;
protected static int TransitionUnique protected static int TransitionUnique => ++_TransitionUnique;
{ get { return ++_TransitionUnique; } } private readonly int _MyTransitionUnique = TransitionUnique;
private int _MyTransitionUnique = TransitionUnique; // Absolutely Unique ID - Editable
public int MyTransitionUnique // Absolutely Unique ID - Editable public int MyTransitionUnique => _MyTransitionUnique;
{ get { return _MyTransitionUnique; } }
protected Transition() protected Transition()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -553,15 +460,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Transition() ~Transition()
{ {
_CountFinalized++; _CountFinalized++;
@@ -579,12 +482,6 @@ namespace VEPROMS.CSLA.Library
} }
if (_MyContent != null) if (_MyContent != null)
_MyContent = null; _MyContent = null;
//if (_MyItemRangeID!=null)
// _MyItemRangeID = null;
//if (_MyItemToID != null)
// _MyItemToID = null;
//if (_MyItemRangeID != null)
// _MyItemRangeID = null;
} }
private void RemoveFromDictionaries() private void RemoveFromDictionaries()
{ {
@@ -599,8 +496,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Transition New() public static Transition New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Transition");
try try
{ {
return DataPortal.Create<Transition>(); return DataPortal.Create<Transition>();
@@ -674,8 +569,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Transition Get(int transitionID) public static Transition Get(int transitionID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Transition");
try try
{ {
Transition tmp = GetCachedByPrimaryKey(transitionID); Transition tmp = GetCachedByPrimaryKey(transitionID);
@@ -701,14 +594,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new Transition(dr); if (dr.Read()) return new Transition(dr);
return null; return null;
} }
internal Transition(SafeDataReader dr) internal Transition(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int transitionID) public static void Delete(int transitionID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Transition");
try try
{ {
DataPortal.Delete(new PKCriteria(transitionID)); DataPortal.Delete(new PKCriteria(transitionID));
@@ -720,12 +608,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Transition Save() public override Transition Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Transition");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Transition");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Transition");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -745,13 +627,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _TransitionID; private readonly int _TransitionID;
public int TransitionID public int TransitionID => _TransitionID;
{ get { return _TransitionID; } } public PKCriteria(int transitionID) => _TransitionID = transitionID;
public PKCriteria(int transitionID)
{
_TransitionID = transitionID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -858,43 +736,50 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyContent != null) _MyContent.Update(); _MyContent?.Update();
if (_MyItemRangeID != null) _MyItemRangeID.Update(); _MyItemRangeID?.Update();
if (_MyItemToID != null) _MyItemToID.Update(); _MyItemToID?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addTransition"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@FromID", FromID); cm.CommandText = "addTransition";
cm.Parameters.AddWithValue("@ToID", ToID); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@RangeID", RangeID); cm.Parameters.AddWithValue("@FromID", FromID);
cm.Parameters.AddWithValue("@IsRange", _IsRange); cm.Parameters.AddWithValue("@ToID", ToID);
cm.Parameters.AddWithValue("@TranType", _TranType); cm.Parameters.AddWithValue("@RangeID", RangeID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@IsRange", _IsRange);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@TranType", _TranType);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int); cm.Parameters.AddWithValue("@UserID", _UserID);
param_TransitionID.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_TransitionID); SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int)
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); {
param_LastChanged.Direction = ParameterDirection.Output; Direction = ParameterDirection.Output
cm.Parameters.Add(param_LastChanged); };
// CSLATODO: Define any additional output parameters cm.Parameters.Add(param_TransitionID);
cm.ExecuteNonQuery(); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// Save all values being returned from the Procedure {
_TransitionID = (int)cm.Parameters["@newTransitionID"].Value; Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_TransitionID = (int)cm.Parameters["@newTransitionID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyZTransition != null) _MyZTransition.Update(this); _MyZTransition?.Update(this);
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.SQLInsert", GetHashCode());
} }
catch (Exception ex) catch (Exception ex)
@@ -925,11 +810,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int); SqlParameter param_TransitionID = new SqlParameter("@newTransitionID", SqlDbType.Int)
param_TransitionID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_TransitionID); cm.Parameters.Add(param_TransitionID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -974,41 +863,46 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.SQLUpdate", GetHashCode());
try try
{ {
if (_MyContent != null) _MyContent.Update(); _MyContent?.Update();
if (_MyItemRangeID != null) _MyItemRangeID.Update(); _MyItemRangeID?.Update();
if (_MyItemToID != null) _MyItemToID.Update(); _MyItemToID?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateTransition"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@TransitionID", _TransitionID); cm.CommandText = "updateTransition";
cm.Parameters.AddWithValue("@FromID", FromID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@ToID", ToID); cm.Parameters.AddWithValue("@TransitionID", _TransitionID);
cm.Parameters.AddWithValue("@RangeID", RangeID); cm.Parameters.AddWithValue("@FromID", FromID);
cm.Parameters.AddWithValue("@IsRange", _IsRange); cm.Parameters.AddWithValue("@ToID", ToID);
cm.Parameters.AddWithValue("@TranType", _TranType); cm.Parameters.AddWithValue("@RangeID", RangeID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@IsRange", _IsRange);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@TranType", _TranType);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
if (_MyZTransition != null) _MyZTransition.Update(this); _MyZTransition?.Update(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1019,17 +913,20 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, _MyItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID); if (IsNew)
else _LastChanged = Transition.Add(cn, ref _TransitionID, _MyContent, _MyItemToID, _MyItemRangeID, _IsRange, _TranType, _Config, _DTS, _UserID);
_LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); else
_LastChanged = Transition.Update(cn, ref _TransitionID, _FromID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
if (_MyZTransition != null) _MyZTransition.Update(this); _MyZTransition?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int transitionID, int fromID, int toID, int rangeID, int isRange, int tranType, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int transitionID, int fromID, int toID, int rangeID, int isRange, int tranType, string config, DateTime dts, string userID, ref byte[] lastChanged)
@@ -1054,8 +951,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1140,16 +1039,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _TransitionID; private readonly int _TransitionID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int transitionID) => _TransitionID = transitionID;
get { return _exists; }
}
public ExistsCommand(int transitionID)
{
_TransitionID = transitionID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Transition.DataPortal_Execute", GetHashCode());
@@ -1165,7 +1058,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsTransition"; cm.CommandText = "existsTransition";
cm.Parameters.AddWithValue("@TransitionID", _TransitionID); cm.Parameters.AddWithValue("@TransitionID", _TransitionID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -1179,7 +1072,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
TransitionExtension _TransitionExtension = new TransitionExtension(); readonly TransitionExtension _TransitionExtension = new TransitionExtension();
[Serializable()] [Serializable()]
partial class TransitionExtension : extensionBase partial class TransitionExtension : extensionBase
{ {
@@ -1188,22 +1081,10 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultIsRange public virtual int DefaultIsRange => 0;
{ public virtual int DefaultTranType => 0;
get { return 0; } public virtual DateTime DefaultDTS => DateTime.Now;
} public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
public virtual int DefaultTranType
{
get { return 0; }
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1232,65 +1113,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Transition) if (destType == typeof(string) && value is Transition transs)
{ {
// Return the ToString value // Return the ToString value
return ((Transition)value).ToString(); return transs.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create TransitionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Transition
// {
// partial class TransitionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultIsRange
// {
// get { return 0; }
// }
// public virtual int DefaultTranType
// {
// get { return 0; }
// }
// 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, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class TransitionInfo : ReadOnlyBase<TransitionInfo>, IDisposable public partial class TransitionInfo : ReadOnlyBase<TransitionInfo>, IDisposable
{ {
public event TransitionInfoEvent Changed; public event TransitionInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<TransitionInfo> _CacheList = new List<TransitionInfo>(); private static List<TransitionInfo> _CacheList = new List<TransitionInfo>();
protected static void AddToCache(TransitionInfo transitionInfo) protected static void AddToCache(TransitionInfo transitionInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(transitionInfo)) _CacheList.Remove(transitionInfo); // In RemoveFromCache while (_CacheList.Contains(transitionInfo)) _CacheList.Remove(transitionInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<TransitionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<TransitionInfo>>(); private static Dictionary<string, List<TransitionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<TransitionInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Transition _Editable; protected Transition _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _TransitionID; private int _TransitionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int TransitionID public int TransitionID
@@ -237,32 +221,19 @@ namespace VEPROMS.CSLA.Library
return _MyZTransition; return _MyZTransition;
} }
} }
// CSLATODO: Replace base TransitionInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current TransitionInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check TransitionInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check TransitionInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current TransitionInfo</returns> /// <returns>A Unique ID for the current TransitionInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyTransitionInfoUnique; // Absolutely Unique ID
{
return MyTransitionInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _TransitionInfoUnique = 0; private static int _TransitionInfoUnique = 0;
private static int TransitionInfoUnique private static int TransitionInfoUnique => ++_TransitionInfoUnique;
{ get { return ++_TransitionInfoUnique; } } private readonly int _MyTransitionInfoUnique = TransitionInfoUnique;
private int _MyTransitionInfoUnique = TransitionInfoUnique; // Absolutely Unique ID - Info
public int MyTransitionInfoUnique // Absolutely Unique ID - Info public int MyTransitionInfoUnique => _MyTransitionInfoUnique;
{ get { return _MyTransitionInfoUnique; } }
protected TransitionInfo() protected TransitionInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -271,15 +242,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~TransitionInfo() ~TransitionInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -296,10 +263,7 @@ namespace VEPROMS.CSLA.Library
if (listTransitionInfo.Count == 0) // If there are no items left in the list if (listTransitionInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list _CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list
} }
public virtual Transition Get() public virtual Transition Get() => _Editable = Transition.Get(_TransitionID);
{
return _Editable = Transition.Get(_TransitionID);
}
public static void Refresh(Transition tmp) public static void Refresh(Transition tmp)
{ {
string key = tmp.TransitionID.ToString(); string key = tmp.TransitionID.ToString();
@@ -312,25 +276,25 @@ namespace VEPROMS.CSLA.Library
{ {
if (_FromID != tmp.FromID) if (_FromID != tmp.FromID)
{ {
if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value MyContent?.RefreshContentTransitions(); // Update List for old value
_FromID = tmp.FromID; // Update the value _FromID = tmp.FromID; // Update the value
} }
_MyContent = null; // Reset list so that the next line gets a new list _MyContent = null; // Reset list so that the next line gets a new list
if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value MyContent?.RefreshContentTransitions(); // Update List for new value
if (_ToID != tmp.ToID) if (_ToID != tmp.ToID)
{ {
if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value MyItemToID?.RefreshItemTransitions_ToID(); // Update List for old value
_ToID = tmp.ToID; // Update the value _ToID = tmp.ToID; // Update the value
} }
_MyItemToID = null; // Reset list so that the next line gets a new list _MyItemToID = null; // Reset list so that the next line gets a new list
if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value MyItemToID?.RefreshItemTransitions_ToID(); // Update List for new value
if (_RangeID != tmp.RangeID) if (_RangeID != tmp.RangeID)
{ {
if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for old value
_RangeID = tmp.RangeID; // Update the value _RangeID = tmp.RangeID; // Update the value
} }
_MyItemRangeID = null; // Reset list so that the next line gets a new list _MyItemRangeID = null; // Reset list so that the next line gets a new list
if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for new value
_IsRange = tmp.IsRange; _IsRange = tmp.IsRange;
_TranType = tmp.TranType; _TranType = tmp.TranType;
_Config = tmp.Config; _Config = tmp.Config;
@@ -352,18 +316,18 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ToID != tmp.ToID) if (_ToID != tmp.ToID)
{ {
if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value MyItemToID?.RefreshItemTransitions_ToID(); // Update List for old value
_ToID = tmp.ToID; // Update the value _ToID = tmp.ToID; // Update the value
} }
_MyItemToID = null; // Reset list so that the next line gets a new list _MyItemToID = null; // Reset list so that the next line gets a new list
if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value MyItemToID?.RefreshItemTransitions_ToID(); // Update List for new value
if (_RangeID != tmp.RangeID) if (_RangeID != tmp.RangeID)
{ {
if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for old value
_RangeID = tmp.RangeID; // Update the value _RangeID = tmp.RangeID; // Update the value
} }
_MyItemRangeID = null; // Reset list so that the next line gets a new list _MyItemRangeID = null; // Reset list so that the next line gets a new list
if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for new value
_IsRange = tmp.IsRange; _IsRange = tmp.IsRange;
_TranType = tmp.TranType; _TranType = tmp.TranType;
_Config = tmp.Config; _Config = tmp.Config;
@@ -385,18 +349,18 @@ namespace VEPROMS.CSLA.Library
{ {
if (_FromID != tmp.FromID) if (_FromID != tmp.FromID)
{ {
if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value MyContent?.RefreshContentTransitions(); // Update List for old value
_FromID = tmp.FromID; // Update the value _FromID = tmp.FromID; // Update the value
} }
_MyContent = null; // Reset list so that the next line gets a new list _MyContent = null; // Reset list so that the next line gets a new list
if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value MyContent?.RefreshContentTransitions(); // Update List for new value
if (_ToID != tmp.ToID) if (_ToID != tmp.ToID)
{ {
if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for old value MyItemToID?.RefreshItemTransitions_ToID(); // Update List for old value
_ToID = tmp.ToID; // Update the value _ToID = tmp.ToID; // Update the value
} }
_MyItemToID = null; // Reset list so that the next line gets a new list _MyItemToID = null; // Reset list so that the next line gets a new list
if (MyItemToID != null) MyItemToID.RefreshItemTransitions_ToID(); // Update List for new value MyItemToID?.RefreshItemTransitions_ToID(); // Update List for new value
_IsRange = tmp.IsRange; _IsRange = tmp.IsRange;
_TranType = tmp.TranType; _TranType = tmp.TranType;
_Config = tmp.Config; _Config = tmp.Config;
@@ -418,18 +382,18 @@ namespace VEPROMS.CSLA.Library
{ {
if (_FromID != tmp.FromID) if (_FromID != tmp.FromID)
{ {
if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for old value MyContent?.RefreshContentTransitions(); // Update List for old value
_FromID = tmp.FromID; // Update the value _FromID = tmp.FromID; // Update the value
} }
_MyContent = null; // Reset list so that the next line gets a new list _MyContent = null; // Reset list so that the next line gets a new list
if (MyContent != null) MyContent.RefreshContentTransitions(); // Update List for new value MyContent?.RefreshContentTransitions(); // Update List for new value
if (_RangeID != tmp.RangeID) if (_RangeID != tmp.RangeID)
{ {
if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for old value MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for old value
_RangeID = tmp.RangeID; // Update the value _RangeID = tmp.RangeID; // Update the value
} }
_MyItemRangeID = null; // Reset list so that the next line gets a new list _MyItemRangeID = null; // Reset list so that the next line gets a new list
if (MyItemRangeID != null) MyItemRangeID.RefreshItemTransitions_RangeID(); // Update List for new value MyItemRangeID?.RefreshItemTransitions_RangeID(); // Update List for new value
_IsRange = tmp.IsRange; _IsRange = tmp.IsRange;
_TranType = tmp.TranType; _TranType = tmp.TranType;
_Config = tmp.Config; _Config = tmp.Config;
@@ -441,8 +405,6 @@ namespace VEPROMS.CSLA.Library
} }
public static TransitionInfo Get(int transitionID) public static TransitionInfo Get(int transitionID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Transition");
try try
{ {
TransitionInfo tmp = GetCachedByPrimaryKey(transitionID); TransitionInfo tmp = GetCachedByPrimaryKey(transitionID);
@@ -481,13 +443,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _TransitionID; private readonly int _TransitionID;
public int TransitionID public int TransitionID => _TransitionID;
{ get { return _TransitionID; } } public PKCriteria(int transitionID) => _TransitionID = transitionID;
public PKCriteria(int transitionID)
{
_TransitionID = transitionID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -551,7 +509,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
TransitionInfoExtension _TransitionInfoExtension = new TransitionInfoExtension(); readonly TransitionInfoExtension _TransitionInfoExtension = new TransitionInfoExtension();
[Serializable()] [Serializable()]
partial class TransitionInfoExtension : extensionBase { } partial class TransitionInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -567,10 +525,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is TransitionInfo) if (destType == typeof(string) && value is TransitionInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((TransitionInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<TransitionInfo> Items internal new IList<TransitionInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (TransitionInfo tmp in this) foreach (TransitionInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~TransitionInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~TransitionInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on TransitionInfoList.Get", ex); throw new DbCslaException("Error on TransitionInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all TransitionInfo. /// Reset the list of all TransitionInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _TransitionInfoList = null;
{ public static TransitionInfoList GetByFromID(int fromID)
_TransitionInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static TransitionInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<TransitionInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on TransitionInfoList.Get", ex);
// }
//}
public static TransitionInfoList GetByFromID(int fromID)
{ {
try try
{ {
@@ -164,7 +142,7 @@ namespace VEPROMS.CSLA.Library
#region Data Access Portal #region Data Access Portal
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -178,7 +156,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new TransitionInfo(dr)); while (dr.Read()) Add(new TransitionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -189,16 +167,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class FromIDCriteria private class FromIDCriteria
{ {
public FromIDCriteria(int fromID) public FromIDCriteria(int fromID) => _FromID = fromID;
{ private int _FromID;
_FromID = fromID;
}
private int _FromID;
public int FromID public int FromID
{ {
get { return _FromID; } get { return _FromID; }
@@ -207,7 +182,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(FromIDCriteria criteria) private void DataPortal_Fetch(FromIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchFromID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchFromID", GetHashCode());
try try
{ {
@@ -222,7 +197,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new TransitionInfo(dr)); while (dr.Read()) Add(new TransitionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -233,16 +208,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchFromID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchFromID", ex);
throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class RangeIDCriteria private class RangeIDCriteria
{ {
public RangeIDCriteria(int rangeID) public RangeIDCriteria(int rangeID) => _RangeID = rangeID;
{ private int _RangeID;
_RangeID = rangeID;
}
private int _RangeID;
public int RangeID public int RangeID
{ {
get { return _RangeID; } get { return _RangeID; }
@@ -251,7 +223,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(RangeIDCriteria criteria) private void DataPortal_Fetch(RangeIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchRangeID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchRangeID", GetHashCode());
try try
{ {
@@ -266,7 +238,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new TransitionInfo(dr)); while (dr.Read()) Add(new TransitionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -277,16 +249,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchRangeID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchRangeID", ex);
throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class ToIDCriteria private class ToIDCriteria
{ {
public ToIDCriteria(int toID) public ToIDCriteria(int toID) => _ToID = toID;
{ private int _ToID;
_ToID = toID;
}
private int _ToID;
public int ToID public int ToID
{ {
get { return _ToID; } get { return _ToID; }
@@ -295,7 +264,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(ToIDCriteria criteria) private void DataPortal_Fetch(ToIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchToID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] TransitionInfoList.DataPortal_FetchToID", GetHashCode());
try try
{ {
@@ -310,7 +279,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new TransitionInfo(dr)); while (dr.Read()) Add(new TransitionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -321,48 +290,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchToID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("TransitionInfoList.DataPortal_FetchToID", ex);
throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("TransitionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
TransitionInfoListPropertyDescriptor pd = new TransitionInfoListPropertyDescriptor(this, i); TransitionInfoListPropertyDescriptor pd = new TransitionInfoListPropertyDescriptor(this, i);
@@ -379,7 +337,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class TransitionInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class TransitionInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private TransitionInfo Item { get { return (TransitionInfo)_Item; } }
public TransitionInfoListPropertyDescriptor(TransitionInfoList collection, int index) : base(collection, index) { ;} public TransitionInfoListPropertyDescriptor(TransitionInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -388,10 +345,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is TransitionInfoList) if (destType == typeof(string) && value is TransitionInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((TransitionInfoList)value).Items.Count.ToString() + " Transitions"; return $"{list.Items.Count} Transitions";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+135 -307
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -69,6 +67,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<User> _CacheList = new List<User>(); private static List<User> _CacheList = new List<User>();
protected static void AddToCache(User user) protected static void AddToCache(User user)
{ {
@@ -78,6 +77,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(user)) _CacheList.Remove(user); // In RemoveFromCache while (_CacheList.Contains(user)) _CacheList.Remove(user); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<User>> _CacheByPrimaryKey = new Dictionary<string, List<User>>(); private static Dictionary<string, List<User>> _CacheByPrimaryKey = new Dictionary<string, List<User>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -103,15 +103,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextUID = -1; private static int _nextUID = -1;
public static int NextUID public static int NextUID => _nextUID--;
{
get { return _nextUID--; }
}
private int _UID; private int _UID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int UID public int UID
@@ -400,10 +394,7 @@ namespace VEPROMS.CSLA.Library
return _UserMemberships; return _UserMemberships;
} }
} }
public void Reset_UserMemberships() public void Reset_UserMemberships() => _UserMembershipCount = -1;
{
_UserMembershipCount = -1;
}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -418,37 +409,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_UserMemberships == null ? false : _UserMemberships.IsDirtyList(list)); return base.IsDirty || (_UserMemberships != null && _UserMemberships.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_UserMemberships == null ? true : _UserMemberships.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_UserMemberships == null || _UserMemberships.IsValidList(list));
} }
// CSLATODO: Replace base User.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current User</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check User.GetIdValue to assure that the ID returned is unique // CSLATODO: Check User.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current User</returns> /// <returns>A Unique ID for the current User</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyUserUnique; // Absolutely Unique ID
{
return MyUserUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -477,8 +453,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -532,49 +508,11 @@ namespace VEPROMS.CSLA.Library
_UserExtension.AddInstanceValidationRules(ValidationRules); _UserExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(UID, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(FirstName, "<Role(s)>");
//AuthorizationRules.AllowRead(MiddleName, "<Role(s)>");
//AuthorizationRules.AllowRead(LastName, "<Role(s)>");
//AuthorizationRules.AllowRead(Suffix, "<Role(s)>");
//AuthorizationRules.AllowRead(CourtesyTitle, "<Role(s)>");
//AuthorizationRules.AllowRead(PhoneNumber, "<Role(s)>");
//AuthorizationRules.AllowRead(CFGName, "<Role(s)>");
//AuthorizationRules.AllowRead(UserLogin, "<Role(s)>");
//AuthorizationRules.AllowRead(UserName, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UsrID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(FirstName, "<Role(s)>");
//AuthorizationRules.AllowWrite(MiddleName, "<Role(s)>");
//AuthorizationRules.AllowWrite(LastName, "<Role(s)>");
//AuthorizationRules.AllowWrite(Suffix, "<Role(s)>");
//AuthorizationRules.AllowWrite(CourtesyTitle, "<Role(s)>");
//AuthorizationRules.AllowWrite(PhoneNumber, "<Role(s)>");
//AuthorizationRules.AllowWrite(CFGName, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserLogin, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserName, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UsrID, "<Role(s)>");
_UserExtension.AddAuthorizationRules(AuthorizationRules); _UserExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -582,55 +520,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_UserExtension.AddInstanceAuthorizationRules(AuthorizationRules); _UserExtension.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;
}
/// <summary>
/// determines if related records (Foreign Keys) will keep this Item from being deleted
/// </summary>
public bool CanDelete
{
get
{
// Check to make sure that there are not any related records
int usedByCount = 0;
usedByCount += _UserMembershipCount;
return (usedByCount == 0);
}
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _UserUnique = 0; private static int _UserUnique = 0;
protected static int UserUnique protected static int UserUnique => ++_UserUnique;
{ get { return ++_UserUnique; } } private readonly int _MyUserUnique = UserUnique;
private int _MyUserUnique = UserUnique; // Absolutely Unique ID - Editable
public int MyUserUnique // Absolutely Unique ID - Editable public int MyUserUnique => _MyUserUnique;
{ get { return _MyUserUnique; } }
protected User() protected User()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -639,15 +536,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~User() ~User()
{ {
_CountFinalized++; _CountFinalized++;
@@ -672,8 +565,6 @@ namespace VEPROMS.CSLA.Library
} }
public static User New() public static User New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a User");
try try
{ {
return DataPortal.Create<User>(); return DataPortal.Create<User>();
@@ -750,8 +641,6 @@ namespace VEPROMS.CSLA.Library
} }
public static User Get(int uid) public static User Get(int uid)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a User");
try try
{ {
User tmp = GetCachedByPrimaryKey(uid); User tmp = GetCachedByPrimaryKey(uid);
@@ -772,19 +661,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on User.Get", ex); throw new DbCslaException("Error on User.Get", ex);
} }
} }
public static User Get(SafeDataReader dr) public static User Get(SafeDataReader dr) => dr.Read() ? new User(dr) : null;
{ internal User(SafeDataReader dr) => ReadData(dr);
if (dr.Read()) return new User(dr);
return null;
}
internal User(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int uid) public static void Delete(int uid)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a User");
try try
{ {
DataPortal.Delete(new PKCriteria(uid)); DataPortal.Delete(new PKCriteria(uid));
@@ -796,12 +676,6 @@ namespace VEPROMS.CSLA.Library
} }
public override User Save() public override User Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a User");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a User");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a User");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -821,13 +695,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _UID; private readonly int _UID;
public int UID public int UID => _UID;
{ get { return _UID; } } public PKCriteria(int uid) => _UID = uid;
public PKCriteria(int uid)
{
_UID = uid;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -938,45 +808,52 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addUser"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@UserID", _UserID); cm.CommandText = "addUser";
cm.Parameters.AddWithValue("@FirstName", _FirstName); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@MiddleName", _MiddleName); cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.AddWithValue("@LastName", _LastName); cm.Parameters.AddWithValue("@FirstName", _FirstName);
cm.Parameters.AddWithValue("@Suffix", _Suffix); cm.Parameters.AddWithValue("@MiddleName", _MiddleName);
cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle); cm.Parameters.AddWithValue("@LastName", _LastName);
cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber); cm.Parameters.AddWithValue("@Suffix", _Suffix);
cm.Parameters.AddWithValue("@CFGName", _CFGName); cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle);
cm.Parameters.AddWithValue("@UserLogin", _UserLogin); cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber);
cm.Parameters.AddWithValue("@UserName", _UserName); cm.Parameters.AddWithValue("@CFGName", _CFGName);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@UserLogin", _UserLogin);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserName", _UserName);
cm.Parameters.AddWithValue("@UsrID", _UsrID); cm.Parameters.AddWithValue("@Config", _Config);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int); cm.Parameters.AddWithValue("@UsrID", _UsrID);
param_UID.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_UID); SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int)
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); {
param_LastChanged.Direction = ParameterDirection.Output; Direction = ParameterDirection.Output
cm.Parameters.Add(param_LastChanged); };
// CSLATODO: Define any additional output parameters cm.Parameters.Add(param_UID);
cm.ExecuteNonQuery(); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// Save all values being returned from the Procedure {
_UID = (int)cm.Parameters["@newUID"].Value; Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_UID = (int)cm.Parameters["@newUID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_UserMemberships != null) _UserMemberships.Update(this); _UserMemberships?.Update(this);
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.SQLInsert", GetHashCode());
} }
catch (Exception ex) catch (Exception ex)
@@ -1012,11 +889,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@UsrID", usrID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int); SqlParameter param_UID = new SqlParameter("@newUID", SqlDbType.Int)
param_UID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_UID); cm.Parameters.Add(param_UID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1061,43 +942,48 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateUser"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@UID", _UID); cm.CommandText = "updateUser";
cm.Parameters.AddWithValue("@UserID", _UserID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@FirstName", _FirstName); cm.Parameters.AddWithValue("@UID", _UID);
cm.Parameters.AddWithValue("@MiddleName", _MiddleName); cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.AddWithValue("@LastName", _LastName); cm.Parameters.AddWithValue("@FirstName", _FirstName);
cm.Parameters.AddWithValue("@Suffix", _Suffix); cm.Parameters.AddWithValue("@MiddleName", _MiddleName);
cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle); cm.Parameters.AddWithValue("@LastName", _LastName);
cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber); cm.Parameters.AddWithValue("@Suffix", _Suffix);
cm.Parameters.AddWithValue("@CFGName", _CFGName); cm.Parameters.AddWithValue("@CourtesyTitle", _CourtesyTitle);
cm.Parameters.AddWithValue("@UserLogin", _UserLogin); cm.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber);
cm.Parameters.AddWithValue("@UserName", _UserName); cm.Parameters.AddWithValue("@CFGName", _CFGName);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@UserLogin", _UserLogin);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@UserName", _UserName);
cm.Parameters.AddWithValue("@UsrID", _UsrID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UsrID", _UsrID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
if (_UserMemberships != null) _UserMemberships.Update(this); _UserMemberships?.Update(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1108,17 +994,20 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = User.Add(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID); if (IsNew)
else _LastChanged = User.Add(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID);
_LastChanged = User.Update(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID, ref _LastChanged); else
_LastChanged = User.Update(cn, ref _UID, _UserID, _FirstName, _MiddleName, _LastName, _Suffix, _CourtesyTitle, _PhoneNumber, _CFGName, _UserLogin, _UserName, _Config, _DTS, _UsrID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
if (_UserMemberships != null) _UserMemberships.Update(this); _UserMemberships?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int uid, string userID, string firstName, string middleName, string lastName, string suffix, string courtesyTitle, string phoneNumber, string cFGName, string userLogin, string userName, string config, DateTime dts, string usrID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int uid, string userID, string firstName, string middleName, string lastName, string suffix, string courtesyTitle, string phoneNumber, string cFGName, string userLogin, string userName, string config, DateTime dts, string usrID, ref byte[] lastChanged)
@@ -1148,8 +1037,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UsrID", usrID); cm.Parameters.AddWithValue("@UsrID", usrID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1234,16 +1125,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _UID; private readonly int _UID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int uid) => _UID = uid;
get { return _exists; }
}
public ExistsCommand(int uid)
{
_UID = uid;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] User.DataPortal_Execute", GetHashCode());
@@ -1259,7 +1144,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsUser"; cm.CommandText = "existsUser";
cm.Parameters.AddWithValue("@UID", _UID); cm.Parameters.AddWithValue("@UID", _UID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -1273,7 +1158,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
UserExtension _UserExtension = new UserExtension(); readonly UserExtension _UserExtension = new UserExtension();
[Serializable()] [Serializable()]
partial class UserExtension : extensionBase partial class UserExtension : extensionBase
{ {
@@ -1282,18 +1167,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual string DefaultUserID public virtual string DefaultUserID => Environment.UserName.ToUpper();
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return Environment.UserName.ToUpper(); } public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUsrID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1322,61 +1198,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is User) if (destType == typeof(string) && value is User myuser)
{ {
// Return the ToString value // Return the ToString value
return ((User)value).ToString(); return myuser.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create UserExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class User
// {
// partial class UserExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUsrID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class UserInfo : ReadOnlyBase<UserInfo>, IDisposable public partial class UserInfo : ReadOnlyBase<UserInfo>, IDisposable
{ {
public event UserInfoEvent Changed; public event UserInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<UserInfo> _CacheList = new List<UserInfo>(); private static List<UserInfo> _CacheList = new List<UserInfo>();
protected static void AddToCache(UserInfo userInfo) protected static void AddToCache(UserInfo userInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(userInfo)) _CacheList.Remove(userInfo); // In RemoveFromCache while (_CacheList.Contains(userInfo)) _CacheList.Remove(userInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<UserInfo>> _CacheByPrimaryKey = new Dictionary<string, List<UserInfo>>(); private static Dictionary<string, List<UserInfo>> _CacheByPrimaryKey = new Dictionary<string, List<UserInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,10 +71,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected User _Editable; protected User _Editable;
private IVEHasBrokenRules HasBrokenRules private IVEHasBrokenRules HasBrokenRules
{ {
@@ -252,32 +246,19 @@ namespace VEPROMS.CSLA.Library
foreach (UserInfo tmp in _CacheByPrimaryKey[_UID.ToString()]) foreach (UserInfo tmp in _CacheByPrimaryKey[_UID.ToString()])
tmp._UserMembershipCount = -1; // This will cause the data to be requeried tmp._UserMembershipCount = -1; // This will cause the data to be requeried
} }
// CSLATODO: Replace base UserInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current UserInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check UserInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check UserInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current UserInfo</returns> /// <returns>A Unique ID for the current UserInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyUserInfoUnique; // Absolutely Unique ID
{
return MyUserInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _UserInfoUnique = 0; private static int _UserInfoUnique = 0;
private static int UserInfoUnique private static int UserInfoUnique => ++_UserInfoUnique;
{ get { return ++_UserInfoUnique; } } private readonly int _MyUserInfoUnique = UserInfoUnique;
private int _MyUserInfoUnique = UserInfoUnique; // Absolutely Unique ID - Info
public int MyUserInfoUnique // Absolutely Unique ID - Info public int MyUserInfoUnique => _MyUserInfoUnique;
{ get { return _MyUserInfoUnique; } }
protected UserInfo() protected UserInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -286,15 +267,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~UserInfo() ~UserInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -311,10 +288,7 @@ namespace VEPROMS.CSLA.Library
if (listUserInfo.Count == 0) // If there are no items left in the list if (listUserInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(UID.ToString()); // remove the list _CacheByPrimaryKey.Remove(UID.ToString()); // remove the list
} }
public virtual User Get() public virtual User Get() => _Editable = User.Get(_UID);
{
return _Editable = User.Get(_UID);
}
public static void Refresh(User tmp) public static void Refresh(User tmp)
{ {
string key = tmp.UID.ToString(); string key = tmp.UID.ToString();
@@ -343,8 +317,6 @@ namespace VEPROMS.CSLA.Library
} }
public static UserInfo Get(int uid) public static UserInfo Get(int uid)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a User");
try try
{ {
UserInfo tmp = GetCachedByPrimaryKey(uid); UserInfo tmp = GetCachedByPrimaryKey(uid);
@@ -383,13 +355,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _UID; private readonly int _UID;
public int UID public int UID => _UID;
{ get { return _UID; } } public PKCriteria(int uid) => _UID = uid;
public PKCriteria(int uid)
{
_UID = uid;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -458,7 +426,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
UserInfoExtension _UserInfoExtension = new UserInfoExtension(); readonly UserInfoExtension _UserInfoExtension = new UserInfoExtension();
[Serializable()] [Serializable()]
partial class UserInfoExtension : extensionBase { } partial class UserInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -474,10 +442,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is UserInfo) if (destType == typeof(string) && value is UserInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((UserInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<UserInfo> Items internal new IList<UserInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (UserInfo tmp in this) foreach (UserInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~UserInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~UserInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on UserInfoList.Get", ex); throw new DbCslaException("Error on UserInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all UserInfo. /// Reset the list of all UserInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _UserInfoList = null;
{ private UserInfoList()
_UserInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static UserInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<UserInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on UserInfoList.Get", ex);
// }
//}
private UserInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new UserInfo(dr)); while (dr.Read()) Add(new UserInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("UserInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("UserInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("UserInfoList.DataPortal_Fetch", ex); throw new DbCslaException("UserInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
UserInfoListPropertyDescriptor pd = new UserInfoListPropertyDescriptor(this, i); UserInfoListPropertyDescriptor pd = new UserInfoListPropertyDescriptor(this, i);
@@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class UserInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class UserInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private UserInfo Item { get { return (UserInfo)_Item; } }
public UserInfoListPropertyDescriptor(UserInfoList collection, int index) : base(collection, index) { ;} public UserInfoListPropertyDescriptor(UserInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is UserInfoList) if (destType == typeof(string) && value is UserInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((UserInfoList)value).Items.Count.ToString() + " Users"; return $"{list.Items.Count} Users";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _UGID; private int _UGID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int UGID public int UGID
@@ -251,19 +245,7 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current UserMembership</returns> /// <returns>A Unique ID for the current UserMembership</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyUserMembershipUnique; // Absolutely Unique ID
{
return MyUserMembershipUnique; // Absolutely Unique ID
}
// CSLATODO: Replace base UserMembership.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current UserMembership</returns>
//public override string ToString()
//{
// return base.ToString();
//}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -278,18 +260,15 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyGroup == null ? false : _MyGroup.IsDirtyList(list)); return base.IsDirty || (_MyGroup != null && _MyGroup.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyGroup == null ? true : _MyGroup.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyGroup == null || _MyGroup.IsValidList(list));
} }
#endregion #endregion
#region ValidationRules #region ValidationRules
@@ -319,8 +298,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -375,80 +354,22 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(UGID, "<Role(s)>");
//AuthorizationRules.AllowRead(GID, "<Role(s)>");
//AuthorizationRules.AllowWrite(GID, "<Role(s)>");
//AuthorizationRules.AllowRead(StartDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(StartDate, "<Role(s)>");
//AuthorizationRules.AllowRead(EndDate, "<Role(s)>");
//AuthorizationRules.AllowWrite(EndDate, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UsrID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UsrID, "<Role(s)>");
}
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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _UserMembershipUnique = 0; private static int _UserMembershipUnique = 0;
private static int UserMembershipUnique private static int UserMembershipUnique => ++_UserMembershipUnique;
{ get { return ++_UserMembershipUnique; } } private readonly int _MyUserMembershipUnique = UserMembershipUnique;
private int _MyUserMembershipUnique = UserMembershipUnique; // Absolutely Unique ID - Editable FK
public int MyUserMembershipUnique // Absolutely Unique ID - Editable FK public int MyUserMembershipUnique => _MyUserMembershipUnique;
{ get { return _MyUserMembershipUnique; } } internal static UserMembership New(Group myGroup) => new UserMembership(myGroup);
internal static UserMembership New(Group myGroup) internal static UserMembership Get(SafeDataReader dr) => new UserMembership(dr);
{
return new UserMembership(myGroup);
}
internal static UserMembership Get(SafeDataReader dr)
{
return new UserMembership(dr);
}
public UserMembership() public UserMembership()
{ {
MarkAsChild(); MarkAsChild();
@@ -478,15 +399,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~UserMembership() ~UserMembership()
{ {
_CountFinalized++; _CountFinalized++;
@@ -528,33 +445,43 @@ namespace VEPROMS.CSLA.Library
internal void Insert(User myUser) internal void Insert(User myUser)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Membership.Add(cn, ref _UGID, myUser, _MyGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID); {
_LastChanged = Membership.Add(cn, ref _UGID, myUser, _MyGroup, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID);
}
MarkOld(); MarkOld();
} }
internal void Update(User myUser) internal void Update(User myUser)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
_LastChanged = Membership.Update(cn, ref _UGID, myUser.UID, _GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged); {
_LastChanged = Membership.Update(cn, ref _UGID, myUser.UID, _GID, new SmartDate(_StartDate), new SmartDate(_EndDate), _Config, _DTS, _UsrID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(User myUser) internal void DeleteSelf(User myUser)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
Membership.Remove(cn, _UGID); {
Membership.Remove(cn, _UGID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
UserMembershipExtension _UserMembershipExtension = new UserMembershipExtension(); readonly UserMembershipExtension _UserMembershipExtension = new UserMembershipExtension();
[Serializable()] [Serializable()]
partial class UserMembershipExtension : extensionBase partial class UserMembershipExtension : extensionBase
{ {
@@ -563,18 +490,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual string DefaultStartDate public virtual string DefaultStartDate => DateTime.Now.ToShortDateString();
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return DateTime.Now.ToShortDateString(); } public virtual string DefaultUsrID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUsrID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -603,61 +521,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is UserMembership) if (destType == typeof(string) && value is UserMembership membership)
{ {
// Return the ToString value // Return the ToString value
return ((UserMembership)value).ToString(); return membership.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create UserMembershipExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class UserMembership
// {
// partial class UserMembershipExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual SmartDate DefaultStartDate
// {
// get { return DateTime.Now.ToShortDateString(); }
// }
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUsrID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public UserMembership this[Membership myMembership]
}
// One To Many
public UserMembership this[Membership myMembership]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<UserMembership> Items public new System.Collections.Generic.IList<UserMembership> Items => base.Items;
{ public UserMembership GetItem(Membership myMembership)
get { return base.Items; }
}
public UserMembership GetItem(Membership myMembership)
{ {
foreach (UserMembership membership in this) foreach (UserMembership membership in this)
if (membership.UGID == myMembership.UGID) if (membership.UGID == myMembership.UGID)
@@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library
public UserMembership Add(Group myGroup) // One to Many public UserMembership Add(Group myGroup) // One to Many
{ {
UserMembership membership = UserMembership.New(myGroup); UserMembership membership = UserMembership.New(myGroup);
this.Add(membership); Add(membership);
return membership; return membership;
} }
public void Remove(Membership myMembership) public void Remove(Membership myMembership)
@@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (UserMembership child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (UserMembership child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static UserMemberships New() internal static UserMemberships New() => new UserMemberships();
{ internal static UserMemberships Get(SafeDataReader dr) => new UserMemberships(dr);
return new UserMemberships(); public static UserMemberships GetByUID(int uid)
}
internal static UserMemberships Get(SafeDataReader dr)
{
return new UserMemberships(dr);
}
public static UserMemberships GetByUID(int uid)
{ {
try try
{ {
@@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on UserMemberships.GetByUID", ex); throw new DbCslaException("Error on UserMemberships.GetByUID", ex);
} }
} }
private UserMemberships() private UserMemberships() => MarkAsChild();
{ internal UserMemberships(SafeDataReader dr)
MarkAsChild();
}
internal UserMemberships(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~UserMemberships()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~UserMemberships()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(UserMembership.Get(dr)); Add(UserMembership.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class UIDCriteria private class UIDCriteria
{ {
public UIDCriteria(int uid) public UIDCriteria(int uid) => _UID = uid;
{ private int _UID;
_UID = uid;
}
private int _UID;
public int UID public int UID
{ {
get { return _UID; } get { return _UID; }
@@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(UIDCriteria criteria) private void DataPortal_Fetch(UIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserMemberships.DataPortal_FetchUID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] UserMemberships.DataPortal_FetchUID", GetHashCode());
try try
{ {
@@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new UserMembership(dr)); while (dr.Read()) Add(new UserMembership(dr));
} }
} }
} }
@@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("UserMemberships.DataPortal_FetchUID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("UserMemberships.DataPortal_FetchUID", ex);
throw new DbCslaException("UserMemberships.DataPortal_Fetch", ex); throw new DbCslaException("UserMemberships.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(User user) internal void Update(User user)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
UserMembershipsPropertyDescriptor pd = new UserMembershipsPropertyDescriptor(this, i); UserMembershipsPropertyDescriptor pd = new UserMembershipsPropertyDescriptor(this, i);
@@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class UserMembershipsPropertyDescriptor : vlnListPropertyDescriptor public partial class UserMembershipsPropertyDescriptor : vlnListPropertyDescriptor
{ {
private UserMembership Item { get { return (UserMembership)_Item; } }
public UserMembershipsPropertyDescriptor(UserMemberships collection, int index) : base(collection, index) { ;} public UserMembershipsPropertyDescriptor(UserMemberships collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is UserMemberships) if (destType == typeof(string) && value is UserMemberships memberships)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((UserMemberships)value).Items.Count.ToString() + " Memberships"; return $"{memberships.Items.Count} Memberships";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+121 -245
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshVersions.Add(this); refreshVersions.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshVersions = new List<Version>();
{
_RefreshVersions = new List<Version>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -58,6 +53,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Version> _CacheList = new List<Version>(); private static List<Version> _CacheList = new List<Version>();
protected static void AddToCache(Version version) protected static void AddToCache(Version version)
{ {
@@ -67,6 +63,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(version)) _CacheList.Remove(version); // In RemoveFromCache while (_CacheList.Contains(version)) _CacheList.Remove(version); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Version>> _CacheByPrimaryKey = new Dictionary<string, List<Version>>(); private static Dictionary<string, List<Version>> _CacheByPrimaryKey = new Dictionary<string, List<Version>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -92,15 +89,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextVersionID = -1; private static int _nextVersionID = -1;
public static int NextVersionID public static int NextVersionID => _nextVersionID--;
{
get { return _nextVersionID--; }
}
private int _VersionID; private int _VersionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int VersionID public int VersionID
@@ -277,37 +268,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyRevision == null ? false : _MyRevision.IsDirtyList(list)) || (_MyStage == null ? false : _MyStage.IsDirtyList(list)); return base.IsDirty || (_MyRevision != null && _MyRevision.IsDirtyList(list)) || (_MyStage != null && _MyStage.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRevision == null ? true : _MyRevision.IsValidList(list)) && (_MyStage == null ? true : _MyStage.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyRevision == null || _MyRevision.IsValidList(list)) && (_MyStage == null || _MyStage.IsValidList(list));
} }
// CSLATODO: Replace base Version.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Version</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Version.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Version.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Version</returns> /// <returns>A Unique ID for the current Version</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyVersionUnique; // Absolutely Unique ID
{
return MyVersionUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -337,8 +313,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -377,35 +353,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(VersionID, "<Role(s)>");
//AuthorizationRules.AllowRead(RevisionID, "<Role(s)>");
//AuthorizationRules.AllowRead(StageID, "<Role(s)>");
//AuthorizationRules.AllowRead(PDF, "<Role(s)>");
//AuthorizationRules.AllowRead(SummaryPDF, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RevisionID, "<Role(s)>");
//AuthorizationRules.AllowWrite(StageID, "<Role(s)>");
//AuthorizationRules.AllowWrite(PDF, "<Role(s)>");
//AuthorizationRules.AllowWrite(SummaryPDF, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_VersionExtension.AddAuthorizationRules(AuthorizationRules); _VersionExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -413,42 +365,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_VersionExtension.AddInstanceAuthorizationRules(AuthorizationRules); _VersionExtension.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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _VersionUnique = 0; private static int _VersionUnique = 0;
protected static int VersionUnique protected static int VersionUnique => ++_VersionUnique;
{ get { return ++_VersionUnique; } } private readonly int _MyVersionUnique = VersionUnique;
private int _MyVersionUnique = VersionUnique; // Absolutely Unique ID - Editable
public int MyVersionUnique // Absolutely Unique ID - Editable public int MyVersionUnique => _MyVersionUnique;
{ get { return _MyVersionUnique; } }
protected Version() protected Version()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -457,15 +381,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Version() ~Version()
{ {
_CountFinalized++; _CountFinalized++;
@@ -490,8 +410,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Version New() public static Version New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Version");
try try
{ {
return DataPortal.Create<Version>(); return DataPortal.Create<Version>();
@@ -539,8 +457,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Version Get(int versionID) public static Version Get(int versionID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Version");
try try
{ {
Version tmp = GetCachedByPrimaryKey(versionID); Version tmp = GetCachedByPrimaryKey(versionID);
@@ -561,19 +477,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on Version.Get", ex); throw new DbCslaException("Error on Version.Get", ex);
} }
} }
public static Version Get(SafeDataReader dr) public static Version Get(SafeDataReader dr) => dr.Read() ? new Version(dr) : null;
{ internal Version(SafeDataReader dr) => ReadData(dr);
if (dr.Read()) return new Version(dr);
return null;
}
internal Version(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int versionID) public static void Delete(int versionID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Version");
try try
{ {
DataPortal.Delete(new PKCriteria(versionID)); DataPortal.Delete(new PKCriteria(versionID));
@@ -585,12 +492,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Version Save() public override Version Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Version");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Version");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Version");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -610,13 +511,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _VersionID; private readonly int _VersionID;
public int VersionID public int VersionID => _VersionID;
{ get { return _VersionID; } } public PKCriteria(int versionID) => _VersionID = versionID;
public PKCriteria(int versionID)
{
_VersionID = versionID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -715,38 +612,45 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyRevision != null) _MyRevision.Update(); _MyRevision?.Update();
if (_MyStage != null) _MyStage.Update(); _MyStage?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addVersion"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@RevisionID", RevisionID); cm.CommandText = "addVersion";
cm.Parameters.AddWithValue("@StageID", StageID); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@PDF", _PDF); cm.Parameters.AddWithValue("@RevisionID", RevisionID);
cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF); cm.Parameters.AddWithValue("@StageID", StageID);
cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML); cm.Parameters.AddWithValue("@PDF", _PDF);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); cm.Parameters.AddWithValue("@UserID", _UserID);
param_VersionID.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_VersionID); SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int)
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); {
param_LastChanged.Direction = ParameterDirection.Output; Direction = ParameterDirection.Output
cm.Parameters.Add(param_LastChanged); };
// CSLATODO: Define any additional output parameters cm.Parameters.Add(param_VersionID);
cm.ExecuteNonQuery(); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// Save all values being returned from the Procedure {
_VersionID = (int)cm.Parameters["@newVersionID"].Value; Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_VersionID = (int)cm.Parameters["@newVersionID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.SQLInsert", GetHashCode());
@@ -778,11 +682,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int)
param_VersionID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_VersionID); cm.Parameters.Add(param_VersionID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -827,36 +735,41 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.SQLUpdate", GetHashCode());
try try
{ {
if (_MyRevision != null) _MyRevision.Update(); _MyRevision?.Update();
if (_MyStage != null) _MyStage.Update(); _MyStage?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateVersion"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@VersionID", _VersionID); cm.CommandText = "updateVersion";
cm.Parameters.AddWithValue("@RevisionID", RevisionID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@StageID", StageID); cm.Parameters.AddWithValue("@VersionID", _VersionID);
cm.Parameters.AddWithValue("@PDF", _PDF); cm.Parameters.AddWithValue("@RevisionID", RevisionID);
cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF); cm.Parameters.AddWithValue("@StageID", StageID);
cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML); cm.Parameters.AddWithValue("@PDF", _PDF);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@SummaryPDF", _SummaryPDF);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@ApprovedXML", _ApprovedXML);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -869,14 +782,17 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, _MyStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID); if (IsNew)
else _LastChanged = Version.Add(cn, ref _VersionID, _MyRevision, _MyStage, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID);
_LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, _StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged); else
_LastChanged = Version.Update(cn, ref _VersionID, _RevisionID, _StageID, _PDF, _SummaryPDF, _ApprovedXML, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
} }
@@ -902,8 +818,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -988,16 +906,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _VersionID; private readonly int _VersionID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int versionID) => _VersionID = versionID;
get { return _exists; }
}
public ExistsCommand(int versionID)
{
_VersionID = versionID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Version.DataPortal_Execute", GetHashCode());
@@ -1013,7 +925,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsVersion"; cm.CommandText = "existsVersion";
cm.Parameters.AddWithValue("@VersionID", _VersionID); cm.Parameters.AddWithValue("@VersionID", _VersionID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -1027,7 +939,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
VersionExtension _VersionExtension = new VersionExtension(); readonly VersionExtension _VersionExtension = new VersionExtension();
[Serializable()] [Serializable()]
partial class VersionExtension : extensionBase partial class VersionExtension : extensionBase
{ {
@@ -1064,49 +976,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Version) if (destType == typeof(string) && value is Version myversion)
{ {
// Return the ToString value // Return the ToString value
return ((Version)value).ToString(); return myversion.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create VersionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Version
// {
// partial class VersionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class VersionInfo : ReadOnlyBase<VersionInfo>, IDisposable public partial class VersionInfo : ReadOnlyBase<VersionInfo>, IDisposable
{ {
public event VersionInfoEvent Changed; public event VersionInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<VersionInfo> _CacheList = new List<VersionInfo>(); private static List<VersionInfo> _CacheList = new List<VersionInfo>();
protected static void AddToCache(VersionInfo versionInfo) protected static void AddToCache(VersionInfo versionInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(versionInfo)) _CacheList.Remove(versionInfo); // In RemoveFromCache while (_CacheList.Contains(versionInfo)) _CacheList.Remove(versionInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<VersionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<VersionInfo>>(); private static Dictionary<string, List<VersionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<VersionInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Version _Editable; protected Version _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _VersionID; private int _VersionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int VersionID public int VersionID
@@ -196,32 +180,19 @@ namespace VEPROMS.CSLA.Library
return _UserID; return _UserID;
} }
} }
// CSLATODO: Replace base VersionInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current VersionInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check VersionInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check VersionInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current VersionInfo</returns> /// <returns>A Unique ID for the current VersionInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyVersionInfoUnique; // Absolutely Unique ID
{
return MyVersionInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _VersionInfoUnique = 0; private static int _VersionInfoUnique = 0;
private static int VersionInfoUnique private static int VersionInfoUnique => ++_VersionInfoUnique;
{ get { return ++_VersionInfoUnique; } } private readonly int _MyVersionInfoUnique = VersionInfoUnique;
private int _MyVersionInfoUnique = VersionInfoUnique; // Absolutely Unique ID - Info
public int MyVersionInfoUnique // Absolutely Unique ID - Info public int MyVersionInfoUnique => _MyVersionInfoUnique;
{ get { return _MyVersionInfoUnique; } }
protected VersionInfo() protected VersionInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -230,15 +201,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~VersionInfo() ~VersionInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -255,10 +222,7 @@ namespace VEPROMS.CSLA.Library
if (listVersionInfo.Count == 0) // If there are no items left in the list if (listVersionInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(VersionID.ToString()); // remove the list _CacheByPrimaryKey.Remove(VersionID.ToString()); // remove the list
} }
public virtual Version Get() public virtual Version Get() => _Editable = Version.Get(_VersionID);
{
return _Editable = Version.Get(_VersionID);
}
public static void Refresh(Version tmp) public static void Refresh(Version tmp)
{ {
string key = tmp.VersionID.ToString(); string key = tmp.VersionID.ToString();
@@ -271,18 +235,18 @@ namespace VEPROMS.CSLA.Library
{ {
if (_RevisionID != tmp.RevisionID) if (_RevisionID != tmp.RevisionID)
{ {
if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for old value MyRevision?.RefreshRevisionVersions(); // Update List for old value
_RevisionID = tmp.RevisionID; // Update the value _RevisionID = tmp.RevisionID; // Update the value
} }
_MyRevision = null; // Reset list so that the next line gets a new list _MyRevision = null; // Reset list so that the next line gets a new list
if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for new value MyRevision?.RefreshRevisionVersions(); // Update List for new value
if (_StageID != tmp.StageID) if (_StageID != tmp.StageID)
{ {
if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for old value MyStage?.RefreshStageVersions(); // Update List for old value
_StageID = tmp.StageID; // Update the value _StageID = tmp.StageID; // Update the value
} }
_MyStage = null; // Reset list so that the next line gets a new list _MyStage = null; // Reset list so that the next line gets a new list
if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for new value MyStage?.RefreshStageVersions(); // Update List for new value
_PDF = tmp.PDF; _PDF = tmp.PDF;
_SummaryPDF = tmp.SummaryPDF; _SummaryPDF = tmp.SummaryPDF;
_DTS = tmp.DTS; _DTS = tmp.DTS;
@@ -302,11 +266,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_StageID != tmp.StageID) if (_StageID != tmp.StageID)
{ {
if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for old value MyStage?.RefreshStageVersions(); // Update List for old value
_StageID = tmp.StageID; // Update the value _StageID = tmp.StageID; // Update the value
} }
_MyStage = null; // Reset list so that the next line gets a new list _MyStage = null; // Reset list so that the next line gets a new list
if (MyStage != null) MyStage.RefreshStageVersions(); // Update List for new value MyStage?.RefreshStageVersions(); // Update List for new value
_PDF = tmp.PDF; _PDF = tmp.PDF;
_SummaryPDF = tmp.SummaryPDF; _SummaryPDF = tmp.SummaryPDF;
_DTS = tmp.DTS; _DTS = tmp.DTS;
@@ -326,11 +290,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_RevisionID != tmp.RevisionID) if (_RevisionID != tmp.RevisionID)
{ {
if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for old value MyRevision?.RefreshRevisionVersions(); // Update List for old value
_RevisionID = tmp.RevisionID; // Update the value _RevisionID = tmp.RevisionID; // Update the value
} }
_MyRevision = null; // Reset list so that the next line gets a new list _MyRevision = null; // Reset list so that the next line gets a new list
if (MyRevision != null) MyRevision.RefreshRevisionVersions(); // Update List for new value MyRevision?.RefreshRevisionVersions(); // Update List for new value
_PDF = tmp.PDF; _PDF = tmp.PDF;
_SummaryPDF = tmp.SummaryPDF; _SummaryPDF = tmp.SummaryPDF;
_DTS = tmp.DTS; _DTS = tmp.DTS;
@@ -340,8 +304,6 @@ namespace VEPROMS.CSLA.Library
} }
public static VersionInfo Get(int versionID) public static VersionInfo Get(int versionID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Version");
try try
{ {
VersionInfo tmp = GetCachedByPrimaryKey(versionID); VersionInfo tmp = GetCachedByPrimaryKey(versionID);
@@ -380,13 +342,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _VersionID; private readonly int _VersionID;
public int VersionID public int VersionID => _VersionID;
{ get { return _VersionID; } } public PKCriteria(int versionID) => _VersionID = versionID;
public PKCriteria(int versionID)
{
_VersionID = versionID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -448,7 +406,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
VersionInfoExtension _VersionInfoExtension = new VersionInfoExtension(); readonly VersionInfoExtension _VersionInfoExtension = new VersionInfoExtension();
[Serializable()] [Serializable()]
partial class VersionInfoExtension : extensionBase { } partial class VersionInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -464,10 +422,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is VersionInfo) if (destType == typeof(string) && value is VersionInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((VersionInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<VersionInfo> Items internal new IList<VersionInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (VersionInfo tmp in this) foreach (VersionInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~VersionInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~VersionInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on VersionInfoList.Get", ex); throw new DbCslaException("Error on VersionInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all VersionInfo. /// Reset the list of all VersionInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _VersionInfoList = null;
{ public static VersionInfoList GetByRevisionID(int revisionID)
_VersionInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static VersionInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<VersionInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on VersionInfoList.Get", ex);
// }
//}
public static VersionInfoList GetByRevisionID(int revisionID)
{ {
try try
{ {
@@ -180,11 +158,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class RevisionIDCriteria private class RevisionIDCriteria
{ {
public RevisionIDCriteria(int revisionID) public RevisionIDCriteria(int revisionID) => _RevisionID = revisionID;
{ private int _RevisionID;
_RevisionID = revisionID;
}
private int _RevisionID;
public int RevisionID public int RevisionID
{ {
get { return _RevisionID; } get { return _RevisionID; }
@@ -224,11 +199,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class StageIDCriteria private class StageIDCriteria
{ {
public StageIDCriteria(int stageID) public StageIDCriteria(int stageID) => _StageID = stageID;
{ private int _StageID;
_StageID = stageID;
}
private int _StageID;
public int StageID public int StageID
{ {
get { return _StageID; } get { return _StageID; }
@@ -265,41 +237,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -321,7 +282,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class VersionInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class VersionInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private VersionInfo Item { get { return (VersionInfo)_Item; } }
public VersionInfoListPropertyDescriptor(VersionInfoList collection, int index) : base(collection, index) { ;} public VersionInfoListPropertyDescriptor(VersionInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -330,10 +290,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is VersionInfoList) if (destType == typeof(string) && value is VersionInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((VersionInfoList)value).Items.Count.ToString() + " Versions"; return $"{list.Items.Count} Versions";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+96 -214
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshZContents.Add(this); refreshZContents.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshZContents = new List<ZContent>();
{
_RefreshZContents = new List<ZContent>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<ZContent> _CacheList = new List<ZContent>(); private static List<ZContent> _CacheList = new List<ZContent>();
protected static void AddToCache(ZContent zContent) protected static void AddToCache(ZContent zContent)
{ {
@@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(zContent)) _CacheList.Remove(zContent); // In RemoveFromCache while (_CacheList.Contains(zContent)) _CacheList.Remove(zContent); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<ZContent>> _CacheByPrimaryKey = new Dictionary<string, List<ZContent>>(); private static Dictionary<string, List<ZContent>> _CacheByPrimaryKey = new Dictionary<string, List<ZContent>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -90,10 +87,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _ContentID; private int _ContentID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ContentID public int ContentID
@@ -138,40 +132,18 @@ namespace VEPROMS.CSLA.Library
} }
} }
private byte[] _LastChanged = new byte[8];//timestamp private byte[] _LastChanged = new byte[8];//timestamp
public override bool IsDirty public override bool IsDirty => base.IsDirty;
{ [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
get { return base.IsDirty; } public bool IsDirtyList(List<object> list) => base.IsDirty;
} public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
public bool IsDirtyList(List<object> list) [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
{ public bool IsValidList(List<object> list) => (IsNew && !IsDirty) || base.IsValid;
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
// CSLATODO: Replace base ZContent.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current ZContent</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check ZContent.GetIdValue to assure that the ID returned is unique // CSLATODO: Check ZContent.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current ZContent</returns> /// <returns>A Unique ID for the current ZContent</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyZContentUnique; // Absolutely Unique ID
{
return MyZContentUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -199,8 +171,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -219,25 +191,11 @@ namespace VEPROMS.CSLA.Library
_ZContentExtension.AddInstanceValidationRules(ValidationRules); _ZContentExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(ContentID, "<Role(s)>");
//AuthorizationRules.AllowRead(OldStepSequence, "<Role(s)>");
//AuthorizationRules.AllowWrite(OldStepSequence, "<Role(s)>");
_ZContentExtension.AddAuthorizationRules(AuthorizationRules); _ZContentExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -245,42 +203,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_ZContentExtension.AddInstanceAuthorizationRules(AuthorizationRules); _ZContentExtension.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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _ZContentUnique = 0; private static int _ZContentUnique = 0;
protected static int ZContentUnique protected static int ZContentUnique => ++_ZContentUnique;
{ get { return ++_ZContentUnique; } } private readonly int _MyZContentUnique = ZContentUnique;
private int _MyZContentUnique = ZContentUnique; // Absolutely Unique ID - Editable
public int MyZContentUnique // Absolutely Unique ID - Editable public int MyZContentUnique => _MyZContentUnique;
{ get { return _MyZContentUnique; } }
protected ZContent() protected ZContent()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -289,15 +219,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~ZContent() ~ZContent()
{ {
_CountFinalized++; _CountFinalized++;
@@ -322,8 +248,6 @@ namespace VEPROMS.CSLA.Library
} }
public static ZContent New() public static ZContent New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a ZContent");
try try
{ {
return DataPortal.Create<ZContent>(); return DataPortal.Create<ZContent>();
@@ -366,8 +290,6 @@ namespace VEPROMS.CSLA.Library
} }
public static ZContent Get(int contentID) public static ZContent Get(int contentID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a ZContent");
try try
{ {
ZContent tmp = GetCachedByPrimaryKey(contentID); ZContent tmp = GetCachedByPrimaryKey(contentID);
@@ -393,14 +315,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new ZContent(dr); if (dr.Read()) return new ZContent(dr);
return null; return null;
} }
internal ZContent(SafeDataReader dr) internal ZContent(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int contentID) public static void Delete(int contentID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a ZContent");
try try
{ {
DataPortal.Delete(new PKCriteria(contentID)); DataPortal.Delete(new PKCriteria(contentID));
@@ -412,12 +329,6 @@ namespace VEPROMS.CSLA.Library
} }
public override ZContent Save() public override ZContent Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a ZContent");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a ZContent");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a ZContent");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -437,13 +348,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _ContentID; private readonly int _ContentID;
public int ContentID public int ContentID => _ContentID;
{ get { return _ContentID; } } public PKCriteria(int contentID) => _ContentID = contentID;
public PKCriteria(int contentID)
{
_ContentID = contentID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -536,27 +443,32 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addZContent"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ContentID", ContentID); cm.CommandText = "addZContent";
cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence); // Input All Fields - Except Calculated Columns
// Output Calculated Columns cm.Parameters.AddWithValue("@ContentID", ContentID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.SQLInsert", GetHashCode());
@@ -583,8 +495,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@ContentID", myContent.ContentID); cm.Parameters.AddWithValue("@ContentID", myContent.ContentID);
cm.Parameters.AddWithValue("@OldStepSequence", oldStepSequence); cm.Parameters.AddWithValue("@OldStepSequence", oldStepSequence);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -628,28 +542,33 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateZContent"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ContentID", ContentID); cm.CommandText = "updateZContent";
cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); cm.Parameters.AddWithValue("@ContentID", ContentID);
// Output Calculated Columns cm.Parameters.AddWithValue("@OldStepSequence", _OldStepSequence);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -662,14 +581,17 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update(Content content) internal void Update(Content content)
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = ZContent.Add(cn, content, _OldStepSequence); if (IsNew)
else _LastChanged = ZContent.Add(cn, content, _OldStepSequence);
_LastChanged = ZContent.Update(cn, content.ContentID, _OldStepSequence, ref _LastChanged); else
_LastChanged = ZContent.Update(cn, content.ContentID, _OldStepSequence, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
} }
@@ -689,8 +611,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@OldStepSequence", oldStepSequence); cm.Parameters.AddWithValue("@OldStepSequence", oldStepSequence);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -775,16 +699,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _ContentID; private readonly int _ContentID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int contentID) => _ContentID = contentID;
get { return _exists; }
}
public ExistsCommand(int contentID)
{
_ContentID = contentID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZContent.DataPortal_Execute", GetHashCode());
@@ -800,7 +718,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsZContent"; cm.CommandText = "existsZContent";
cm.Parameters.AddWithValue("@ContentID", _ContentID); cm.Parameters.AddWithValue("@ContentID", _ContentID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -814,7 +732,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
ZContentExtension _ZContentExtension = new ZContentExtension(); readonly ZContentExtension _ZContentExtension = new ZContentExtension();
[Serializable()] [Serializable()]
partial class ZContentExtension : extensionBase partial class ZContentExtension : extensionBase
{ {
@@ -851,49 +769,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is ZContent) if (destType == typeof(string) && value is ZContent mycontent)
{ {
// Return the ToString value // Return the ToString value
return ((ZContent)value).ToString(); return mycontent.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create ZContentExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class ZContent
// {
// partial class ZContentExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class ZContentInfo : ReadOnlyBase<ZContentInfo>, IDisposable public partial class ZContentInfo : ReadOnlyBase<ZContentInfo>, IDisposable
{ {
public event ZContentInfoEvent Changed; public event ZContentInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<ZContentInfo> _CacheList = new List<ZContentInfo>(); private static List<ZContentInfo> _CacheList = new List<ZContentInfo>();
protected static void AddToCache(ZContentInfo zContentInfo) protected static void AddToCache(ZContentInfo zContentInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(zContentInfo)) _CacheList.Remove(zContentInfo); // In RemoveFromCache while (_CacheList.Contains(zContentInfo)) _CacheList.Remove(zContentInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<ZContentInfo>> _CacheByPrimaryKey = new Dictionary<string, List<ZContentInfo>>(); private static Dictionary<string, List<ZContentInfo>> _CacheByPrimaryKey = new Dictionary<string, List<ZContentInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -70,21 +67,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected ZContent _Editable; protected ZContent _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _ContentID; private int _ContentID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ContentID public int ContentID
@@ -116,32 +100,19 @@ namespace VEPROMS.CSLA.Library
return _OldStepSequence; return _OldStepSequence;
} }
} }
// CSLATODO: Replace base ZContentInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current ZContentInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check ZContentInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check ZContentInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current ZContentInfo</returns> /// <returns>A Unique ID for the current ZContentInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyZContentInfoUnique; // Absolutely Unique ID
{
return MyZContentInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _ZContentInfoUnique = 0; private static int _ZContentInfoUnique = 0;
private static int ZContentInfoUnique private static int ZContentInfoUnique => ++_ZContentInfoUnique;
{ get { return ++_ZContentInfoUnique; } } private readonly int _MyZContentInfoUnique = ZContentInfoUnique;
private int _MyZContentInfoUnique = ZContentInfoUnique; // Absolutely Unique ID - Info
public int MyZContentInfoUnique // Absolutely Unique ID - Info public int MyZContentInfoUnique => _MyZContentInfoUnique;
{ get { return _MyZContentInfoUnique; } }
protected ZContentInfo() protected ZContentInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -150,15 +121,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~ZContentInfo() ~ZContentInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -175,10 +142,7 @@ namespace VEPROMS.CSLA.Library
if (listZContentInfo.Count == 0) // If there are no items left in the list if (listZContentInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list
} }
public virtual ZContent Get() public virtual ZContent Get() => _Editable = ZContent.Get(_ContentID);
{
return _Editable = ZContent.Get(_ContentID);
}
public static void Refresh(ZContent tmp) public static void Refresh(ZContent tmp)
{ {
string key = tmp.ContentID.ToString(); string key = tmp.ContentID.ToString();
@@ -191,20 +155,10 @@ namespace VEPROMS.CSLA.Library
{ {
_OldStepSequence = tmp.OldStepSequence; _OldStepSequence = tmp.OldStepSequence;
_ZContentInfoExtension.Refresh(this); _ZContentInfoExtension.Refresh(this);
//RHM Removed 20090724 - Duplicates function of code above.
// - Dispose caused error when a new step was added.
// - Resequence of transitions did not work properly.
// if(_MyContent != null)
// {
// _MyContent.Dispose();// Dispose related value
// _MyContent = null;// Reset related value
// }
OnChange();// raise an event OnChange();// raise an event
} }
public static ZContentInfo Get(int contentID) public static ZContentInfo Get(int contentID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a ZContent");
try try
{ {
ZContentInfo tmp = GetCachedByPrimaryKey(contentID); ZContentInfo tmp = GetCachedByPrimaryKey(contentID);
@@ -243,13 +197,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _ContentID; private readonly int _ContentID;
public int ContentID public int ContentID => _ContentID;
{ get { return _ContentID; } } public PKCriteria(int contentID) => _ContentID = contentID;
public PKCriteria(int contentID)
{
_ContentID = contentID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -305,7 +255,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
ZContentInfoExtension _ZContentInfoExtension = new ZContentInfoExtension(); readonly ZContentInfoExtension _ZContentInfoExtension = new ZContentInfoExtension();
[Serializable()] [Serializable()]
partial class ZContentInfoExtension : extensionBase { } partial class ZContentInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -321,10 +271,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is ZContentInfo) if (destType == typeof(string) && value is ZContentInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((ZContentInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshZTransitions.Add(this); refreshZTransitions.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshZTransitions = new List<ZTransition>();
{
_RefreshZTransitions = new List<ZTransition>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<ZTransition> _CacheList = new List<ZTransition>(); private static List<ZTransition> _CacheList = new List<ZTransition>();
protected static void AddToCache(ZTransition zTransition) protected static void AddToCache(ZTransition zTransition)
{ {
@@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(zTransition)) _CacheList.Remove(zTransition); // In RemoveFromCache while (_CacheList.Contains(zTransition)) _CacheList.Remove(zTransition); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<ZTransition>> _CacheByPrimaryKey = new Dictionary<string, List<ZTransition>>(); private static Dictionary<string, List<ZTransition>> _CacheByPrimaryKey = new Dictionary<string, List<ZTransition>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -90,10 +87,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _TransitionID; private int _TransitionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int TransitionID public int TransitionID
@@ -136,40 +130,18 @@ namespace VEPROMS.CSLA.Library
} }
} }
private byte[] _LastChanged = new byte[8];//timestamp private byte[] _LastChanged = new byte[8];//timestamp
public override bool IsDirty public override bool IsDirty => base.IsDirty;
{ [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
get { return base.IsDirty; } public bool IsDirtyList(List<object> list) => base.IsDirty;
} public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
public bool IsDirtyList(List<object> list) [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
{ public bool IsValidList(List<object> list) => (IsNew && !IsDirty) || base.IsValid;
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
// CSLATODO: Replace base ZTransition.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current ZTransition</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check ZTransition.GetIdValue to assure that the ID returned is unique // CSLATODO: Check ZTransition.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current ZTransition</returns> /// <returns>A Unique ID for the current ZTransition</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyZTransitionUnique; // Absolutely Unique ID
{
return MyZTransitionUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -197,8 +169,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -217,17 +189,6 @@ namespace VEPROMS.CSLA.Library
_ZTransitionExtension.AddInstanceValidationRules(ValidationRules); _ZTransitionExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // 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 #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
@@ -243,42 +204,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_ZTransitionExtension.AddInstanceAuthorizationRules(AuthorizationRules); _ZTransitionExtension.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 #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _ZTransitionUnique = 0; private static int _ZTransitionUnique = 0;
protected static int ZTransitionUnique protected static int ZTransitionUnique => ++_ZTransitionUnique;
{ get { return ++_ZTransitionUnique; } } private readonly int _MyZTransitionUnique = ZTransitionUnique;
private int _MyZTransitionUnique = ZTransitionUnique; // Absolutely Unique ID - Editable
public int MyZTransitionUnique // Absolutely Unique ID - Editable public int MyZTransitionUnique => _MyZTransitionUnique;
{ get { return _MyZTransitionUnique; } }
protected ZTransition() protected ZTransition()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -287,15 +220,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~ZTransition() ~ZTransition()
{ {
_CountFinalized++; _CountFinalized++;
@@ -320,8 +249,6 @@ namespace VEPROMS.CSLA.Library
} }
public static ZTransition New() public static ZTransition New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a ZTransition");
try try
{ {
return DataPortal.Create<ZTransition>(); return DataPortal.Create<ZTransition>();
@@ -364,8 +291,6 @@ namespace VEPROMS.CSLA.Library
} }
public static ZTransition Get(int transitionID) public static ZTransition Get(int transitionID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a ZTransition");
try try
{ {
ZTransition tmp = GetCachedByPrimaryKey(transitionID); ZTransition tmp = GetCachedByPrimaryKey(transitionID);
@@ -386,19 +311,10 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on ZTransition.Get", ex); throw new DbCslaException("Error on ZTransition.Get", ex);
} }
} }
public static ZTransition Get(SafeDataReader dr) public static ZTransition Get(SafeDataReader dr) => dr.Read() ? new ZTransition(dr) : null;
{ internal ZTransition(SafeDataReader dr) => ReadData(dr);
if (dr.Read()) return new ZTransition(dr);
return null;
}
internal ZTransition(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int transitionID) public static void Delete(int transitionID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a ZTransition");
try try
{ {
DataPortal.Delete(new PKCriteria(transitionID)); DataPortal.Delete(new PKCriteria(transitionID));
@@ -410,12 +326,6 @@ namespace VEPROMS.CSLA.Library
} }
public override ZTransition Save() public override ZTransition Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a ZTransition");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a ZTransition");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a ZTransition");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -435,13 +345,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _TransitionID; private readonly int _TransitionID;
public int TransitionID public int TransitionID => _TransitionID;
{ get { return _TransitionID; } } public PKCriteria(int transitionID) => _TransitionID = transitionID;
public PKCriteria(int transitionID)
{
_TransitionID = transitionID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -534,27 +440,32 @@ namespace VEPROMS.CSLA.Library
[Transactional(TransactionalTypes.TransactionScope)] [Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "addZTransition"; cm.CommandType = CommandType.StoredProcedure;
// Input All Fields - Except Calculated Columns cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@TransitionID", TransitionID); cm.CommandText = "addZTransition";
cm.Parameters.AddWithValue("@Oldto", _Oldto); // Input All Fields - Except Calculated Columns
// Output Calculated Columns cm.Parameters.AddWithValue("@TransitionID", TransitionID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@Oldto", _Oldto);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.SQLInsert", GetHashCode());
@@ -581,8 +492,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@TransitionID", myTransition.TransitionID); cm.Parameters.AddWithValue("@TransitionID", myTransition.TransitionID);
cm.Parameters.AddWithValue("@Oldto", oldto); cm.Parameters.AddWithValue("@Oldto", oldto);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -626,28 +539,33 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateZTransition"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@TransitionID", TransitionID); cm.CommandText = "updateZTransition";
cm.Parameters.AddWithValue("@Oldto", _Oldto); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); cm.Parameters.AddWithValue("@TransitionID", TransitionID);
// Output Calculated Columns cm.Parameters.AddWithValue("@Oldto", _Oldto);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; 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(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -660,14 +578,17 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update(Transition transition) internal void Update(Transition transition)
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"])
if (IsNew) {
_LastChanged = ZTransition.Add(cn, transition, _Oldto); if (IsNew)
else _LastChanged = ZTransition.Add(cn, transition, _Oldto);
_LastChanged = ZTransition.Update(cn, transition.TransitionID, _Oldto, ref _LastChanged); else
_LastChanged = ZTransition.Update(cn, transition.TransitionID, _Oldto, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
} }
@@ -687,8 +608,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@Oldto", oldto); cm.Parameters.AddWithValue("@Oldto", oldto);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -773,16 +696,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _TransitionID; private readonly int _TransitionID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int transitionID) => _TransitionID = transitionID;
get { return _exists; }
}
public ExistsCommand(int transitionID)
{
_TransitionID = transitionID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ZTransition.DataPortal_Execute", GetHashCode());
@@ -798,7 +715,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandText = "existsZTransition"; cm.CommandText = "existsZTransition";
cm.Parameters.AddWithValue("@TransitionID", _TransitionID); cm.Parameters.AddWithValue("@TransitionID", _TransitionID);
int count = (int)cm.ExecuteScalar(); int count = (int)cm.ExecuteScalar();
_exists = (count > 0); _exists = count > 0;
} }
} }
} }
@@ -812,7 +729,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
ZTransitionExtension _ZTransitionExtension = new ZTransitionExtension(); readonly ZTransitionExtension _ZTransitionExtension = new ZTransitionExtension();
[Serializable()] [Serializable()]
partial class ZTransitionExtension : extensionBase partial class ZTransitionExtension : extensionBase
{ {
@@ -849,49 +766,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is ZTransition) if (destType == typeof(string) && value is ZTransition mytransition)
{ {
// Return the ToString value // Return the ToString value
return ((ZTransition)value).ToString(); return mytransition.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create ZTransitionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class ZTransition
// {
// partial class ZTransitionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// 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 */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class ZTransitionInfo : ReadOnlyBase<ZTransitionInfo>, IDisposable public partial class ZTransitionInfo : ReadOnlyBase<ZTransitionInfo>, IDisposable
{ {
public event ZTransitionInfoEvent Changed; public event ZTransitionInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<ZTransitionInfo> _CacheList = new List<ZTransitionInfo>(); private static List<ZTransitionInfo> _CacheList = new List<ZTransitionInfo>();
protected static void AddToCache(ZTransitionInfo zTransitionInfo) protected static void AddToCache(ZTransitionInfo zTransitionInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(zTransitionInfo)) _CacheList.Remove(zTransitionInfo); // In RemoveFromCache while (_CacheList.Contains(zTransitionInfo)) _CacheList.Remove(zTransitionInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<ZTransitionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<ZTransitionInfo>>(); private static Dictionary<string, List<ZTransitionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<ZTransitionInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -70,21 +67,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected ZTransition _Editable; protected ZTransition _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _TransitionID; private int _TransitionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int TransitionID public int TransitionID
@@ -116,32 +100,19 @@ namespace VEPROMS.CSLA.Library
return _Oldto; return _Oldto;
} }
} }
// CSLATODO: Replace base ZTransitionInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current ZTransitionInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check ZTransitionInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check ZTransitionInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current ZTransitionInfo</returns> /// <returns>A Unique ID for the current ZTransitionInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyZTransitionInfoUnique; // Absolutely Unique ID
{
return MyZTransitionInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _ZTransitionInfoUnique = 0; private static int _ZTransitionInfoUnique = 0;
private static int ZTransitionInfoUnique private static int ZTransitionInfoUnique => ++_ZTransitionInfoUnique;
{ get { return ++_ZTransitionInfoUnique; } } private readonly int _MyZTransitionInfoUnique = ZTransitionInfoUnique;
private int _MyZTransitionInfoUnique = ZTransitionInfoUnique; // Absolutely Unique ID - Info
public int MyZTransitionInfoUnique // Absolutely Unique ID - Info public int MyZTransitionInfoUnique => _MyZTransitionInfoUnique;
{ get { return _MyZTransitionInfoUnique; } }
protected ZTransitionInfo() protected ZTransitionInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -150,15 +121,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~ZTransitionInfo() ~ZTransitionInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -175,10 +142,7 @@ namespace VEPROMS.CSLA.Library
if (listZTransitionInfo.Count == 0) // If there are no items left in the list if (listZTransitionInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list _CacheByPrimaryKey.Remove(TransitionID.ToString()); // remove the list
} }
public virtual ZTransition Get() public virtual ZTransition Get() => _Editable = ZTransition.Get(_TransitionID);
{
return _Editable = ZTransition.Get(_TransitionID);
}
public static void Refresh(ZTransition tmp) public static void Refresh(ZTransition tmp)
{ {
string key = tmp.TransitionID.ToString(); string key = tmp.TransitionID.ToString();
@@ -195,8 +159,6 @@ namespace VEPROMS.CSLA.Library
} }
public static ZTransitionInfo Get(int transitionID) public static ZTransitionInfo Get(int transitionID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a ZTransition");
try try
{ {
ZTransitionInfo tmp = GetCachedByPrimaryKey(transitionID); ZTransitionInfo tmp = GetCachedByPrimaryKey(transitionID);
@@ -235,13 +197,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _TransitionID; private readonly int _TransitionID;
public int TransitionID public int TransitionID => _TransitionID;
{ get { return _TransitionID; } } public PKCriteria(int transitionID) => _TransitionID = transitionID;
public PKCriteria(int transitionID)
{
_TransitionID = transitionID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -297,7 +255,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
ZTransitionInfoExtension _ZTransitionInfoExtension = new ZTransitionInfoExtension(); readonly ZTransitionInfoExtension _ZTransitionInfoExtension = new ZTransitionInfoExtension();
[Serializable()] [Serializable()]
partial class ZTransitionInfoExtension : extensionBase { } partial class ZTransitionInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -313,10 +271,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is ZTransitionInfo) if (destType == typeof(string) && value is ZTransitionInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((ZTransitionInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }