BaseObject.cs 20 KB

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