Entity.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 IEnclosedEntity
  17. {
  18. }
  19. public interface IEntity
  20. {
  21. Guid ID { get; set; }
  22. Guid Deleted { get; set; }
  23. bool IsChanged();
  24. }
  25. public interface ITaxable
  26. {
  27. double ExTax { get; set; }
  28. double TaxRate { get; set; }
  29. double Tax { get; set; }
  30. double IncTax { get; set; }
  31. }
  32. public interface IIssues
  33. {
  34. string Issues { get; set; }
  35. }
  36. public interface IExportable
  37. {
  38. }
  39. public interface IImportable
  40. {
  41. }
  42. public interface IMergeable
  43. {
  44. }
  45. public interface ISecure { }
  46. public interface IDuplicatable
  47. {
  48. IEntityDuplicator GetDuplicator();
  49. }
  50. public interface IEntityDuplicator
  51. {
  52. //void Duplicate(IFilter filter);
  53. void Duplicate(IEnumerable<BaseObject> entities);
  54. }
  55. public class EntityDuplicator<TEntity> : IEntityDuplicator where TEntity : Entity, IRemotable, IPersistent
  56. {
  57. private readonly List<Tuple<Type, Type, Expression>> _relationships = new List<Tuple<Type, Type, Expression>>();
  58. public void Duplicate(IEnumerable<TEntity> entites) =>
  59. Duplicate(typeof(TEntity),
  60. new Filter<TEntity>(x => x.ID).InList(entites.Select(x => x.ID).ToArray()));
  61. public void Duplicate(IFilter filter)
  62. {
  63. Duplicate(typeof(TEntity), filter);
  64. }
  65. private void Duplicate(Type parent, IFilter filter)
  66. {
  67. var table = ClientFactory.CreateClient(parent).Query(filter);
  68. foreach (var row in table.Rows)
  69. {
  70. var update = (row.ToObject(parent) as Entity)!;
  71. var id = update.ID;
  72. update.ID = Guid.Empty;
  73. update.CommitChanges();
  74. ClientFactory.CreateClient(parent).Save(update, "Duplicated Record");
  75. foreach (var relationship in _relationships.Where(x => x.Item1 == parent))
  76. {
  77. var filtertype = typeof(Filter<>).MakeGenericType(relationship.Item2);
  78. var newfilter = Activator.CreateInstance(filtertype) as IFilter;
  79. filter.Expression = relationship.Item3;
  80. filter.Operator = Operator.IsEqualTo;
  81. filter.Value = id;
  82. Duplicate(relationship.Item2, filter);
  83. }
  84. }
  85. }
  86. public void AddChild<TParent, TChild>(Expression<Func<TChild, IEntityLink<TParent>>> childkey) where TParent : Entity where TChild : Entity
  87. {
  88. _relationships.Add(new Tuple<Type, Type, Expression>(typeof(TParent), typeof(TChild), childkey));
  89. }
  90. void IEntityDuplicator.Duplicate(IEnumerable<BaseObject> entities) => Duplicate(entities.Cast<TEntity>());
  91. }
  92. /// <summary>
  93. /// An <see cref="IProperty"/> is required if it has the <see cref="RequiredColumnAttribute"/> defined on it.<br/>
  94. /// If it is part of an <see cref="IEntityLink"/> (or <see cref="IEnclosedEntity"/>), then it is only required
  95. /// if the <see cref="IEntityLink"/> property on the parent class also has <see cref="RequiredColumnAttribute"/>.
  96. /// </summary>
  97. public class RequiredColumnAttribute : Attribute { }
  98. public abstract class Entity : BaseObject, IEntity
  99. {
  100. private bool bTaxing;
  101. //public String Name { get; set; }
  102. [TimestampEditor(Visible = Visible.Optional, Editable = Editable.Hidden)]
  103. [RequiredColumn]
  104. public virtual DateTime LastUpdate { get; set; }
  105. [CodeEditor(Visible = Visible.Optional, Editable = Editable.Hidden)]
  106. [RequiredColumn]
  107. public string LastUpdateBy { get; set; }
  108. [NullEditor]
  109. [RequiredColumn]
  110. public virtual DateTime Created { get; set; }
  111. [NullEditor]
  112. [RequiredColumn]
  113. public virtual string CreatedBy { get; set; }
  114. [NullEditor]
  115. [RequiredColumn]
  116. public Guid ID { get; set; }
  117. /// <summary>
  118. /// If the entity is deleted, holds the ID of the Deletion. Otherwise, it holds Guid.Empty
  119. /// </summary>
  120. [NullEditor]
  121. [DoNotSerialize]
  122. public Guid Deleted { get; set; }
  123. public static Type ClassVersion(Type t)
  124. {
  125. //Type t = MethodBase.GetCurrentMethod().DeclaringType;
  126. var ti = t.GetTypeInfo();
  127. var interfaces = ti.GetInterfaces();
  128. if (ti.GetInterfaces().Contains(typeof(IPersistent)))
  129. {
  130. if (ti.BaseType != null)
  131. throw new Exception(t.Name + " hase no Base Type");
  132. if (ti.BaseType.Equals(typeof(Entity)))
  133. throw new Exception(t.Name + " may not derive directly from TEntity");
  134. var props = t.GetTypeInfo().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
  135. if (props.Count() > 0)
  136. throw new Exception(t.Name + "may not declare properties");
  137. }
  138. return t.GetTypeInfo().BaseType;
  139. }
  140. //[NullEditor]
  141. //public List<EntityHistory> History { get; set; }
  142. protected override void Init()
  143. {
  144. base.Init();
  145. ID = Guid.Empty;
  146. Deleted = Guid.Empty;
  147. Created = DateTime.Now;
  148. CreatedBy = ClientFactory.UserID;
  149. LastUpdate = DateTime.Now;
  150. LastUpdateBy = ClientFactory.UserID;
  151. //History = new List<EntityHistory>();
  152. CheckSequence();
  153. }
  154. //public Entity() : base()
  155. //{
  156. // CommitChanges();
  157. //}
  158. //public Entity(Guid id) : base()
  159. //{
  160. // ID = id;
  161. // History = new List<EntityHistory>();
  162. // UserProperties = new Dictionary<string, Object>();
  163. // DataModel.InitializeEntity(this);
  164. // CheckSequence();
  165. // CommitChanges();
  166. //}
  167. public static bool IsEntityLinkValid<T, U>(Expression<Func<T, U>> expression, CoreRow arg) where U : IEntityLink
  168. {
  169. return arg.IsEntityLinkValid(expression);
  170. }
  171. /// <summary>
  172. /// 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)"/>)
  173. /// </summary>
  174. /// <typeparam name="T">The entity type</typeparam>
  175. /// <typeparam name="U">The entity link type</typeparam>
  176. /// <param name="expression">An expression to the entity link of type <typeparamref name="U"/></param>
  177. /// <param name="arg">The row representing the entity of type <typeparamref name="T"/></param>
  178. /// <returns>The ID on the entity link, or <c>null</c> if the entity link is invalid</returns>
  179. public static Guid? EntityLinkID<T, U>(Expression<Func<T, U>> expression, CoreRow arg) where U : IEntityLink
  180. {
  181. var col = CoreUtils.GetFullPropertyName(expression, ".");
  182. var id = arg.Get<Guid>(col + ".ID");
  183. if (id != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty)
  184. return id;
  185. return null;
  186. }
  187. private void CheckSequence()
  188. {
  189. if (this is ISequenceable)
  190. {
  191. var seq = (ISequenceable)this;
  192. if (seq.Sequence <= 0)
  193. seq.Sequence = CoreUtils.GenerateSequence();
  194. }
  195. }
  196. protected override void SetChanged(string name, object before, object after)
  197. {
  198. base.SetChanged(name, before, after);
  199. CheckTax(name, before, after);
  200. }
  201. private void CheckTax(string name, object before, object after)
  202. {
  203. if (this is ITaxable)
  204. {
  205. if (bTaxing)
  206. return;
  207. bTaxing = true;
  208. var taxable = this as ITaxable;
  209. if (name.Equals("ExTax"))
  210. {
  211. taxable.Tax = (double)after * (taxable.TaxRate / 100.0F);
  212. taxable.IncTax = (double)after + taxable.Tax;
  213. }
  214. else if (name.Equals("TaxRate"))
  215. {
  216. taxable.Tax = taxable.ExTax * ((double)after / 100.0F);
  217. taxable.IncTax = taxable.ExTax + taxable.Tax;
  218. }
  219. else if (name.Equals("Tax"))
  220. {
  221. taxable.IncTax = (double)after + taxable.Tax;
  222. }
  223. else if (name.Equals("IncTax"))
  224. {
  225. taxable.ExTax = (double)after / ((100.0F + taxable.TaxRate) / 100.0F);
  226. taxable.Tax = (double)after - taxable.ExTax;
  227. }
  228. bTaxing = false;
  229. }
  230. }
  231. protected override void DoPropertyChanged(string name, object before, object after)
  232. {
  233. if (!IsObserving())
  234. return;
  235. //CheckSequence();
  236. if (!name.Equals("LastUpdate"))
  237. LastUpdate = DateTime.Now;
  238. LastUpdateBy = ClientFactory.UserID;
  239. // This doesn;t work - keeps being updated to current date
  240. // Created => null ::Set ID = guid.empty -> now :: any other change -> unchanged!
  241. // Moved to Create(), should not simply be overwritten on deserialise from json
  242. //if (Created.Equals(DateTime.MinValue))
  243. //{
  244. // Created = DateTime.Now;
  245. // CreatedBy = ClientFactory.UserID;
  246. //}
  247. }
  248. #region Linked Properties
  249. // Why?
  250. [DoNotSerialize]
  251. private static readonly List<LinkedProperty> _LinkedProperties = new List<LinkedProperty>();
  252. public virtual void LinkProperty<TEntityLink, TLinkedEntity>(Expression<Func<TEntityLink, object>> source,
  253. Expression<Func<TLinkedEntity, object>> target)
  254. {
  255. var map = LinkedProperty.Create(source, target);
  256. if (!_LinkedProperties.Any(x =>
  257. x.Source.DeclaringType.Equals(typeof(TEntityLink)) && x.Source.Name.Equals(map.Source.Name) &&
  258. x.Source.Name.Equals(map.Source.Name) && x.Target.DeclaringType.Equals(typeof(TLinkedEntity)) &&
  259. x.Target.Name.Equals(map.Target.Name)))
  260. _LinkedProperties.Add(LinkedProperty.Create(source, target));
  261. }
  262. public IEnumerable<LinkedProperty> LinkedProperties(Type type)
  263. {
  264. var result = _LinkedProperties.Where(x =>
  265. (x.Source.DeclaringType.Equals(type) || x.Source.DeclaringType.IsSubclassOf(type)) &&
  266. (x.Target.DeclaringType.Equals(GetType()) || x.Target.DeclaringType.IsSubclassOf(GetType()))
  267. );
  268. return result;
  269. }
  270. #endregion
  271. }
  272. public interface ILicense<TLicenseToken> where TLicenseToken : LicenseToken
  273. {
  274. }
  275. public interface IPersistent
  276. {
  277. }
  278. public interface IRemotable
  279. {
  280. }
  281. //public interface IRemoteQuery
  282. //{
  283. //}
  284. //public interface IRemoteUpdate
  285. //{
  286. //}
  287. //public interface IRemoteDelete
  288. //{
  289. //}
  290. public interface ISequenceable
  291. {
  292. long Sequence { get; set; }
  293. }
  294. public interface IAutoIncrement<T, TType>
  295. {
  296. Expression<Func<T, TType>> AutoIncrementField();
  297. Filter<T> AutoIncrementFilter();
  298. }
  299. public interface INumericAutoIncrement<T> : IAutoIncrement<T, int>
  300. {
  301. }
  302. public interface IStringAutoIncrement<T> : IAutoIncrement<T, string>
  303. {
  304. string AutoIncrementFormat();
  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. var activator = typeof(EntityFactory).GetMethod("GetActivator").MakeGenericMethod(typeof(T));
  366. _cache[typeof(T)] = GetActivator<T>(ctor);
  367. }
  368. var createdActivator = _cache[typeof(T)];
  369. return (T)createdActivator();
  370. }
  371. public static object CreateEntity(Type type)
  372. {
  373. if (!_cache.ContainsKey(type))
  374. {
  375. var ctor = type.GetConstructors().First();
  376. var activator = typeof(EntityFactory).GetMethod("GetActivator").MakeGenericMethod(type);
  377. _cache[type] = (ObjectActivator)activator.Invoke(null, new object[] { ctor });
  378. }
  379. var createdActivator = _cache[type];
  380. return createdActivator();
  381. }
  382. }
  383. }