Entity.cs 15 KB

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