DatabaseUpdateScripts.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.Database;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration.Provider;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using Syncfusion.Windows.Tools.Controls;
  12. using System.Diagnostics.CodeAnalysis;
  13. using System.Reflection;
  14. using System.Text.RegularExpressions;
  15. using FastReport.Utils;
  16. namespace PRS.Shared
  17. {
  18. public static class DatabaseUpdateScripts
  19. {
  20. public static void RegisterScripts()
  21. {
  22. DataUpdater.RegisterUpdateScript("6.31", Update_6_31);
  23. DataUpdater.RegisterUpdateScript("6.37", Update_6_37);
  24. DataUpdater.RegisterUpdateScript("6.38", Update_6_38);
  25. DataUpdater.RegisterUpdateScript("6.39", Update_6_39);
  26. DataUpdater.RegisterUpdateScript("6.43", Update_6_43);
  27. DataUpdater.RegisterUpdateScript("7.00", Update_7_00);
  28. DataUpdater.RegisterUpdateScript("7.06", Update_7_06);
  29. DataUpdater.RegisterUpdateScript("7.14", Update_7_14);
  30. DataUpdater.RegisterUpdateScript("7.19", Update_7_19);
  31. }
  32. private static Dictionary<string, Tuple<string, string>> _6_31_module_map = new()
  33. {
  34. { "Assignments", new("Assignments", "Assignments") },
  35. { "Daily Report", new("Daily Report", "Assignments") },
  36. { "Delivered On Site", new("Delivered On Site", "Delivery Items") },
  37. { "Deliveries", new("Deliveries", "Deliveries") },
  38. { "Digital Forms", new("Digital Forms", "DigitalForm") },
  39. { "Employee List", new("Employees", "Employee") },
  40. { "Equipment List", new("Equipment", "Equipment") },
  41. { "Factory Floor", new("Factory", "Manufacturing Packets") },
  42. { "Incoming Consignments", new("Consignments", "Consignment") },
  43. { "Manufacturing Status", new("Manufacturing Packets", "Manufacturing Packets") },
  44. { "Product List", new("Products", "Products") },
  45. { "Projects", new("Job Details", "Job Details") },
  46. { "Purchase Orders", new("Purchase Orders", "PurchaseOrder") },
  47. { "Quotes", new("Quotes", "Quotes") },
  48. { "Rack List", new("Shipping", "Shipments") },
  49. { "Site Requisitions", new("Requisitions", "Requisition") },
  50. { "Staff TimeSheets", new("Timesheets", "TimeSheet") },
  51. { "Stock Locations", new("Stock Locations", "StockLocation") },
  52. { "Stock Movements", new("Stock Movements", "StockMovement") },
  53. { "Task List", new("Tasks By Status", "Kanban") },
  54. };
  55. private static bool Update_6_31()
  56. {
  57. var modules = DbFactory.Provider.Query(new Filter<CustomModule>().All())
  58. .Rows.Select(x => x.ToObject<CustomModule>()).ToList();
  59. foreach(var module in modules)
  60. {
  61. if (!string.IsNullOrWhiteSpace(module.Section))
  62. {
  63. if (_6_31_module_map.TryGetValue(module.Section, out var map))
  64. {
  65. module.Section = map.Item1;
  66. module.DataModel = map.Item2;
  67. module.AllRecords = true;
  68. }
  69. else
  70. {
  71. Logger.Send(LogType.Error, "", $"Custom Module '{module.Name}' has section name '{module.Section}' and will no longer be visible!");
  72. }
  73. }
  74. }
  75. DbFactory.Provider.Save(modules);
  76. return true;
  77. }
  78. private static bool Update_6_37()
  79. {
  80. Logger.Send(LogType.Information, "", "Recreating views");
  81. DbFactory.Provider.ForceRecreateViews();
  82. return true;
  83. }
  84. private static bool Update_6_38()
  85. {
  86. Logger.Send(LogType.Information, "", "Converting Job Requisition Dates to Due Dates");
  87. List<JobRequisition> updates = new List<JobRequisition>();
  88. var columns = new Columns<JobRequisition>(x => x.ID);
  89. columns.Add("Date");
  90. CoreTable requis = DbFactory.Provider.Query<JobRequisition>(null, columns);
  91. foreach (var row in requis.Rows)
  92. {
  93. var requi = row.ToObject<JobRequisition>();
  94. requi.Approved = row.Get<DateTime>("Date");
  95. updates.Add(requi);
  96. }
  97. DbFactory.Provider.Save(updates);
  98. return true;
  99. }
  100. private static bool Update_6_39()
  101. {
  102. void ConvertJobDocumentIssuedDates()
  103. {
  104. Logger.Send(LogType.Information, "", "Converting Job Document Issued Dates");
  105. List<JobDocumentSetMileStone> updates = new List<JobDocumentSetMileStone>();
  106. var columns = new Columns<JobDocumentSetMileStone>(x => x.ID).Add(x => x.Submitted).Add(x => x.Status);
  107. columns.Add("Issued");
  108. CoreTable milestones = DbFactory.Provider.Query<JobDocumentSetMileStone>(null, columns);
  109. foreach (var row in milestones.Rows)
  110. {
  111. var milestone = row.ToObject<JobDocumentSetMileStone>();
  112. if (milestone.Status == JobDocumentSetMileStoneStatus.Unknown)
  113. milestone.Status = JobDocumentSetMileStoneStatus.Submitted;
  114. milestone.Submitted = row.Get<DateTime>("Issued");
  115. updates.Add(milestone);
  116. }
  117. DbFactory.Provider.Save(updates);
  118. }
  119. void ConvertProductUnitsOfMeasure()
  120. {
  121. Logger.Send(LogType.Information, "", "Converting Product Units of Measure");
  122. List<ProductDimensionUnit> updates = new List<ProductDimensionUnit>();
  123. var columns = new Columns<ProductDimensionUnit>(x => x.ID).Add(x => x.Description);
  124. CoreTable units = DbFactory.Provider.Query<ProductDimensionUnit>(new Filter<ProductDimensionUnit>(x=>x.Code).IsEqualTo(""), columns);
  125. foreach (var row in units.Rows)
  126. {
  127. var unit = row.ToObject<ProductDimensionUnit>();
  128. unit.Code = unit.Description;
  129. updates.Add(unit);
  130. }
  131. DbFactory.Provider.Save(updates);
  132. }
  133. void ConvertQuoteUnitsOfMeasure()
  134. {
  135. Logger.Send(LogType.Information, "", "Converting Quote Units of Measure");
  136. List<QuoteTakeOffUnit> updates = new List<QuoteTakeOffUnit>();
  137. var columns = new Columns<QuoteTakeOffUnit>(x => x.ID).Add(x => x.Description);
  138. CoreTable units = DbFactory.Provider.Query<QuoteTakeOffUnit>(new Filter<QuoteTakeOffUnit>(x=>x.Code).IsEqualTo(""), columns);
  139. foreach (var row in units.Rows)
  140. {
  141. var unit = row.ToObject<QuoteTakeOffUnit>();
  142. unit.Code = unit.Description;
  143. updates.Add(unit);
  144. }
  145. DbFactory.Provider.Save(updates);
  146. }
  147. ConvertJobDocumentIssuedDates();
  148. ConvertProductUnitsOfMeasure();
  149. ConvertQuoteUnitsOfMeasure();
  150. return true;
  151. }
  152. private static bool Update_6_43()
  153. {
  154. void ConvertSupplierProductLinks()
  155. {
  156. Logger.Send(LogType.Information, "", "Converting Supplier/Product Links");
  157. List<SupplierProduct> updates = new List<SupplierProduct>();
  158. var columns = new Columns<SupplierProduct>(x => x.ID).Add(x=>x.Product.ID);
  159. columns.Add("ProductLink.ID");
  160. CoreTable products = DbFactory.Provider.Query<SupplierProduct>(null, columns);
  161. foreach (var row in products.Rows)
  162. {
  163. Guid id = row.Get<SupplierProduct,Guid>(x=>x.ID);
  164. Guid oldid = row.Get<Guid>("ProductLink.ID");
  165. Guid newid = row.Get<SupplierProduct,Guid>(x=>x.Product.ID);
  166. if ((oldid != Guid.Empty) && (newid == Guid.Empty))
  167. {
  168. var update = new SupplierProduct() { ID = id };
  169. update.CommitChanges();
  170. update.Product.ID = oldid;
  171. updates.Add(update);
  172. }
  173. }
  174. DbFactory.Provider.Save(updates);
  175. }
  176. ConvertSupplierProductLinks();
  177. return true;
  178. }
  179. private struct Map<T>
  180. {
  181. public String Old;
  182. public Expression<Func<T, object>> New;
  183. public Map(String oldcolumn, Expression<Func<T, object>> newcolumn)
  184. {
  185. Old = oldcolumn;
  186. New = newcolumn;
  187. }
  188. }
  189. private static bool Update_7_00()
  190. {
  191. static void Convert<T>(
  192. Filter<T> filter,
  193. params Map<T>[] maps
  194. ) where T : Entity, IPersistent, IRemotable, new()
  195. {
  196. Logger.Send(LogType.Information, "", $"Converting {typeof(T).EntityName().Split('.').Last()}...");
  197. List<T> updates = new List<T>();
  198. var columns = new Columns<T>(x => x.ID);
  199. foreach (var map in maps)
  200. {
  201. if (!columns.Items.Any(x=>String.Equals(x.Property,map.Old)))
  202. columns.Add(map.Old);
  203. if (!columns.Items.Any(x=>String.Equals(x.Property,CoreUtils.GetFullPropertyName<T, object>(map.New, "."))))
  204. columns.Add(map.New);
  205. }
  206. CoreTable table = DbFactory.Provider.Query<T>(filter,columns);
  207. int iCount = 0;
  208. foreach (var row in table.Rows)
  209. {
  210. var update = row.ToObject<T>();
  211. foreach (var map in maps)
  212. CoreUtils.SetPropertyValue(update, CoreUtils.GetFullPropertyName<T, object>(map.New, "."), CoreUtils.GetPropertyValue(update, map.Old));
  213. if (update.IsChanged())
  214. updates.Add(update);
  215. if (updates.Count == 100)
  216. {
  217. iCount += updates.Count;
  218. Logger.Send(LogType.Information, "", $"Converting {typeof(T).EntityName().Split('.').Last()} Times ({iCount}/{table.Rows.Count}");
  219. DbFactory.Provider.Save(updates);
  220. updates.Clear();
  221. }
  222. }
  223. if (updates.Count > 0)
  224. {
  225. iCount += updates.Count;
  226. Logger.Send(LogType.Information, "", $"Converting {typeof(T).EntityName().Split('.').Last()} Times ({iCount}/{table.Rows.Count})");
  227. DbFactory.Provider.Save(updates);
  228. updates.Clear();
  229. }
  230. }
  231. Convert<Assignment>(
  232. new Filter<Assignment>(x=>x.Booked.Start).IsEqualTo(DateTime.MinValue)
  233. .And(x=>x.Booked.Finish).IsEqualTo(DateTime.MinValue)
  234. .And(x=>x.Actual.Finish).IsEqualTo(DateTime.MinValue)
  235. .And(x=>x.Actual.Finish).IsEqualTo(DateTime.MinValue),
  236. new Map<Assignment>("Start",x => x.Booked.Start),
  237. new Map<Assignment>("Finish",x => x.Booked.Finish),
  238. new Map<Assignment>("Start",x => x.Actual.Start),
  239. new Map<Assignment>("Finish",x => x.Actual.Finish)
  240. );
  241. // ConvertTimes<TimeSheet>(
  242. // x => x.Actual.Duration,
  243. // new TimeExpressions<TimeSheet>(x => x.Actual.Start, x => x.Actual.Finish),
  244. // new TimeExpressions<TimeSheet>(x => x.Approved.Start, x => x.Approved.Finish)
  245. // );
  246. void Convert_StandardLeaves_and_LeaveRequests()
  247. {
  248. // Delete from TimeSheet where processed={} and leaverequestlink.id != empty
  249. var unprocessedtimesheets = DbFactory.Provider.Query<TimeSheet>(
  250. new Filter<TimeSheet>(x => x.Processed).IsEqualTo(DateTime.MinValue)
  251. .And(x => x.LeaveRequestLink.ID).IsNotEqualTo(Guid.Empty),
  252. new Columns<TimeSheet>(x=>x.ID)
  253. ).Rows.Select(x=>x.ToObject<TimeSheet>()).ToArray();
  254. int iTimes = 0;
  255. while (iTimes < unprocessedtimesheets.Length)
  256. {
  257. var deletions = unprocessedtimesheets.Skip(iTimes).Take(100).ToArray();
  258. DbFactory.Provider.Purge<TimeSheet>(deletions);
  259. iTimes += deletions.Length;
  260. }
  261. //DbFactory.Provider.Delete<TimeSheet>(unprocessedtimesheets,"");
  262. // Find all Leave Requests where public holiday != empty
  263. var standardleaverequests = DbFactory.Provider.Query<LeaveRequest>(
  264. new Filter<LeaveRequest>(x => x.PublicHoliday.ID).IsNotEqualTo(Guid.Empty),
  265. new Columns<LeaveRequest>(x=>x.ID)
  266. .Add(x=>x.PublicHoliday.ID)
  267. ).Rows.Select(x => x.ToObject<LeaveRequest>()).ToArray();
  268. foreach (var standardleaverequest in standardleaverequests)
  269. {
  270. // Find all timesheets for this leave request
  271. var standardleavetimesheets = DbFactory.Provider.Query<TimeSheet>(
  272. new Filter<TimeSheet>(x=>x.LeaveRequestLink.ID).IsEqualTo(standardleaverequest.ID),
  273. new Columns<TimeSheet>(x=>x.ID)
  274. .Add(x=>x.LeaveRequestLink.ID)
  275. ).Rows.Select(x=>x.ToObject<TimeSheet>()).ToArray();
  276. // Redirect timesheet from leaverequest to standardleave
  277. foreach (var standardleavetimesheet in standardleavetimesheets)
  278. {
  279. standardleavetimesheet.StandardLeaveLink.ID = standardleaverequest.PublicHoliday.ID;
  280. standardleavetimesheet.LeaveRequestLink.ID = Guid.Empty;
  281. }
  282. if (standardleavetimesheets.Any())
  283. DbFactory.Provider.Save(standardleavetimesheets);
  284. }
  285. // delete these leave requests
  286. int iRequests = 0;
  287. while (iRequests < standardleaverequests.Length)
  288. {
  289. var deletions = standardleaverequests.Skip(iRequests).Take(100).ToArray();
  290. DbFactory.Provider.Purge<LeaveRequest>(deletions);
  291. iRequests += deletions.Length;
  292. }
  293. // Delete from Assignment where leaverequestlink id != empty
  294. var leaveassignments = DbFactory.Provider.Query<Assignment>(
  295. new Filter<Assignment>(x => x.LeaveRequestLink.ID).IsNotEqualTo(Guid.Empty),
  296. new Columns<Assignment>(x=>x.ID)
  297. ).Rows.Select(x=>x.ToObject<Assignment>()).ToArray();
  298. int iAssignments = 0;
  299. while (iAssignments < leaveassignments.Length)
  300. {
  301. var deletions = leaveassignments.Skip(iAssignments).Take(100).ToArray();
  302. DbFactory.Provider.Purge<Assignment>(deletions);
  303. iAssignments += deletions.Length;
  304. }
  305. }
  306. Convert_StandardLeaves_and_LeaveRequests();
  307. return true;
  308. }
  309. private class Update_7_06_Class
  310. {
  311. private static Dictionary<Type, List<Tuple<Type, string>>> _cascades = new();
  312. private static Dictionary<Type, List<Tuple<Type, List<string>>>> _setNulls = new();
  313. private static void LoadDeletions(Type type)
  314. {
  315. if (_cascades.ContainsKey(type)) return;
  316. // Get the EntityLink that is associated with this class
  317. var linkclass = CoreUtils.TypeList(
  318. new[] { type.Assembly },
  319. x => typeof(IEntityLink).GetTypeInfo().IsAssignableFrom(x) && x.GetInheritedGenericTypeArguments().FirstOrDefault() == type
  320. ).FirstOrDefault();
  321. // if The entitylink does not exist, we don't need to do anything
  322. if (linkclass == null)
  323. return;
  324. var cascades = new List<Tuple<Type, string>>();
  325. var setNulls = new List<Tuple<Type, List<string>>>();
  326. var childtypes = DbFactory.Provider.Types.Where(x => x.IsSubclassOf(typeof(Entity)) && x.GetCustomAttribute<AutoEntity>() == null);
  327. foreach (var childtype in childtypes)
  328. {
  329. // Get all registered types for this entitylink
  330. var fields = new List<string>();
  331. var bDelete = false;
  332. // Find any IEntityLink<> properties that refer back to this class
  333. var childprops = CoreUtils.PropertyList(childtype, x => x.PropertyType == linkclass);
  334. foreach (var childprop in childprops)
  335. {
  336. var fieldname = string.Format("{0}.ID", childprop.Name);
  337. var attr = childprop.GetCustomAttributes(typeof(EntityRelationshipAttribute), true).FirstOrDefault();
  338. if (attr != null && ((EntityRelationshipAttribute)attr).Action.Equals(DeleteAction.Cascade))
  339. {
  340. cascades.Add(new(childtype, fieldname));
  341. bDelete = true;
  342. break;
  343. }
  344. fields.Add(fieldname);
  345. }
  346. if (!bDelete && fields.Any())
  347. {
  348. setNulls.Add(new(childtype, fields));
  349. }
  350. }
  351. _cascades[type] = cascades;
  352. _setNulls[type] = setNulls;
  353. }
  354. private static bool GetCascades(Type type, [NotNullWhen(true)] out List<Tuple<Type, string>>? cascades)
  355. {
  356. LoadDeletions(type);
  357. return _cascades.TryGetValue(type, out cascades);
  358. }
  359. private static bool GetSetNulls(Type type, [NotNullWhen(true)] out List<Tuple<Type, List<string>>>? setNulls)
  360. {
  361. LoadDeletions(type);
  362. return _setNulls.TryGetValue(type, out setNulls);
  363. }
  364. private static MethodInfo _deleteEntitiesMethod = typeof(Update_7_06_Class).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
  365. .Single(x => x.Name == nameof(DeleteEntity) && x.IsGenericMethod);
  366. private static void DeleteEntity<T>(Deletion deletion, Guid parentID, string parentField, DeletionData deletionData) where T : Entity, new()
  367. {
  368. var columns = DeletionData.DeletionColumns<T>();
  369. var delEntities = DbFactory.Provider.QueryDeleted(deletion, new Filter<T>(parentField).IsEqualTo(parentID), columns);
  370. var nDelntities = DbFactory.Provider.Query(new Filter<T>(parentField).IsEqualTo(parentID), columns);
  371. foreach (var row in delEntities.Rows.Concat(nDelntities.Rows))
  372. {
  373. deletionData.DeleteEntity<T>(row);
  374. CascadeDelete(typeof(T), deletion, row.Get<T, Guid>(x => x.ID), deletionData);
  375. }
  376. }
  377. private static void DeleteEntity(Type T, Deletion deletion, Guid parentID, string parentField, DeletionData deletionData)
  378. {
  379. _deleteEntitiesMethod.MakeGenericMethod(T).Invoke(null, new object?[] { deletion, parentID, parentField, deletionData });
  380. }
  381. private static MethodInfo _setNullEntityMethod = typeof(Update_7_06_Class).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
  382. .Single(x => x.Name == nameof(SetNullEntity) && x.IsGenericMethod);
  383. private static void SetNullEntity<T>(List<string> properties, Guid parentID, DeletionData deletionData) where T : Entity, new()
  384. {
  385. foreach (var property in properties)
  386. {
  387. var entities = DbFactory.Provider.Query(new Filter<T>(property).IsEqualTo(parentID), new Columns<T>(x => x.ID));
  388. foreach (var row in entities.Rows)
  389. {
  390. deletionData.SetNullEntity<T>(row.Get<T, Guid>(x => x.ID), property, parentID);
  391. }
  392. }
  393. }
  394. private static void SetNullEntity(Type T, List<string> properties, Guid parentID, DeletionData deletionData)
  395. {
  396. _setNullEntityMethod.MakeGenericMethod(T).Invoke(null, new object?[] { properties, parentID, deletionData });
  397. }
  398. private static void CascadeDelete(Type type, Deletion deletion, Guid parentID, DeletionData deletionData)
  399. {
  400. if (GetCascades(type, out var cascades))
  401. {
  402. foreach (var cascade in cascades)
  403. {
  404. DeleteEntity(cascade.Item1, deletion, parentID, cascade.Item2, deletionData);
  405. }
  406. }
  407. if (GetSetNulls(type, out var setNulls))
  408. {
  409. foreach (var setNull in setNulls)
  410. {
  411. SetNullEntity(setNull.Item1, setNull.Item2, parentID, deletionData);
  412. }
  413. }
  414. }
  415. // Referenced via reflection.
  416. private static void PurgeEntityType<T>(Deletion deletion) where T : Entity, new()
  417. {
  418. var entities = DbFactory.Provider.QueryDeleted(deletion, null, DeletionData.DeletionColumns<T>()).ToObjects<T>().ToList();
  419. var deletionData = new DeletionData();
  420. foreach (var entity in entities)
  421. {
  422. deletionData.DeleteEntity(entity);
  423. CascadeDelete(typeof(T), deletion, entity.ID, deletionData);
  424. }
  425. if (deletionData.Cascades.Count > 0 || deletionData.SetNulls.Count > 0)
  426. {
  427. var tableName = typeof(T).Name;
  428. var newDeletion = new Deletion()
  429. {
  430. DeletionDate = DateTime.Now,
  431. HeadTable = tableName,
  432. Description = $"Deleted {entities.Count} entries",
  433. DeletedBy = deletion.DeletedBy,
  434. Data = Serialization.Serialize(deletionData)
  435. };
  436. DbFactory.Provider.Save(newDeletion);
  437. }
  438. DbFactory.Provider.Purge(entities);
  439. }
  440. public static void Purge(Deletion deletion)
  441. {
  442. if (deletion.ID == Guid.Empty)
  443. {
  444. Logger.Send(LogType.Error, "", "Empty Deletion ID");
  445. return;
  446. }
  447. var entityType = CoreUtils.Entities.FirstOrDefault(x => x.Name == deletion.HeadTable);
  448. if (entityType is null)
  449. {
  450. Logger.Send(LogType.Error, "", $"Entity {deletion.HeadTable} does not exist");
  451. return;
  452. }
  453. var purgeMethod = typeof(Update_7_06_Class).GetMethod(nameof(PurgeEntityType), BindingFlags.NonPublic | BindingFlags.Static)!;
  454. purgeMethod.MakeGenericMethod(entityType).Invoke(null, new object[] { deletion });
  455. DbFactory.Provider.Purge<Deletion>(deletion);
  456. }
  457. }
  458. private static bool Update_7_06()
  459. {
  460. var deletions = DbFactory.Provider.Query<Deletion>(
  461. new Filter<Deletion>(x => x.Data).IsEqualTo(""));
  462. Logger.Send(LogType.Information, "", "Updating Deletions");
  463. foreach (var deletion in deletions.ToObjects<Deletion>())
  464. {
  465. Update_7_06_Class.Purge(deletion);
  466. }
  467. Logger.Send(LogType.Information, "", "Finished updating Deletions");
  468. return true;
  469. }
  470. /// <summary>
  471. /// Updating Wpf and Timebench fields to use Platform.DesktopVersion and Platform.MobileVersion
  472. /// </summary>
  473. /// <returns></returns>
  474. private static bool Update_7_14()
  475. {
  476. Logger.Send(LogType.Information, "", "Converting User.Wpf, User.Timebench -> User.Platform.DesktopVersion, User.Platform.MobileVersion");
  477. Logger.Send(LogType.Information, "", "Loading Wpf, Timebench properties");
  478. var props = DbFactory.Provider.Query<CustomProperty>(new Filter<CustomProperty>(x => x.Name).InList("Wpf", "TimeBench"))
  479. .Rows.Select(x => x.ToObject<CustomProperty>()).ToArray();
  480. DatabaseSchema.Load(props);
  481. var columns = new Columns<User>(x => x.ID);
  482. columns.Add("Wpf", "TimeBench");
  483. var users = DbFactory.Provider.Query<User>(
  484. new Filter<User>().All(),
  485. columns).ToObjects<User>().ToList();
  486. foreach(var user in users)
  487. {
  488. if(user.UserProperties.Dictionary.TryGetValue("Wpf", out var wpf))
  489. {
  490. user.Platform.DesktopVersion = wpf?.Value?.ToString() ?? "";
  491. }
  492. if (user.UserProperties.Dictionary.TryGetValue("TimeBench", out var timebench))
  493. {
  494. user.Platform.MobileVersion = timebench?.Value?.ToString() ?? "";
  495. }
  496. }
  497. DbFactory.Provider.Save<User>(users);
  498. Logger.Send(LogType.Information, "", "Finished updating user versions");
  499. return true;
  500. }
  501. /// <summary>
  502. /// Trigger the calculation of Digital Form Numbers
  503. /// </summary>
  504. /// <returns>true (always)</returns>
  505. private static bool Update_7_19()
  506. {
  507. // Find all classes that derive from EntityForm
  508. var formtypes = CoreUtils.TypeList(
  509. new[]
  510. {
  511. typeof(Setout).Assembly
  512. },
  513. myType =>
  514. myType is { IsClass: true, IsAbstract: false, IsGenericType: false }
  515. && myType.IsSubclassOf(typeof(Entity))
  516. && myType.GetInterfaces().Contains(typeof(IEntityForm))
  517. ).ToArray();
  518. foreach (var formtype in formtypes)
  519. {
  520. var columns = Columns.Create(formtype).Add("ID").Add("Number");
  521. var forms = DbFactory.Provider.Query(formtype, null, columns);
  522. var nullforms = forms.Rows
  523. .Where(r => String.IsNullOrWhiteSpace(r.Get<String>("Number")))
  524. .Select(r=>r.ToObject(formtype))
  525. .OfType<Entity>()
  526. .ToArray();
  527. if (!nullforms.Any())
  528. continue;
  529. var maxvalue = forms.Rows.Select(r => Regex.Match(r.Get<String>("Number") ?? "", @"(?<=-)\d+")?.Value ?? "0")
  530. .MaxBy(x => x) ?? "0";
  531. int.TryParse(maxvalue, out int iNumber);
  532. String format = null;
  533. foreach (var form in nullforms)
  534. {
  535. format ??= (form as IStringAutoIncrement)?.AutoIncrementFormat() ?? "{0:D8}";
  536. iNumber++;
  537. CoreUtils.SetPropertyValue(form, "Number", String.Format(format, iNumber));
  538. }
  539. DbFactory.Provider.Save(formtype, nullforms);
  540. }
  541. return true;
  542. }
  543. }
  544. }