Store.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. using System.Collections.Concurrent;
  2. using System.Reflection;
  3. using System.Text.RegularExpressions;
  4. using InABox.Core;
  5. using NPOI.POIFS.FileSystem;
  6. namespace InABox.Database
  7. {
  8. public static class UserTrackingCache
  9. {
  10. public static ConcurrentBag<UserTracking> Cache = new();
  11. public static DateTime Date = DateTime.MinValue;
  12. }
  13. // public interface ICacheStore<T>
  14. // {
  15. // void LoadCache();
  16. // T GetCacheItem();
  17. // void UpdateCache();
  18. // }
  19. public class Store<T> : IStore, IStore<T> where T : Entity, new()
  20. {
  21. public bool IsSubStore { get; set; }
  22. public Guid UserGuid { get; set; }
  23. public string UserID { get; set; }
  24. public Platform Platform { get; set; }
  25. public string Version { get; set; }
  26. public IProvider Provider { get; set; }
  27. public virtual void Init()
  28. {
  29. }
  30. private Type GetTrackingType(Type type)
  31. {
  32. var attr = type.GetCustomAttribute<UserTrackingAttribute>();
  33. if (attr == null)
  34. return type;
  35. if (!attr.Enabled)
  36. return null;
  37. if (attr.Parent != null)
  38. return GetTrackingType(attr.Parent);
  39. return type;
  40. }
  41. private void UpdateUserTracking(UserTrackingAction action)
  42. {
  43. if (IsSubStore)
  44. return;
  45. if (!DbFactory.IsSupported<UserTracking>())
  46. return;
  47. if (string.IsNullOrWhiteSpace(UserID))
  48. return;
  49. var type = GetTrackingType(typeof(T));
  50. if (type == null)
  51. return;
  52. if (UserTrackingCache.Date != DateTime.Today)
  53. {
  54. var tdata = Provider.Query(
  55. new Filter<UserTracking>(x => x.Date).IsEqualTo(DateTime.Today),
  56. new Columns<UserTracking>().Default(ColumnType.IncludeForeignKeys)
  57. );
  58. UserTrackingCache.Cache = new ConcurrentBag<UserTracking>(tdata.Rows.Select(x => x.ToObject<UserTracking>()));
  59. UserTrackingCache.Date = DateTime.Today;
  60. }
  61. var tracking = UserTrackingCache.Cache.FirstOrDefault(x =>
  62. Equals(x.User.ID, UserGuid) && DateTime.Equals(x.Date, DateTime.Today) && string.Equals(x.Type, type.Name));
  63. if (tracking == null)
  64. {
  65. tracking = new UserTracking();
  66. tracking.Date = DateTime.Today;
  67. tracking.Type = type.Name;
  68. tracking.User.ID = UserGuid;
  69. UserTrackingCache.Cache.Add(tracking);
  70. }
  71. tracking.Increment(DateTime.Now, action);
  72. Provider.Save(tracking);
  73. }
  74. public IStore FindSubStore(Type t)
  75. {
  76. var defType = typeof(Store<>).MakeGenericType(t);
  77. var subType = DbFactory.Stores.Where(myType => myType.IsSubclassOf(defType)).FirstOrDefault();
  78. var result = (IStore)Activator.CreateInstance(subType == null ? defType : subType);
  79. result.UserGuid = UserGuid;
  80. result.UserID = UserID;
  81. result.Platform = Platform;
  82. result.Version = Version;
  83. result.IsSubStore = true;
  84. result.Provider = Provider;
  85. return result;
  86. }
  87. public IStore<TEntity> FindSubStore<TEntity>() where TEntity : Entity, new()
  88. {
  89. var defType = typeof(Store<>).MakeGenericType(typeof(TEntity));
  90. var subType = DbFactory.Stores.Where(myType => myType.IsSubclassOf(defType)).FirstOrDefault();
  91. var store = (Store<TEntity>)Activator.CreateInstance(subType == null ? defType : subType);
  92. store.UserGuid = UserGuid;
  93. store.UserID = UserID;
  94. store.Platform = Platform;
  95. store.Version = Version;
  96. store.IsSubStore = true;
  97. store.Provider = Provider;
  98. return store;
  99. }
  100. private Filter<T>? RunScript(ScriptType type, Filter<T>? filter)
  101. {
  102. var scriptname = type.ToString();
  103. var key = string.Format("{0} {1}", typeof(T).EntityName(), scriptname);
  104. if (DbFactory.LoadedScripts.ContainsKey(key))
  105. {
  106. var script = DbFactory.LoadedScripts[key];
  107. Logger.Send(LogType.Information, UserID, string.Format("{0}.{1} Executing..", typeof(T).EntityName(), scriptname));
  108. try
  109. {
  110. script.SetValue("Store", this);
  111. script.SetValue("Filter", filter);
  112. var result = script.Execute();
  113. Logger.Send(LogType.Information, UserID, string.Format("{0}.{1} returns {2}", typeof(T).EntityName(), scriptname, result));
  114. return result ? script.GetValue("Filter") as Filter<T> : filter;
  115. }
  116. catch (Exception eExec)
  117. {
  118. Logger.Send(LogType.Information, UserID,
  119. string.Format("{0}.{1} Invoke Exception: {2}", typeof(T).EntityName(), scriptname, eExec.Message));
  120. }
  121. }
  122. return filter;
  123. }
  124. private IEnumerable<T> RunScript(ScriptType type, IEnumerable<T> entities)
  125. {
  126. var scriptname = type.ToString();
  127. var variable = typeof(T).EntityName().Split('.').Last() + "s";
  128. var key = string.Format("{0} {1}", typeof(T).EntityName(), scriptname);
  129. if (DbFactory.LoadedScripts.ContainsKey(key))
  130. {
  131. var script = DbFactory.LoadedScripts[key];
  132. script.SetValue("Store", this);
  133. script.SetValue(variable, entities);
  134. Logger.Send(LogType.Information, UserID, string.Format("{0}.{1} Executing..", typeof(T).EntityName(), scriptname));
  135. foreach (var entity in entities)
  136. try
  137. {
  138. var result = script.Execute();
  139. Logger.Send(LogType.Information, UserID,
  140. string.Format("{0}.{1} returns {2}: {3}", typeof(T).EntityName(), scriptname, result, entity));
  141. return result ? script.GetValue(variable) as IEnumerable<T> : entities;
  142. }
  143. catch (Exception eExec)
  144. {
  145. var stack = new List<string>();
  146. var eStack = eExec;
  147. while (eStack != null)
  148. {
  149. stack.Add(eStack.Message);
  150. eStack = eStack.InnerException;
  151. }
  152. stack.Reverse();
  153. var message = string.Join("\n", stack);
  154. Logger.Send(LogType.Information, UserID,
  155. string.Format("{0}.{1} Invoke Exception: {2}", typeof(T).EntityName(), scriptname, message));
  156. }
  157. }
  158. return entities;
  159. }
  160. private CoreTable RunScript(ScriptType type, CoreTable table)
  161. {
  162. var scriptname = type.ToString();
  163. var variable = typeof(T).EntityName().Split('.').Last() + "s";
  164. var key = string.Format("{0} {1}", typeof(T).EntityName(), scriptname);
  165. if (DbFactory.LoadedScripts.ContainsKey(key))
  166. {
  167. var script = DbFactory.LoadedScripts[key];
  168. Logger.Send(LogType.Information, UserID, string.Format("{0}.{1} Executing..", typeof(T).EntityName(), scriptname));
  169. try
  170. {
  171. script.SetValue("Store", this);
  172. script.SetValue(variable, table);
  173. var result = script.Execute();
  174. Logger.Send(LogType.Information, UserID,
  175. string.Format("{0}.{1} returns {2}: {3}", typeof(T).EntityName(), scriptname, result, table));
  176. return result ? script.GetValue(variable) as CoreTable : table;
  177. }
  178. catch (Exception eExec)
  179. {
  180. Logger.Send(LogType.Information, UserID,
  181. string.Format("{0}.{1} Invoke Exception: {2}", typeof(T).EntityName(), scriptname, eExec.Message));
  182. }
  183. }
  184. return table;
  185. }
  186. //#region Session / Transaction Handling
  187. //void //OpenSession(String action, bool write)
  188. //{
  189. // if (!IsSubStore)
  190. // Provider.OpenSession<T>(action, write);
  191. //}
  192. //void //CloseSession(String action, bool write)
  193. //{
  194. // if (!IsSubStore)
  195. // Provider.CloseSession<T>(action, write);
  196. //}
  197. //#endregion
  198. #region List Functions
  199. private IEnumerable<object[]> DoList(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null)
  200. {
  201. UpdateUserTracking(UserTrackingAction.Read);
  202. //last = DateTime.Now;
  203. //OpenSession("List", false);
  204. //LogStep("OpenSession");
  205. try
  206. {
  207. var flt = PrepareFilter(filter);
  208. flt = RunScript(ScriptType.BeforeQuery, flt);
  209. var result = Provider.List(flt, columns, sort);
  210. //LogStep("PopulateTable");
  211. AfterList(result);
  212. //CloseSession("List", false);
  213. //LogStep("CloseSession");
  214. return result;
  215. }
  216. catch (Exception e)
  217. {
  218. //CloseSession("List", false);
  219. throw new Exception(e.Message + "\n\n" + e.StackTrace + "\n");
  220. }
  221. }
  222. public IEnumerable<object[]> List(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null)
  223. {
  224. return DoList(filter, columns, sort);
  225. }
  226. public IEnumerable<object[]> List(Filter<Entity>? filter = null, Columns<Entity>? columns = null, SortOrder<Entity>? sort = null)
  227. {
  228. return DoList((Filter<T>?)filter, (Columns<T>)columns, (SortOrder<T>)sort);
  229. }
  230. protected virtual void AfterList(IEnumerable<object[]> data)
  231. {
  232. }
  233. #endregion
  234. #region Query Functions
  235. protected virtual CoreTable OnQuery(Filter<T>? filter, Columns<T>? columns, SortOrder<T>? sort)
  236. {
  237. return Provider.Query(filter, columns, sort);
  238. }
  239. private CoreTable DoQuery(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null)
  240. {
  241. UpdateUserTracking(UserTrackingAction.Read);
  242. //last = DateTime.Now;
  243. //OpenSession("Query", false);
  244. //LogStep("OpenSession");
  245. try
  246. {
  247. var flt = PrepareFilter(filter);
  248. flt = RunScript(ScriptType.BeforeQuery, flt);
  249. var result = OnQuery(filter, columns, sort);
  250. //LogStep("PopulateTable");
  251. AfterQuery(result);
  252. result = RunScript(ScriptType.AfterQuery, result);
  253. //CloseSession("Query", false);
  254. //LogStep("CloseSession");
  255. return result;
  256. }
  257. catch (Exception e)
  258. {
  259. //CloseSession("Query", false);
  260. throw new Exception(e.Message + "\n\n" + e.StackTrace + "\n");
  261. }
  262. }
  263. public CoreTable Query(Filter<T>? filter = null, Columns<T>? columns = null, SortOrder<T>? sort = null)
  264. {
  265. return DoQuery(filter, columns, sort);
  266. }
  267. public CoreTable Query(Filter<Entity>? filter = null, Columns<Entity>? columns = null, SortOrder<Entity>? sort = null)
  268. {
  269. return DoQuery((Filter<T>?)filter, (Columns<T>)columns, (SortOrder<T>)sort);
  270. }
  271. public CoreTable Query(IFilter? filter = null, IColumns? columns = null, ISortOrder? sort = null)
  272. {
  273. return DoQuery(filter as Filter<T>, columns as Columns<T>, sort as SortOrder<T>);
  274. }
  275. protected virtual void AfterQuery(CoreTable data)
  276. {
  277. }
  278. #endregion
  279. #region Load Functions
  280. protected virtual Filter<T>? PrepareFilter(Filter<T>? filter)
  281. {
  282. return filter;
  283. }
  284. private T[] DoLoad(Filter<T>? filter = null, SortOrder<T>? sort = null)
  285. {
  286. UpdateUserTracking(UserTrackingAction.Read);
  287. //OpenSession("Load", false);
  288. T[] results = null;
  289. try
  290. {
  291. var flt = PrepareFilter(filter);
  292. flt = RunScript(ScriptType.BeforeQuery, flt);
  293. results = Provider.Load(flt, sort);
  294. AfterLoad(results);
  295. //CloseSession("Load", false);
  296. results = RunScript(ScriptType.AfterLoad, results) as T[];
  297. return results;
  298. }
  299. catch (Exception e)
  300. {
  301. //CloseSession("Load", false);
  302. throw new Exception(e.Message + "\n\n" + e.StackTrace + "\n");
  303. }
  304. }
  305. public Entity[] Load(Filter<Entity>? filter = null, SortOrder<Entity>? sort = null)
  306. {
  307. return DoLoad((Filter<T>?)filter, sort != null ? (SortOrder<T>)sort : null);
  308. }
  309. public T[] Load(Filter<T>? filter = null, SortOrder<T>? sort = null)
  310. {
  311. return DoLoad(filter, sort);
  312. }
  313. protected virtual void AfterLoad(IEnumerable<T> items)
  314. {
  315. foreach (var item in items)
  316. item.SetObserving(true);
  317. }
  318. #endregion
  319. #region Saving Functions
  320. private static readonly Regex IsNumeric = new(@"^\d+$");
  321. private void CheckAutoIncrement(params T[] entities)
  322. {
  323. if (ProcessNumericAutoInc(entities))
  324. return;
  325. ProcessStringAutoIncrement(entities);
  326. }
  327. //public static string AutoIncrementPrefix { get; set; }
  328. private bool ProcessStringAutoIncrement(params T[] entities)
  329. {
  330. if (!entities.Any())
  331. return false;
  332. if (entities.First() is IStringAutoIncrement<T> autoinc)
  333. {
  334. var prefix = autoinc.AutoIncrementPrefix() ?? "";
  335. var prop = CoreUtils.GetPropertyFromExpression<T, string>(autoinc.AutoIncrementField());
  336. var requiredEntities = entities.Where(x =>
  337. {
  338. return (prop.GetValue(x) as string).IsNullOrWhiteSpace() && (x.ID == Guid.Empty || x.HasOriginalValue(prop.Name));
  339. }).ToList();
  340. if (requiredEntities.Count > 0)
  341. {
  342. var filter = new Filter<T>(prop.Name).IsGreaterThanOrEqualTo(String.Format("{0}0",prefix))
  343. .And(prop.Name).IsLessThanOrEqualTo(String.Format("{0}9999999999", prefix));
  344. var filter2 = autoinc.AutoIncrementFilter();
  345. if (filter2 != null)
  346. filter = filter.And(filter2);
  347. var newvalue = 0;
  348. var row = Provider.Query(
  349. filter,
  350. new Columns<T>(new[] { prop.Name }),
  351. new SortOrder<T>(prop.Name, SortDirection.Descending),
  352. 1
  353. ).Rows.FirstOrDefault();
  354. if (row != null)
  355. {
  356. var id = row.Get<string>(prop.Name);
  357. if (!string.IsNullOrWhiteSpace(prefix))
  358. id = id.Substring(prefix.Length);
  359. id = new string(id.Where(c => char.IsDigit(c)).ToArray());
  360. int.TryParse(id, out newvalue);
  361. }
  362. foreach (var entity in requiredEntities)
  363. {
  364. newvalue++;
  365. prop.SetValue(entity, prefix + string.Format(autoinc.AutoIncrementFormat(), newvalue));
  366. }
  367. return true;
  368. }
  369. }
  370. return false;
  371. }
  372. private bool ProcessNumericAutoInc(params T[] entities)
  373. {
  374. if (!entities.Any())
  375. return false;
  376. if (entities.First() is INumericAutoIncrement<T> autoinc)
  377. {
  378. var prop = CoreUtils.GetPropertyFromExpression(autoinc.AutoIncrementField());
  379. var requiredEntities = entities.Where(x =>
  380. {
  381. return object.Equals(prop.GetValue(x), 0) && (x.ID == Guid.Empty || x.HasOriginalValue(prop.Name));
  382. }).ToList();
  383. if (requiredEntities.Count > 0)
  384. {
  385. var row = Provider.Query(
  386. autoinc.AutoIncrementFilter(),
  387. new Columns<T>(new[] { prop.Name }),
  388. new SortOrder<T>(prop.Name,SortDirection.Descending),
  389. 1
  390. ).Rows.FirstOrDefault();
  391. int newvalue = row != null ? row.Get<int>(prop.Name) : 0;
  392. foreach (var entity in requiredEntities)
  393. {
  394. newvalue++;
  395. prop.SetValue(entity, newvalue);
  396. }
  397. return true;
  398. }
  399. }
  400. return false;
  401. }
  402. protected virtual void BeforeSave(T entity)
  403. {
  404. // Check for (a) blank code fields and (b) duplicate codes
  405. // There may be more than one code on an entity (why would you do this?)
  406. // so it's a bit trickier that I would hope
  407. Filter<T> codes = null;
  408. var columns = new Columns<T>(x => x.ID);
  409. var props = CoreUtils.PropertyList(typeof(T), x => x.GetCustomAttributes<UniqueCodeEditor>().Any(), true);
  410. foreach (var key in props.Keys)
  411. if (entity.HasOriginalValue(key) || entity.ID == Guid.Empty)
  412. {
  413. var code = CoreUtils.GetPropertyValue(entity, key) as string;
  414. if (string.IsNullOrWhiteSpace(code))
  415. throw new NullCodeException(typeof(T), key);
  416. var expr = CoreUtils.GetPropertyExpression<T, object>(key); //CoreUtils.GetMemberExpression(typeof(T),key)
  417. codes = codes == null ? new Filter<T>(expr).IsEqualTo(code) : codes.Or(expr).IsEqualTo(code);
  418. columns.Add(key);
  419. }
  420. if (codes != null)
  421. {
  422. var filter = new Filter<T>(x => x.ID).IsNotEqualTo(entity.ID);
  423. filter = filter.And(codes);
  424. var others = Provider.Query(filter, columns);
  425. var duplicates = new Dictionary<string, object>();
  426. foreach (var row in others.Rows)
  427. foreach (var key in props.Keys)
  428. {
  429. var eval = CoreUtils.GetPropertyValue(entity, key);
  430. var cval = row.Get<string>(key);
  431. if (Equals(eval, cval))
  432. duplicates[key] = eval;
  433. }
  434. if (duplicates.Any())
  435. throw new DuplicateCodeException(typeof(T), duplicates);
  436. }
  437. }
  438. protected virtual void AfterSave(T entity)
  439. {
  440. }
  441. protected virtual void OnSave(T entity, ref string auditnote)
  442. {
  443. CheckAutoIncrement(entity);
  444. Provider.Save(entity);
  445. }
  446. private void DoSave(T entity, string auditnote)
  447. {
  448. UpdateUserTracking(UserTrackingAction.Write);
  449. entity = RunScript(ScriptType.BeforeSave, new[] { entity }).First();
  450. //OpenSession("Save", true);
  451. //try
  452. //{
  453. var changes = entity.ChangedValues();
  454. //UpdateInternalLinks(entity);
  455. // Process any AutoIncrement Fields before we apply the Unique Code test
  456. // Thus, if we have a unique autoincrement, it will be populated prior to validation
  457. CheckAutoIncrement(entity);
  458. BeforeSave(entity);
  459. //OpenSession("Save", true);
  460. try
  461. {
  462. OnSave(entity, ref auditnote);
  463. }
  464. catch (Exception e)
  465. {
  466. //CloseSession("Save", true);
  467. throw e;
  468. }
  469. //CloseSession("Save", true);
  470. if (DbFactory.IsSupported<AuditTrail>())
  471. {
  472. var notes = new List<string>();
  473. if (!string.IsNullOrEmpty(auditnote))
  474. notes.Add(auditnote);
  475. if (!string.IsNullOrEmpty(changes))
  476. notes.Add(changes);
  477. if (notes.Any()) AuditTrail(entity, notes);
  478. }
  479. AfterSave(entity);
  480. //UpdateExternalLinks(entity, false);
  481. entity = RunScript(ScriptType.AfterSave, new[] { entity }).First();
  482. //entity.CommitChanges();
  483. //CloseSession("Save", false);
  484. //}
  485. //catch (Exception e)
  486. //{
  487. // //CloseSession("Save", false);
  488. // throw new Exception(e.Message + "\n\n" + e.StackTrace + "\n");
  489. //}
  490. }
  491. protected void AuditTrail(IEnumerable<Entity> entities, IEnumerable<string> notes)
  492. {
  493. var updates = new List<AuditTrail>();
  494. foreach (var entity in entities)
  495. {
  496. var audit = new AuditTrail
  497. {
  498. EntityID = entity.ID,
  499. Timestamp = DateTime.Now,
  500. User = UserID,
  501. Note = string.Join(": ", notes)
  502. };
  503. updates.Add(audit);
  504. }
  505. Provider.Save(updates);
  506. }
  507. protected void AuditTrail(Entity entity, IEnumerable<string> notes)
  508. {
  509. AuditTrail(new[] { entity }, notes);
  510. }
  511. public void Save(T entity, string auditnote)
  512. {
  513. DoSave(entity, auditnote);
  514. }
  515. public void Save(Entity entity, string auditnote)
  516. {
  517. var ent = (T)entity;
  518. DoSave(ent, auditnote);
  519. }
  520. public void Save(IEnumerable<T> entities, string auditnote)
  521. {
  522. DoSave(entities, auditnote);
  523. }
  524. public void Save(IEnumerable<Entity> entities, string auditnote)
  525. {
  526. var updates = new List<T>();
  527. foreach (var entity in entities)
  528. updates.Add((T)entity);
  529. DoSave(updates, auditnote);
  530. }
  531. protected virtual void OnSave(IEnumerable<T> entities, ref string auditnote)
  532. {
  533. CheckAutoIncrement(entities.ToArray());
  534. Provider.Save(entities);
  535. }
  536. private void DoSave(IEnumerable<T> entities, string auditnote)
  537. {
  538. UpdateUserTracking(UserTrackingAction.Write);
  539. entities = RunScript(ScriptType.BeforeSave, entities.ToList());
  540. //OpenSession("Save", true);
  541. //try
  542. //{
  543. // Process any AutoIncrement Fields before we apply the Unique Code test
  544. // Thus, if we have a unique autoincrement, it will be populated prior to validation
  545. CheckAutoIncrement(entities.ToArray());
  546. var changes = new Dictionary<T, string>();
  547. foreach (var entity in entities)
  548. {
  549. changes[entity] = entity.ChangedValues();
  550. //UpdateInternalLinks(entity);
  551. BeforeSave(entity);
  552. }
  553. try
  554. {
  555. //OpenSession("Save", true);
  556. OnSave(entities, ref auditnote);
  557. //CloseSession("Save", true);
  558. }
  559. catch (Exception e)
  560. {
  561. //CloseSession("Save", true);
  562. throw e;
  563. }
  564. if (DbFactory.IsSupported<AuditTrail>())
  565. {
  566. var audittrails = new List<AuditTrail>();
  567. foreach (var entity in entities)
  568. {
  569. var notes = new List<string>();
  570. if (!string.IsNullOrEmpty(auditnote))
  571. notes.Add(auditnote);
  572. if (changes.ContainsKey(entity) && !string.IsNullOrEmpty(changes[entity]))
  573. notes.Add(changes[entity]);
  574. if (notes.Any())
  575. {
  576. var audit = new AuditTrail
  577. {
  578. EntityID = entity.ID,
  579. Timestamp = DateTime.Now,
  580. User = UserID,
  581. Note = string.Join(": ", notes)
  582. };
  583. audittrails.Add(audit);
  584. //Provider.Save<AuditTrail>(audit);
  585. }
  586. }
  587. if (audittrails.Any())
  588. Provider.Save(audittrails);
  589. }
  590. foreach (var entity in entities)
  591. {
  592. AfterSave(entity);
  593. //UpdateExternalLinks(entity, false);
  594. //entity.CommitChanges();
  595. }
  596. entities = RunScript(ScriptType.AfterSave, entities);
  597. //}
  598. //catch (Exception e)
  599. //{
  600. // throw e;
  601. //}
  602. }
  603. #endregion
  604. #region Delete Functions
  605. protected virtual void BeforeDelete(T entity)
  606. {
  607. }
  608. protected virtual void OnDelete(T entity)
  609. {
  610. Provider.Delete(entity, UserID);
  611. }
  612. protected virtual void OnDelete(IEnumerable<T> entities)
  613. {
  614. Provider.Delete(entities, UserID);
  615. }
  616. private void DoDelete(T entity, string auditnote)
  617. {
  618. UpdateUserTracking(UserTrackingAction.Write);
  619. entity = RunScript(ScriptType.BeforeDelete, new[] { entity }).First();
  620. //OpenSession("Delete",false);
  621. try
  622. {
  623. BeforeDelete(entity);
  624. //OpenSession("Delete",true);
  625. try
  626. {
  627. OnDelete(entity);
  628. }
  629. catch (Exception e)
  630. {
  631. Logger.Send(LogType.Error, "", $"Error in DoDelete(T entity, string auditnote):\n{CoreUtils.FormatException(e)}");
  632. //CloseSession("Delete", true);
  633. //throw e;
  634. }
  635. //CloseSession("Delete",true);
  636. AfterDelete(entity);
  637. //UpdateExternalLinks(entity, true);
  638. //CloseSession("Delete", false);
  639. entity = RunScript(ScriptType.AfterDelete, new[] { entity }).First();
  640. }
  641. catch (Exception e)
  642. {
  643. //CloseSession("Delete", false);
  644. throw new Exception(e.Message + "\n\n" + e.StackTrace + "\n");
  645. }
  646. }
  647. private void DoDelete(IEnumerable<T> entities, string auditnote)
  648. {
  649. UpdateUserTracking(UserTrackingAction.Write);
  650. entities = RunScript(ScriptType.BeforeDelete, entities);
  651. //OpenSession("Delete", false);
  652. try
  653. {
  654. foreach (var entity in entities)
  655. BeforeDelete(entity);
  656. //OpenSession("Delete", true);
  657. try
  658. {
  659. OnDelete(entities);
  660. }
  661. catch (Exception e)
  662. {
  663. Logger.Send(LogType.Error, "", $"Error in DoDelete(IEnumerable<T> entities, string auditnote):\n{CoreUtils.FormatException(e)}");
  664. ////CloseSession("Delete", true);
  665. }
  666. ////CloseSession("Delete", true);
  667. foreach (var entity in entities) AfterDelete(entity);
  668. //UpdateExternalLinks(entity, true);
  669. ////CloseSession("Delete", false);
  670. entities = RunScript(ScriptType.AfterDelete, entities);
  671. }
  672. catch (Exception e)
  673. {
  674. ////CloseSession("Delete", false);
  675. throw new Exception(e.Message + "\n\n" + e.StackTrace + "\n");
  676. }
  677. }
  678. public void Delete(T entity, string auditnote)
  679. {
  680. DoDelete(entity, auditnote);
  681. }
  682. public void Delete(Entity entity, string auditnote)
  683. {
  684. DoDelete((T)entity, auditnote);
  685. }
  686. public void Delete(IEnumerable<T> entities, string auditnote)
  687. {
  688. DoDelete(entities, auditnote);
  689. }
  690. public void Delete(IEnumerable<Entity> entities, string auditnote)
  691. {
  692. var updates = new List<T>();
  693. foreach (var entity in entities)
  694. updates.Add((T)entity);
  695. DoDelete(updates, auditnote);
  696. }
  697. protected virtual void AfterDelete(T entity)
  698. {
  699. }
  700. #endregion
  701. #region BulkUpdate Functions
  702. public void BulkUpdate(IEnumerable<Entity> entities)
  703. {
  704. BulkUpdate((IEnumerable<T>)entities);
  705. }
  706. public virtual void BulkUpdate(IEnumerable<T> entities)
  707. {
  708. UpdateUserTracking(UserTrackingAction.Write);
  709. Provider.Save(entities);
  710. }
  711. #endregion
  712. }
  713. }