BaseObject.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. using System.Runtime.CompilerServices;
  10. using System.Runtime.Serialization;
  11. //using PropertyChanged;
  12. namespace InABox.Core
  13. {
  14. public class DoNotSerialize : Attribute
  15. {
  16. }
  17. public interface IBaseObject
  18. {
  19. public bool IsChanged();
  20. public void CancelChanges();
  21. public void CommitChanges();
  22. public bool IsObserving();
  23. public void SetObserving(bool active);
  24. }
  25. /// <summary>
  26. /// Observable object with INotifyPropertyChanged implemented
  27. /// </summary>
  28. public abstract class BaseObject : INotifyPropertyChanged, IBaseObject
  29. {
  30. public BaseObject()
  31. {
  32. SetObserving(false);
  33. DatabaseSchema.InitializeSubObjects(this);
  34. Init();
  35. SetObserving(true);
  36. }
  37. [OnDeserializing]
  38. internal void OnDeserializingMethod(StreamingContext context)
  39. {
  40. if (_observing)
  41. SetObserving(false);
  42. }
  43. [OnDeserialized]
  44. internal void OnDeserializedMethod(StreamingContext context)
  45. {
  46. if (!_observing)
  47. SetObserving(true);
  48. }
  49. protected virtual void Init()
  50. {
  51. CheckOriginalValues();
  52. LoadedColumns = new HashSet<string>();
  53. UserProperties = new UserProperties();
  54. //UserProperties.ParentType = this.GetType();
  55. DatabaseSchema.InitializeObject(this);
  56. UserProperties.OnPropertyChanged += (o, n, b, a) =>
  57. {
  58. if (IsObserving())
  59. OnPropertyChanged(n, b, a);
  60. };
  61. CheckSequence();
  62. }
  63. private void CheckSequence()
  64. {
  65. if (this is ISequenceable seq && seq.Sequence <= 0)
  66. {
  67. seq.Sequence = CoreUtils.GenerateSequence();
  68. }
  69. }
  70. #region Observing Flags
  71. public static bool GlobalObserving = true;
  72. private bool _observing = true;
  73. public bool IsObserving()
  74. {
  75. return GlobalObserving && _observing;
  76. }
  77. public void SetObserving(bool active)
  78. {
  79. bApplyingChanges = true;
  80. _observing = active;
  81. foreach (var oo in DatabaseSchema.GetSubObjects(this))
  82. oo.SetObserving(active);
  83. bApplyingChanges = false;
  84. }
  85. protected virtual void DoPropertyChanged(string name, object? before, object? after)
  86. {
  87. }
  88. public event PropertyChangedEventHandler? PropertyChanged;
  89. private bool bApplyingChanges;
  90. private bool bChanged;
  91. [DoNotPersist]
  92. public ConcurrentDictionary<string, object?> OriginalValues { get; set; }
  93. [DoNotPersist]
  94. [DoNotSerialize]
  95. public HashSet<string> LoadedColumns { get; set; }
  96. protected virtual void SetChanged(string name, object? before, object? after)
  97. {
  98. bChanged = true;
  99. if (!bApplyingChanges)
  100. {
  101. try
  102. {
  103. bApplyingChanges = true;
  104. DoPropertyChanged(name, before, after);
  105. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  106. }
  107. catch (Exception e)
  108. {
  109. }
  110. bApplyingChanges = false;
  111. }
  112. }
  113. private bool QueryChanged()
  114. {
  115. CheckOriginalValues();
  116. if (OriginalValues.Count > 0)
  117. return true;
  118. foreach (var oo in DatabaseSchema.GetSubObjects(this))
  119. if (oo.IsChanged())
  120. return true;
  121. return false;
  122. }
  123. private bool HasChanged(object? before, object? after)
  124. {
  125. if ((before == null || before.Equals("")) && (after == null || after.Equals("")))
  126. return false;
  127. if (before == null != (after == null))
  128. return true;
  129. if (!before!.GetType().Equals(after!.GetType()))
  130. return true;
  131. if (before is string[] && after is string[])
  132. return !(before as string[]).SequenceEqual(after as string[]);
  133. return !before.Equals(after);
  134. }
  135. public void OnPropertyChanged(string name, object? before, object? after)
  136. {
  137. if (!IsObserving())
  138. return;
  139. if (name.Equals("IsChanged"))
  140. return;
  141. if (name.Equals("Observing"))
  142. return;
  143. if (name.Equals("OriginalValues"))
  144. return;
  145. LoadedColumns.Add(name);
  146. if (!HasChanged(before, after))
  147. return;
  148. CheckOriginalValues();
  149. if (!OriginalValues.ContainsKey(name))
  150. OriginalValues[name] = before;
  151. SetChanged(name, before, after);
  152. }
  153. private void CheckOriginalValues()
  154. {
  155. if (OriginalValues == null)
  156. {
  157. var bObserving = _observing;
  158. _observing = false;
  159. OriginalValues = new ConcurrentDictionary<string, object?>();
  160. _observing = bObserving;
  161. }
  162. }
  163. public bool IsChanged()
  164. {
  165. return IsObserving() ? QueryChanged() : bChanged;
  166. }
  167. public void CancelChanges()
  168. {
  169. bApplyingChanges = true;
  170. var bObs = IsObserving();
  171. SetObserving(false);
  172. CheckOriginalValues();
  173. foreach (var key in OriginalValues.Keys.ToArray())
  174. {
  175. try
  176. {
  177. var prop = key.Contains(".")
  178. ? CoreUtils.GetProperty(GetType(),key)
  179. : GetType().GetRuntimeProperty(key);
  180. if(prop != null)
  181. {
  182. if (prop.SetMethod != null)
  183. {
  184. var val = OriginalValues[key];
  185. // Funky 64bit stuff here?
  186. if (prop.PropertyType == typeof(int) && val?.GetType() == typeof(long))
  187. val = Convert.ToInt32(val);
  188. prop.SetValue(this, val);
  189. }
  190. }
  191. else if (UserProperties.ContainsKey(key))
  192. {
  193. UserProperties[key] = OriginalValues[key];
  194. }
  195. else
  196. {
  197. Logger.Send(LogType.Error, "", $"'{key}' is neither a runtime property nor custom property of {GetType().Name}");
  198. }
  199. }
  200. catch (Exception e)
  201. {
  202. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  203. }
  204. }
  205. OriginalValues.Clear();
  206. bChanged = false;
  207. foreach (var oo in DatabaseSchema.GetSubObjects(this)) oo.CancelChanges();
  208. SetObserving(bObs);
  209. bApplyingChanges = false;
  210. }
  211. public void CommitChanges()
  212. {
  213. bApplyingChanges = true;
  214. CheckOriginalValues();
  215. OriginalValues.Clear();
  216. bChanged = false;
  217. foreach (var oo in DatabaseSchema.GetSubObjects(this))
  218. oo.CommitChanges();
  219. bApplyingChanges = false;
  220. }
  221. public string ChangedValues()
  222. {
  223. var result = new List<string>();
  224. var type = GetType();
  225. try
  226. {
  227. CheckOriginalValues();
  228. foreach (var key in OriginalValues.Keys)
  229. try
  230. {
  231. if (UserProperties.ContainsKey(key))
  232. {
  233. var obj = UserProperties[key];
  234. result.Add(string.Format("[{0} = {1}]", key, obj != null ? obj.ToString() : "null"));
  235. }
  236. else
  237. {
  238. var prop = DatabaseSchema.Property(type, key);// GetType().GetProperty(key);
  239. if (prop is StandardProperty standard && standard.Loggable != null)
  240. {
  241. /*var attribute = //prop.GetCustomAttributes(typeof(LoggablePropertyAttribute), true).FirstOrDefault();
  242. if (attribute != null)
  243. {*/
  244. //var lpa = (LoggablePropertyAttribute)attribute;
  245. var format = standard.Loggable.Format;
  246. var value = standard.Getter()(this);
  247. if (string.IsNullOrEmpty(format))
  248. result.Add($"[{key} = {value}]");
  249. else
  250. result.Add(string.Format("[{0} = {1:" + format + "}]", key, value));
  251. //}
  252. }
  253. }
  254. }
  255. catch (Exception e)
  256. {
  257. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  258. }
  259. }
  260. catch (Exception e)
  261. {
  262. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  263. }
  264. return string.Join(" ", result);
  265. }
  266. #endregion
  267. #region UserProperties
  268. private UserProperties _userproperties;
  269. public UserProperties UserProperties
  270. {
  271. get
  272. {
  273. CheckUserProperties();
  274. return _userproperties;
  275. }
  276. set
  277. {
  278. _userproperties = value;
  279. CheckUserProperties();
  280. }
  281. }
  282. private static Dictionary<string, object?>? DefaultProperties;
  283. private void CheckUserProperties()
  284. {
  285. if (_userproperties == null)
  286. {
  287. _userproperties = new UserProperties();
  288. if (DefaultProperties == null)
  289. {
  290. DefaultProperties = new Dictionary<string, object?>();
  291. var props = DatabaseSchema.Properties(GetType()).Where(x => x is CustomProperty).ToArray();
  292. foreach (var field in props)
  293. DefaultProperties[field.Name] = DatabaseSchema.DefaultValue(field.PropertyType);
  294. }
  295. _userproperties.LoadFromDictionary(DefaultProperties);
  296. }
  297. }
  298. #endregion
  299. }
  300. public static class BaseObjectExtensions
  301. {
  302. public static bool HasColumn<T>(this T sender, string column)
  303. where T : BaseObject
  304. {
  305. return sender.LoadedColumns.Contains(column);
  306. }
  307. public static bool HasColumn<T, TType>(this T sender, Expression<Func<T, TType>> column)
  308. where T : BaseObject
  309. {
  310. return sender.LoadedColumns.Contains(CoreUtils.GetFullPropertyName(column, "."));
  311. }
  312. public static bool HasOriginalValue<T>(this T sender, string propertyname) where T : BaseObject
  313. {
  314. return sender.OriginalValues != null && sender.OriginalValues.ContainsKey(propertyname);
  315. }
  316. public static TType GetOriginalValue<T, TType>(this T sender, string propertyname) where T : BaseObject
  317. {
  318. return sender.OriginalValues != null && sender.OriginalValues.ContainsKey(propertyname)
  319. ? (TType)CoreUtils.ChangeType(sender.OriginalValues[propertyname], typeof(TType))
  320. : default;
  321. }
  322. public static Dictionary<string, object> GetValues<T>(this T sender, bool all, bool followlinks = false) where T : BaseObject
  323. {
  324. var result = new Dictionary<string, object>();
  325. LoadValues(sender, result, "", all, false, followlinks);
  326. return result;
  327. }
  328. public static void SetValues<T>(this T sender, Dictionary<string, object> values)
  329. {
  330. foreach (var value in values)
  331. CoreUtils.SetPropertyValue(sender, value.Key, value.Value);
  332. }
  333. public static Dictionary<string, object> GetOriginaValues<T>(this T sender, bool all) where T : BaseObject
  334. {
  335. var result = new Dictionary<string, object>();
  336. LoadValues(sender, result, "", all, true);
  337. return result;
  338. }
  339. private static void LoadValues(BaseObject sender, Dictionary<string, object?> values, string prefix, bool all, bool original, bool followlinks = false)
  340. {
  341. try
  342. {
  343. var props = sender.GetType().GetProperties().Where(x =>
  344. x.GetCustomAttribute<DoNotSerialize>() == null
  345. && x.GetCustomAttribute<DoNotPersist>() == null
  346. && x.GetCustomAttribute<AggregateAttribute>() == null
  347. && x.GetCustomAttribute<FormulaAttribute>() == null
  348. && x.GetCustomAttribute<ConditionAttribute>() == null
  349. && x.GetCustomAttribute<ChildEntityAttribute>() == null
  350. && x.CanWrite);
  351. foreach (var prop in props)
  352. if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnclosedEntity)))
  353. {
  354. var child = prop.GetValue(sender) as BaseObject;
  355. if (child != null)
  356. LoadValues(child, values, string.IsNullOrWhiteSpace(prefix) ? prop.Name : prefix + "." + prop.Name, all, original, followlinks);
  357. }
  358. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IEntityLink)))
  359. {
  360. var child = prop.GetValue(sender) as BaseObject;
  361. if (child != null)
  362. {
  363. if (all)
  364. {
  365. values[string.IsNullOrWhiteSpace(prefix) ? prop.Name + ".ID" : prefix + "." + prop.Name + ".ID"] =
  366. original
  367. ? child.OriginalValues.ContainsKey("ID") ? child.OriginalValues["ID"] : Guid.Empty
  368. : CoreUtils.GetPropertyValue(child, "ID");
  369. }
  370. else
  371. {
  372. if (child.HasOriginalValue("ID"))
  373. values[string.IsNullOrWhiteSpace(prefix) ? prop.Name + ".ID" : prefix + "." + prop.Name + ".ID"] =
  374. original
  375. ? child.OriginalValues.ContainsKey("ID") ? child.OriginalValues["ID"] : Guid.Empty
  376. : CoreUtils.GetPropertyValue(child, "ID");
  377. }
  378. if (followlinks)
  379. LoadValues(child, values, string.IsNullOrWhiteSpace(prefix) ? prop.Name : prefix + "." + prop.Name, all, original, followlinks);
  380. }
  381. }
  382. else if (prop.PropertyType.GetInterfaces().Contains(typeof(IBaseObject)))
  383. {
  384. var child = prop.GetValue(sender) as IBaseObject;
  385. if (child != null)
  386. {
  387. if (all)
  388. {
  389. values[string.IsNullOrWhiteSpace(prefix) ? prop.Name : prefix + "." + prop.Name] = child;
  390. }
  391. else
  392. {
  393. if (child.IsChanged())
  394. values[string.IsNullOrWhiteSpace(prefix) ? prop.Name : prefix + "." + prop.Name] = child;
  395. }
  396. }
  397. }
  398. else
  399. {
  400. if (all)
  401. {
  402. values[string.IsNullOrWhiteSpace(prefix) ? prop.Name : prefix + "." + prop.Name] =
  403. original
  404. ? sender.OriginalValues.ContainsKey(prop.Name) ? sender.OriginalValues[prop.Name] : prop.PropertyType.GetDefault()
  405. : prop.GetValue(sender);
  406. }
  407. else
  408. {
  409. if (sender.HasOriginalValue(prop.Name))
  410. values[string.IsNullOrWhiteSpace(prefix) ? prop.Name : prefix + "." + prop.Name] =
  411. original
  412. ? sender.OriginalValues.ContainsKey(prop.Name)
  413. ? sender.OriginalValues[prop.Name]
  414. : prop.PropertyType.GetDefault()
  415. : prop.GetValue(sender);
  416. }
  417. }
  418. var iprops = DatabaseSchema.Properties(sender.GetType()).Where(x => x is CustomProperty);
  419. foreach (var iprop in iprops)
  420. if (all || sender.HasOriginalValue(iprop.Name))
  421. values[string.IsNullOrWhiteSpace(prefix) ? iprop.Name : prefix + "." + iprop.Name] =
  422. original
  423. ? sender.OriginalValues.ContainsKey(iprop.Name)
  424. ? sender.OriginalValues[iprop.Name]
  425. : iprop.PropertyType.GetDefault()
  426. : sender.UserProperties[iprop.Name];
  427. }
  428. catch (Exception e)
  429. {
  430. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  431. }
  432. }
  433. public static List<string> Compare<T>(this T sender, Dictionary<string, object> original) where T : BaseObject
  434. {
  435. var result = new List<string>();
  436. var current = GetValues(sender, true);
  437. foreach (var key in current.Keys)
  438. if (original.ContainsKey(key))
  439. {
  440. if (current[key] == null)
  441. {
  442. if (original[key] != null)
  443. result.Add(string.Format("[{0}] has changed from [{1}] to [{2}]", key, original[key], current[key]));
  444. }
  445. else
  446. {
  447. if (!current[key].Equals(original[key]))
  448. result.Add(string.Format("[{0}] has changed from [{1}] to [{2}]", key, original[key], current[key]));
  449. }
  450. }
  451. else
  452. {
  453. result.Add(string.Format("[{0}] not present in previous dictionary!", key));
  454. }
  455. return result;
  456. }
  457. public static bool GetValue<T,TType>(this T sender, Expression<Func<T,TType>> property, bool original, out TType result) where T : BaseObject
  458. {
  459. if (sender.HasOriginalValue<T, TType>(property))
  460. {
  461. if (original)
  462. result = sender.GetOriginalValue<T, TType>(property);
  463. else
  464. {
  465. var expr = property.Compile();
  466. result = expr(sender);
  467. }
  468. return true;
  469. }
  470. result = default(TType);
  471. return false;
  472. }
  473. public static void SetOriginalValue<T, TType>(this T sender, string propertyname, TType value) where T : BaseObject
  474. {
  475. sender.OriginalValues[propertyname] = value;
  476. }
  477. public static bool HasOriginalValue<T, TType>(this T sender, Expression<Func<T, TType>> property) where T : BaseObject
  478. {
  479. //var prop = ((MemberExpression)property.Body).Member as PropertyInfo;
  480. String propname = CoreUtils.GetFullPropertyName(property, ".");
  481. return !String.IsNullOrWhiteSpace(propname) && sender.OriginalValues != null && sender.OriginalValues.ContainsKey(propname);
  482. }
  483. public static TType GetOriginalValue<T, TType>(this T sender, Expression<Func<T, TType>> property) where T : BaseObject
  484. {
  485. var prop = ((MemberExpression)property.Body).Member as PropertyInfo;
  486. return prop != null && sender.OriginalValues != null && sender.OriginalValues.ContainsKey(prop.Name)
  487. ? (TType)CoreUtils.ChangeType(sender.OriginalValues[prop.Name], typeof(TType))
  488. : default;
  489. }
  490. public static TType GetOriginalValue<T, TType>(this T sender, Expression<Func<T, TType>> property, TType defaultValue) where T : BaseObject
  491. {
  492. var prop = ((MemberExpression)property.Body).Member as PropertyInfo;
  493. return prop != null && sender.OriginalValues != null && sender.OriginalValues.ContainsKey(prop.Name)
  494. ? (TType)CoreUtils.ChangeType(sender.OriginalValues[prop.Name], typeof(TType))
  495. : defaultValue;
  496. }
  497. public static void SetOriginalValue<T, TType>(this T sender, Expression<Func<T, TType>> property, TType value) where T : BaseObject
  498. {
  499. var prop = ((MemberExpression)property.Body).Member as PropertyInfo;
  500. sender.OriginalValues[prop.Name] = value;
  501. }
  502. }
  503. /// <summary>
  504. /// An <see cref="IProperty"/> is loggable if it has the <see cref="LoggablePropertyAttribute"/> defined on it.<br/>
  505. /// If it is part of an <see cref="IEntityLink"/>, then it is only loggable if the <see cref="IEntityLink"/> property on the parent class
  506. /// also has <see cref="LoggablePropertyAttribute"/>.
  507. /// </summary>
  508. public class LoggablePropertyAttribute : Attribute
  509. {
  510. public string Format { get; set; }
  511. }
  512. }