Entity.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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.Create(parent).DefaultColumns(ColumnType.DataColumns));
  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)
  219. {
  220. if (bTaxing)
  221. return;
  222. bTaxing = true;
  223. try
  224. {
  225. var taxable = this as ITaxable;
  226. if (name.Equals("ExTax"))
  227. {
  228. taxable.Tax = (double)after * (taxable.TaxRate / 100.0F);
  229. taxable.IncTax = (double)after + taxable.Tax;
  230. }
  231. else if (name.Equals("TaxRate"))
  232. {
  233. taxable.Tax = taxable.ExTax * ((double)after / 100.0F);
  234. taxable.IncTax = taxable.ExTax + taxable.Tax;
  235. }
  236. else if (name.Equals("Tax"))
  237. {
  238. taxable.ExTax = taxable.IncTax - (double)after;
  239. }
  240. else if (name.Equals("IncTax"))
  241. {
  242. taxable.ExTax = (double)after / ((100.0F + taxable.TaxRate) / 100.0F);
  243. taxable.Tax = (double)after - taxable.ExTax;
  244. }
  245. }
  246. catch (Exception e)
  247. {
  248. Logger.Send(LogType.Error, "", String.Join("\n",e.Message,e.StackTrace));
  249. }
  250. bTaxing = false;
  251. }
  252. }
  253. protected override void DoPropertyChanged(string name, object? before, object? after)
  254. {
  255. if (!IsObserving())
  256. return;
  257. //CheckSequence();
  258. if (!name.Equals("LastUpdate"))
  259. LastUpdate = DateTime.Now;
  260. LastUpdateBy = ClientFactory.UserID;
  261. // This doesn;t work - keeps being updated to current date
  262. // Created => null ::Set ID = guid.empty -> now :: any other change -> unchanged!
  263. // Moved to Create(), should not simply be overwritten on deserialise from json
  264. //if (Created.Equals(DateTime.MinValue))
  265. //{
  266. // Created = DateTime.Now;
  267. // CreatedBy = ClientFactory.UserID;
  268. //}
  269. }
  270. }
  271. public interface ILicense<TLicenseToken> where TLicenseToken : LicenseToken
  272. {
  273. }
  274. public interface IPersistent
  275. {
  276. }
  277. public interface IRemotable
  278. {
  279. }
  280. //public interface IRemoteQuery
  281. //{
  282. //}
  283. //public interface IRemoteUpdate
  284. //{
  285. //}
  286. //public interface IRemoteDelete
  287. //{
  288. //}
  289. public interface ISequenceable
  290. {
  291. long Sequence { get; set; }
  292. }
  293. public interface IAutoIncrement<T, TType>
  294. {
  295. Expression<Func<T, TType>> AutoIncrementField();
  296. Filter<T>? AutoIncrementFilter();
  297. }
  298. public interface INumericAutoIncrement<T> : IAutoIncrement<T, int>
  299. {
  300. }
  301. public interface IStringAutoIncrement
  302. {
  303. string AutoIncrementPrefix();
  304. string AutoIncrementFormat();
  305. }
  306. public interface IStringAutoIncrement<T> : IAutoIncrement<T, string>, IStringAutoIncrement
  307. {
  308. }
  309. /// <summary>
  310. /// 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
  311. /// entity relationships.
  312. /// </summary>
  313. /// <remarks>
  314. /// This will cause a ManyToMany grid of <typeparamref name="TRight"/> to appear on all <typeparamref name="TLeft"/> editors.
  315. /// 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>
  316. /// vice versa, one must flag the entity with both <c>IManyToMany&lt;<typeparamref name="TLeft"/>, <typeparamref name="TRight"/>&gt;</c> and
  317. /// <c>IManyToMany&lt;<typeparamref name="TRight"/>, <typeparamref name="TLeft"/>&gt;</c>.
  318. /// </remarks>
  319. /// <typeparam name="TLeft"></typeparam>
  320. /// <typeparam name="TRight"></typeparam>
  321. public interface IManyToMany<TLeft, TRight> where TLeft : Entity where TRight : Entity
  322. {
  323. }
  324. public interface IOneToMany<TOne> where TOne : Entity
  325. {
  326. }
  327. public static class EntityFactory
  328. {
  329. public delegate object ObjectActivator(params object[] args);
  330. private static readonly Dictionary<Type, ObjectActivator> _cache = new Dictionary<Type, ObjectActivator>();
  331. public static ObjectActivator GetActivator<T>(ConstructorInfo ctor)
  332. {
  333. var type = ctor.DeclaringType;
  334. var paramsInfo = ctor.GetParameters();
  335. //create a single param of type object[]
  336. var param =
  337. Expression.Parameter(typeof(object[]), "args");
  338. var argsExp =
  339. new Expression[paramsInfo.Length];
  340. //pick each arg from the params array
  341. //and create a typed expression of them
  342. for (var i = 0; i < paramsInfo.Length; i++)
  343. {
  344. Expression index = Expression.Constant(i);
  345. var paramType = paramsInfo[i].ParameterType;
  346. Expression paramAccessorExp =
  347. Expression.ArrayIndex(param, index);
  348. Expression paramCastExp =
  349. Expression.Convert(paramAccessorExp, paramType);
  350. argsExp[i] = paramCastExp;
  351. }
  352. //make a NewExpression that calls the
  353. //ctor with the args we just created
  354. var newExp = Expression.New(ctor, argsExp);
  355. //create a lambda with the New
  356. //Expression as body and our param object[] as arg
  357. var lambda =
  358. Expression.Lambda(typeof(ObjectActivator), newExp, param);
  359. //compile it
  360. var compiled = (ObjectActivator)lambda.Compile();
  361. return compiled;
  362. }
  363. public static T CreateEntity<T>() where T : BaseObject
  364. {
  365. if (!_cache.ContainsKey(typeof(T)))
  366. {
  367. var ctor = typeof(T).GetConstructors().First();
  368. _cache[typeof(T)] = GetActivator<T>(ctor);
  369. }
  370. var createdActivator = _cache[typeof(T)];
  371. return (T)createdActivator();
  372. }
  373. public static object CreateEntity(Type type)
  374. {
  375. if (!_cache.ContainsKey(type))
  376. {
  377. var ctor = type.GetConstructors().First();
  378. var activator = typeof(EntityFactory).GetMethod("GetActivator").MakeGenericMethod(type);
  379. _cache[type] = (ObjectActivator)activator.Invoke(null, new object[] { ctor });
  380. }
  381. var createdActivator = _cache[type];
  382. return createdActivator();
  383. }
  384. }
  385. }