Entity.cs 16 KB

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