Entity.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Reflection;
  7. using InABox.Clients;
  8. using InABox.Core;
  9. namespace InABox.Core
  10. {
  11. public class Credentials
  12. {
  13. public virtual string UserID { get; set; }
  14. public virtual string Password { get; set; }
  15. }
  16. public interface IEntity
  17. {
  18. Guid ID { get; set; }
  19. Guid Deleted { get; set; }
  20. bool IsChanged();
  21. void CommitChanges();
  22. void CancelChanges();
  23. }
  24. public interface ITaxable
  25. {
  26. double ExTax { get; set; }
  27. double TaxRate { get; set; }
  28. double Tax { get; set; }
  29. double IncTax { get; set; }
  30. }
  31. public interface IIssues
  32. {
  33. string Issues { get; set; }
  34. }
  35. public interface IExportable
  36. {
  37. }
  38. public interface IImportable
  39. {
  40. }
  41. /// <summary>
  42. /// Indicate that an <see cref="Entity"/> is able to be merged together.
  43. /// </summary>
  44. /// <remarks>
  45. /// It is recommended that an <see cref="Entity"/> that implements this should provide a <see cref="object.ToString"/> implementation.
  46. /// </remarks>
  47. public interface IMergeable
  48. {
  49. }
  50. public interface ISecure { }
  51. public interface IDuplicatable
  52. {
  53. IEntityDuplicator GetDuplicator();
  54. }
  55. public interface IEntityDuplicator
  56. {
  57. //void Duplicate(IFilter filter);
  58. void Duplicate(IEnumerable<BaseObject> entities);
  59. }
  60. public class EntityDuplicator<TEntity> : IEntityDuplicator where TEntity : Entity, IRemotable, IPersistent
  61. {
  62. private interface IRelationship
  63. {
  64. Type ParentType { get; }
  65. Type ChildType { get; }
  66. IFilter GetFilter(Entity parent);
  67. }
  68. private class EntityLinkRelationship<TParent, TChild> : IRelationship
  69. {
  70. public Type ParentType => typeof(TParent);
  71. public Type ChildType => typeof(TChild);
  72. public Column<TChild> Column { get; set; }
  73. public IFilter GetFilter(Entity parent)
  74. {
  75. return new Filter<TChild>(Column).IsEqualTo(parent.ID);
  76. }
  77. }
  78. private class GenericRelationship<TParent, TChild> : IRelationship
  79. where TParent : Entity
  80. {
  81. public Type ParentType => typeof(TParent);
  82. public Type ChildType => typeof(TChild);
  83. public Column<TChild> Column { get; set; }
  84. public Func<TParent, object?> Func { get; set; }
  85. public IFilter GetFilter(Entity parent)
  86. {
  87. return new Filter<TChild>(Column).IsEqualTo(Func(parent as TParent));
  88. }
  89. }
  90. private readonly List<IRelationship> _relationships = new List<IRelationship>();
  91. public void Duplicate(IEnumerable<TEntity> entites) =>
  92. Duplicate(typeof(TEntity),
  93. new Filter<TEntity>(x => x.ID).InList(entites.Select(x => x.ID).ToArray()));
  94. private void Duplicate(Type parent, IFilter filter)
  95. {
  96. var table = ClientFactory.CreateClient(parent)
  97. .Query(filter, Columns.Local(parent));
  98. foreach (var row in table.Rows)
  99. {
  100. var update = (row.ToObject(parent) as Entity)!;
  101. var id = update.ID;
  102. update.ID = Guid.Empty;
  103. update.CommitChanges();
  104. ClientFactory.CreateClient(parent).Save(update, "Duplicated Record");
  105. foreach (var relationship in _relationships.Where(x => x.ParentType == parent))
  106. {
  107. Duplicate(relationship.ChildType, relationship.GetFilter(update));
  108. }
  109. }
  110. }
  111. public void AddChild<TParent, TChild, TParentLink>(Expression<Func<TChild, TParentLink>> childkey)
  112. where TParent : Entity, IRemotable, IPersistent
  113. where TChild : Entity, IRemotable, IPersistent
  114. where TParentLink : IEntityLink<TParent>
  115. {
  116. _relationships.Add(new EntityLinkRelationship<TParent, TChild>
  117. {
  118. Column = new Column<TChild>(CoreUtils.GetFullPropertyName(childkey, ".") + ".ID")
  119. });
  120. }
  121. public void AddChild<TParent, TChild>(Column<TChild> linkColumn, Func<TParent, object?> value)
  122. where TParent : Entity, IRemotable, IPersistent
  123. where TChild : Entity, IRemotable, IPersistent
  124. {
  125. _relationships.Add(new GenericRelationship<TParent, TChild>
  126. {
  127. Column = linkColumn,
  128. Func = value
  129. });
  130. }
  131. void IEntityDuplicator.Duplicate(IEnumerable<BaseObject> entities) => Duplicate(entities.Cast<TEntity>());
  132. }
  133. /// <summary>
  134. /// An <see cref="IProperty"/> is required if it has the <see cref="RequiredColumnAttribute"/> defined on it.<br/>
  135. /// If it is part of an <see cref="IEntityLink"/> (or <see cref="IEnclosedEntity"/>), then it is only required
  136. /// if the <see cref="IEntityLink"/> property on the parent class also has <see cref="RequiredColumnAttribute"/>.
  137. /// </summary>
  138. public class RequiredColumnAttribute : Attribute { }
  139. public abstract class Entity : BaseObject, IEntity
  140. {
  141. private bool bTaxing;
  142. //public String Name { get; set; }
  143. [TimestampEditor(Visible = Visible.Optional, Editable = Editable.Hidden)]
  144. [RequiredColumn]
  145. public virtual DateTime LastUpdate { get; set; } = DateTime.Now;
  146. [CodeEditor(Visible = Visible.Optional, Editable = Editable.Hidden)]
  147. [RequiredColumn]
  148. public string LastUpdateBy { get; set; } = ClientFactory.UserID;
  149. [NullEditor]
  150. [RequiredColumn]
  151. public virtual DateTime Created { get; set; } = DateTime.Now;
  152. [NullEditor]
  153. [RequiredColumn]
  154. public virtual string CreatedBy { get; set; } = ClientFactory.UserID;
  155. [NullEditor]
  156. [RequiredColumn]
  157. public Guid ID { get; set; } = Guid.Empty;
  158. /// <summary>
  159. /// If the entity is deleted, holds the ID of the Deletion. Otherwise, it holds Guid.Empty
  160. /// </summary>
  161. [NullEditor]
  162. [DoNotSerialize]
  163. [Obsolete]
  164. public Guid Deleted { get; set; } = Guid.Empty;
  165. public static Type ClassVersion(Type t)
  166. {
  167. //Type t = MethodBase.GetCurrentMethod().DeclaringType;
  168. var ti = t.GetTypeInfo();
  169. var interfaces = ti.GetInterfaces();
  170. if (ti.GetInterfaces().Contains(typeof(IPersistent)))
  171. {
  172. if (ti.BaseType != null)
  173. throw new Exception(t.Name + " hase no Base Type");
  174. if (ti.BaseType.Equals(typeof(Entity)))
  175. throw new Exception(t.Name + " may not derive directly from TEntity");
  176. var props = t.GetTypeInfo().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
  177. if (props.Count() > 0)
  178. throw new Exception(t.Name + "may not declare properties");
  179. }
  180. return t.GetTypeInfo().BaseType;
  181. }
  182. //[NullEditor]
  183. //public List<EntityHistory> History { get; set; }
  184. //public Entity() : base()
  185. //{
  186. // CommitChanges();
  187. //}
  188. //public Entity(Guid id) : base()
  189. //{
  190. // ID = id;
  191. // History = new List<EntityHistory>();
  192. // UserProperties = new Dictionary<string, Object>();
  193. // DataModel.InitializeEntity(this);
  194. // CheckSequence();
  195. // CommitChanges();
  196. //}
  197. public static bool IsEntityLinkValid<T, U>(Expression<Func<T, U>> expression, CoreRow arg) where U : IEntityLink
  198. {
  199. return arg.IsEntityLinkValid(expression);
  200. }
  201. /// <summary>
  202. /// Gets the ID of an entity link of an entity, doing a validity check (see <see cref="IsEntityLinkValid{T, U}(Expression{Func{T, U}}, CoreRow)"/>)
  203. /// </summary>
  204. /// <typeparam name="T">The entity type</typeparam>
  205. /// <typeparam name="U">The entity link type</typeparam>
  206. /// <param name="expression">An expression to the entity link of type <typeparamref name="U"/></param>
  207. /// <param name="arg">The row representing the entity of type <typeparamref name="T"/></param>
  208. /// <returns>The ID on the entity link, or <c>null</c> if the entity link is invalid</returns>
  209. public static Guid? EntityLinkID<T, U>(Expression<Func<T, U>> expression, CoreRow arg) where U : IEntityLink
  210. {
  211. var col = CoreUtils.GetFullPropertyName(expression, ".");
  212. var id = arg.Get<Guid>(col + ".ID");
  213. if (id != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty)
  214. return id;
  215. return null;
  216. }
  217. protected override void SetChanged(string name, object? before, object? after)
  218. {
  219. base.SetChanged(name, before, after);
  220. CheckTax(name, before, after);
  221. }
  222. private void CheckTax(string name, object? before, object? after)
  223. {
  224. if (this is ITaxable taxable && !bTaxing)
  225. {
  226. bTaxing = true;
  227. try
  228. {
  229. if (name.Equals("ExTax"))
  230. {
  231. taxable.Tax = (double)after * (taxable.TaxRate / 100.0F);
  232. taxable.IncTax = (double)after + taxable.Tax;
  233. }
  234. else if (name.Equals("TaxRate"))
  235. {
  236. taxable.Tax = taxable.ExTax * ((double)after / 100.0F);
  237. taxable.IncTax = taxable.ExTax + taxable.Tax;
  238. }
  239. else if (name.Equals("Tax"))
  240. {
  241. taxable.ExTax = taxable.IncTax - (double)after;
  242. }
  243. else if (name.Equals("IncTax"))
  244. {
  245. taxable.ExTax = (double)after / ((100.0F + taxable.TaxRate) / 100.0F);
  246. taxable.Tax = (double)after - taxable.ExTax;
  247. }
  248. }
  249. catch (Exception e)
  250. {
  251. Logger.Send(LogType.Error, "", String.Join("\n",e.Message,e.StackTrace));
  252. }
  253. bTaxing = false;
  254. }
  255. }
  256. protected override void DoPropertyChanged(string name, object? before, object? after)
  257. {
  258. if (!IsObserving())
  259. return;
  260. //CheckSequence();
  261. if (!name.Equals("LastUpdate"))
  262. LastUpdate = DateTime.Now;
  263. LastUpdateBy = ClientFactory.UserID;
  264. // This doesn;t work - keeps being updated to current date
  265. // Created => null ::Set ID = guid.empty -> now :: any other change -> unchanged!
  266. // Moved to Create(), should not simply be overwritten on deserialise from json
  267. //if (Created.Equals(DateTime.MinValue))
  268. //{
  269. // Created = DateTime.Now;
  270. // CreatedBy = ClientFactory.UserID;
  271. //}
  272. }
  273. }
  274. public interface ILicense<TLicenseToken> where TLicenseToken : LicenseToken
  275. {
  276. }
  277. public interface IPersistent
  278. {
  279. }
  280. public interface IRemotable
  281. {
  282. }
  283. //public interface IRemoteQuery
  284. //{
  285. //}
  286. //public interface IRemoteUpdate
  287. //{
  288. //}
  289. //public interface IRemoteDelete
  290. //{
  291. //}
  292. public interface ISequenceable
  293. {
  294. long Sequence { get; set; }
  295. }
  296. public interface IAutoIncrement<T, TType>
  297. {
  298. Expression<Func<T, TType>> AutoIncrementField();
  299. Filter<T>? AutoIncrementFilter();
  300. }
  301. public interface INumericAutoIncrement<T> : IAutoIncrement<T, int>
  302. {
  303. }
  304. public interface IStringAutoIncrement
  305. {
  306. string AutoIncrementPrefix();
  307. string AutoIncrementFormat();
  308. }
  309. public interface IStringAutoIncrement<T> : IAutoIncrement<T, string>, IStringAutoIncrement
  310. {
  311. }
  312. /// <summary>
  313. /// Used to flag an entity as exhibiting the properties of a ManyToMany relationship, allowing PRS to auto-generate things like grids and datamodels based on
  314. /// entity relationships.
  315. /// </summary>
  316. /// <remarks>
  317. /// This will cause a ManyToMany grid of <typeparamref name="TRight"/> to appear on all <typeparamref name="TLeft"/> editors.
  318. /// Hence, if one wishes to cause both grids to appear (that is, for <typeparamref name="TLeft"/> to appear for <typeparamref name="TRight"/> <i>and</i>
  319. /// vice versa, one must flag the entity with both <c>IManyToMany&lt;<typeparamref name="TLeft"/>, <typeparamref name="TRight"/>&gt;</c> and
  320. /// <c>IManyToMany&lt;<typeparamref name="TRight"/>, <typeparamref name="TLeft"/>&gt;</c>.
  321. /// </remarks>
  322. /// <typeparam name="TLeft"></typeparam>
  323. /// <typeparam name="TRight"></typeparam>
  324. public interface IManyToMany<TLeft, TRight> where TLeft : Entity where TRight : Entity
  325. {
  326. }
  327. public interface IOneToMany<TOne> where TOne : Entity
  328. {
  329. }
  330. public static class EntityFactory
  331. {
  332. public delegate object ObjectActivator(params object[] args);
  333. private static readonly Dictionary<Type, ObjectActivator> _cache = new Dictionary<Type, ObjectActivator>();
  334. public static ObjectActivator GetActivator<T>(ConstructorInfo ctor)
  335. {
  336. var type = ctor.DeclaringType;
  337. var paramsInfo = ctor.GetParameters();
  338. //create a single param of type object[]
  339. var param =
  340. Expression.Parameter(typeof(object[]), "args");
  341. var argsExp =
  342. new Expression[paramsInfo.Length];
  343. //pick each arg from the params array
  344. //and create a typed expression of them
  345. for (var i = 0; i < paramsInfo.Length; i++)
  346. {
  347. Expression index = Expression.Constant(i);
  348. var paramType = paramsInfo[i].ParameterType;
  349. Expression paramAccessorExp =
  350. Expression.ArrayIndex(param, index);
  351. Expression paramCastExp =
  352. Expression.Convert(paramAccessorExp, paramType);
  353. argsExp[i] = paramCastExp;
  354. }
  355. //make a NewExpression that calls the
  356. //ctor with the args we just created
  357. var newExp = Expression.New(ctor, argsExp);
  358. //create a lambda with the New
  359. //Expression as body and our param object[] as arg
  360. var lambda =
  361. Expression.Lambda(typeof(ObjectActivator), newExp, param);
  362. //compile it
  363. var compiled = (ObjectActivator)lambda.Compile();
  364. return compiled;
  365. }
  366. public static T CreateEntity<T>() where T : BaseObject
  367. {
  368. if (!_cache.ContainsKey(typeof(T)))
  369. {
  370. var ctor = typeof(T).GetConstructors().First();
  371. _cache[typeof(T)] = GetActivator<T>(ctor);
  372. }
  373. var createdActivator = _cache[typeof(T)];
  374. return (T)createdActivator();
  375. }
  376. public static object CreateEntity(Type type)
  377. {
  378. if (!_cache.ContainsKey(type))
  379. {
  380. var ctor = type.GetConstructors().First();
  381. var activator = typeof(EntityFactory).GetMethod("GetActivator").MakeGenericMethod(type);
  382. _cache[type] = (ObjectActivator)activator.Invoke(null, new object[] { ctor });
  383. }
  384. var createdActivator = _cache[type];
  385. return createdActivator();
  386. }
  387. }
  388. }