BaseImporter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.Linq;
  6. using InABox.Clients;
  7. using Newtonsoft.Json.Linq;
  8. namespace InABox.Core
  9. {
  10. public abstract class BaseImporter<T> : IImporter, IDisposable where T : Entity, IRemotable, IPersistent, new()
  11. {
  12. private readonly List<string> _log = new List<string>();
  13. public BaseImporter()
  14. {
  15. Properties = CoreUtils.PropertyList(typeof(T), x => true, true).Keys.ToArray();
  16. Fields = new string[] { };
  17. Mappings = new List<ImportMapping>();
  18. HasHeader = true;
  19. HeaderRow = 1;
  20. }
  21. public void Dispose()
  22. {
  23. Close();
  24. Properties = null;
  25. Fields = null;
  26. Mappings = null;
  27. }
  28. public string[] Properties { get; private set; }
  29. public bool HasHeader { get; set; }
  30. public int HeaderRow { get; set; }
  31. public abstract bool ReadHeader();
  32. public string[] Fields { get; protected set; }
  33. public List<ImportMapping> Mappings { get; private set; }
  34. public IEnumerable<string> Log => _log;
  35. public event ImportNotificationEvent OnNotify;
  36. public void InitialiseFields(string[] fields)
  37. {
  38. Fields = fields;
  39. }
  40. public abstract bool Open(Stream stream);
  41. public abstract void Close();
  42. public abstract bool MoveNext();
  43. public abstract Dictionary<string, string> ReadLine();
  44. public event ImportPreProcessEvent BeforeProcess;
  45. public event ImportPostProcessEvent AfterProcess;
  46. public event ImportLoadEvent OnLoad;
  47. public event ImportSaveEvent OnSave;
  48. public event ImportLogEvent OnLog;
  49. public event ImportLogEvent OnError;
  50. public int Import()
  51. {
  52. _log.Clear();
  53. _log.Add(string.Format("Import Log {0:dd/MM/yyyy hh:mm:ss}", DateTime.Now));
  54. _log.Add("==============================");
  55. var iResult = 0;
  56. ImportLookup? keylookup = null;
  57. var lookups = new List<ImportLookup>();
  58. Notify("Preparing Import Mappings...");
  59. foreach (var mapping in Mappings)
  60. {
  61. if (mapping.Key)
  62. {
  63. if (keylookup == null)
  64. {
  65. keylookup = new ImportLookup(typeof(T), "ID", OnLoad);
  66. var others = LookupFactory.DefineColumns(typeof(T));
  67. foreach (var other in others.ColumnNames())
  68. keylookup.Fields.Add(other);
  69. lookups.Add(keylookup);
  70. }
  71. if (!keylookup.Fields.Contains(mapping.Property))
  72. keylookup.Fields.Add(mapping.Property);
  73. }
  74. if (mapping.Lookup != ImportLookupType.None)
  75. {
  76. var parentprop = string.Join(".", mapping.Property.Split('.').Reverse().Skip(1).Reverse());
  77. var parent = CoreUtils.GetProperty(typeof(T), parentprop);
  78. var childprop = mapping.Property.Split('.').Last();
  79. var bt = parent.PropertyType.BaseType;
  80. if (bt != null)
  81. {
  82. var lookuptype = bt.GetGenericArguments().FirstOrDefault();
  83. var lookup = lookups.FirstOrDefault(x => x.Type == lookuptype);
  84. if (lookup == null)
  85. {
  86. lookup = new ImportLookup(lookuptype, parentprop + ".ID", null);
  87. var others = LookupFactory.DefineColumns(lookuptype);
  88. foreach (var other in others.ColumnNames())
  89. lookup.Fields.Add(other);
  90. lookups.Add(lookup);
  91. }
  92. if (!lookup.Fields.Contains(childprop))
  93. lookup.Fields.Add(childprop);
  94. }
  95. }
  96. }
  97. if (keylookup == null)
  98. {
  99. WriteLog(0, "WARNING: No Key Fields Found - All Items will be treated as new");
  100. //return iResult;
  101. }
  102. else
  103. {
  104. Notify(string.Format("Loading {0} Keys [{1}]", keylookup.Type.Name, string.Join("]+[", keylookup.Fields)));
  105. keylookup.Refresh();
  106. }
  107. foreach (var lookup in lookups)
  108. if (lookup.Results == null)
  109. {
  110. Notify(string.Format("Loading {0} Lookups [{1}]", lookup.Type.Name, string.Join("]+[", lookup.Fields)));
  111. lookup.Refresh();
  112. }
  113. var itemlist = new List<T>();
  114. var iRow = 0;
  115. while (MoveNext())
  116. {
  117. iRow++;
  118. var item = new T();
  119. Notify(string.Format("Parsing Row {0}", iRow));
  120. Dictionary<string, string> values;
  121. try
  122. {
  123. var lineValues = ReadLine();
  124. values = Mappings.ToDictionary(
  125. x => x.Property,
  126. x =>
  127. {
  128. if (!x.Field.IsNullOrWhiteSpace())
  129. {
  130. return lineValues.GetValueOrDefault(x.Field) ?? "";
  131. }
  132. else
  133. {
  134. return x.Constant;
  135. }
  136. });
  137. }
  138. catch(Exception e)
  139. {
  140. WriteError(iRow, $"Error reading line: {e.Message}");
  141. continue;
  142. }
  143. var bUpdatesOK = BeforeProcess != null ? BeforeProcess.Invoke(this, values) : true;
  144. try
  145. {
  146. foreach (var property in values.Keys)
  147. {
  148. var value = values[property];
  149. var p2 = DatabaseSchema.Property(typeof(T), property);
  150. //var prop = CoreUtils.GetProperty(typeof(T), property);
  151. var type = p2.PropertyType;
  152. item.OriginalValues[property] = CoreUtils.GetPropertyValue(item, property);
  153. if (type == typeof(string))
  154. {
  155. if (p2.Editor is UniqueCodeEditor || p2.Editor is CodeEditor)
  156. CoreUtils.SetPropertyValue(item, property, value?.ToUpper());
  157. else
  158. CoreUtils.SetPropertyValue(item, property, value);
  159. }
  160. else
  161. {
  162. if (string.IsNullOrWhiteSpace(value))
  163. {
  164. var def = type.GetDefault();
  165. CoreUtils.SetPropertyValue(item, property, def);
  166. }
  167. else
  168. {
  169. var converter = TypeDescriptor.GetConverter(type);
  170. try
  171. {
  172. var converted = converter.ConvertFrom(value);
  173. CoreUtils.SetPropertyValue(item, property, converted);
  174. }
  175. catch (Exception e)
  176. {
  177. WriteError(iRow, string.Format("Unable to Set Value: {0} [{1}] {2}", property, value, e.Message));
  178. }
  179. }
  180. }
  181. }
  182. }
  183. catch (Exception e)
  184. {
  185. bUpdatesOK = false;
  186. WriteError(iRow, string.Format("Unable to Update Values: {0}", e.Message));
  187. }
  188. if (!bUpdatesOK)
  189. {
  190. continue;
  191. }
  192. var bLookupsOK = true;
  193. if (keylookup != null)
  194. {
  195. try
  196. {
  197. var keyrows = keylookup.Results.Rows.ToList();
  198. foreach (var mapping in Mappings.Where(x => x.Key))
  199. {
  200. var keyvalue = CoreUtils.GetPropertyValue(item, mapping.Property);
  201. keyrows = keyrows.Where(r => string.Equals(r.Get<string>(mapping.Property)?.Trim(), keyvalue?.ToString().Trim()))
  202. .ToList();
  203. }
  204. var keyid = keyrows.Any() ? keyrows.First().Get<Guid>("ID") : Guid.Empty;
  205. CoreUtils.SetPropertyValue(item, "ID", keyid);
  206. }
  207. catch (Exception e)
  208. {
  209. bLookupsOK = false;
  210. WriteError(iRow, string.Format("Unable to set Primary Key: {0}", e.Message));
  211. }
  212. }
  213. else
  214. {
  215. CoreUtils.SetPropertyValue(item, "ID", Guid.Empty);
  216. }
  217. try
  218. {
  219. foreach (var mapping in Mappings.Where(x => x.Lookup != ImportLookupType.None))
  220. {
  221. var parentprop = string.Join(".", mapping.Property.Split('.').Reverse().Skip(1).Reverse());
  222. var parent = CoreUtils.GetProperty(typeof(T), parentprop);
  223. var childprop = mapping.Property.Split('.').Last();
  224. var bt = parent.PropertyType.BaseType;
  225. if (bt != null)
  226. {
  227. var lookuptype = bt.GetGenericArguments().FirstOrDefault();
  228. var lookup = lookups.FirstOrDefault(x => x.Type.Equals(lookuptype));
  229. IEnumerable<CoreRow> lookuprows = lookup.Results.Rows;
  230. var lookupvalue = CoreUtils.GetPropertyValue(item, mapping.Property) as string;
  231. if (!string.IsNullOrWhiteSpace(lookupvalue))
  232. {
  233. lookuprows = lookuprows.Where(r => r.Get<string>(childprop).Equals(lookupvalue));
  234. var lookupid = lookuprows.Any() ? lookuprows.First().Get<Guid>("ID") : Guid.Empty;
  235. if (lookupid == Guid.Empty)
  236. {
  237. if (mapping.Lookup == ImportLookupType.Restrict)
  238. {
  239. bLookupsOK = false;
  240. WriteError(iRow, string.Format("Lookup Value [{0}] not found", lookupvalue));
  241. }
  242. else if (mapping.Lookup == ImportLookupType.Create)
  243. {
  244. var newlookup = Activator.CreateInstance(lookuptype);
  245. CoreUtils.SetPropertyValue(newlookup, childprop, lookupvalue);
  246. ClientFactory.CreateClient(lookuptype).Save(newlookup, "Created by Import");
  247. lookupid = (Guid?)CoreUtils.GetPropertyValue(newlookup, "ID") ?? Guid.Empty;
  248. var newrow = lookup.Results.NewRow();
  249. lookup.Results.LoadRow(newrow, newlookup);
  250. lookup.Results.Rows.Add(newrow);
  251. CoreUtils.SetPropertyValue(item, lookup.ID, lookupid);
  252. var prefix = String.Join(".", lookup.ID.Split('.').Reverse().Skip(1).Reverse());
  253. foreach (var field in lookup.Fields)
  254. CoreUtils.SetPropertyValue(item, String.Join(".", new String[] { prefix, field }), newrow[field]);
  255. }
  256. }
  257. else
  258. {
  259. CoreUtils.SetPropertyValue(item, lookup.ID, lookupid);
  260. var prefix = String.Join(".", lookup.ID.Split('.').Reverse().Skip(1).Reverse());
  261. foreach (var field in lookup.Fields)
  262. CoreUtils.SetPropertyValue(item, String.Join(".", new String[] { prefix, field }), lookuprows.First()[field]);
  263. }
  264. }
  265. }
  266. }
  267. }
  268. catch (Exception e)
  269. {
  270. bLookupsOK = false;
  271. WriteError(iRow, string.Format("Exception setting lookup values: {0}", e.Message));
  272. }
  273. if (bLookupsOK)
  274. {
  275. var bOK = AfterProcess != null ? AfterProcess.Invoke(this, item, values) : true;
  276. if (bOK && item.IsChanged())
  277. try
  278. {
  279. var bNewKey = keylookup != null && item.ID == Guid.Empty;
  280. if (OnSave != null)
  281. OnSave?.Invoke(this, item);
  282. else
  283. new Client<T>().Save(item, "");
  284. if (bNewKey)
  285. {
  286. var row = keylookup!.Results.NewRow();
  287. keylookup.Results.LoadRow(row, item);
  288. keylookup.Results.Rows.Add(row);
  289. }
  290. var key = new List<object?>();
  291. foreach (var mapping in Mappings.Where(x => x.Key))
  292. key.Add(CoreUtils.GetPropertyValue(item, mapping.Property));
  293. WriteLog(iRow, string.Format("Successfully Imported [{0}]", string.Join(" + ", key)));
  294. iResult++;
  295. }
  296. catch (Exception e)
  297. {
  298. WriteError(iRow, string.Format("Unable to Save Item: {0}", e.Message));
  299. }
  300. }
  301. }
  302. _log.Add("");
  303. return iResult;
  304. }
  305. protected void Notify(string message)
  306. {
  307. OnNotify?.Invoke(this, message);
  308. }
  309. private void WriteLog(int row, string message)
  310. {
  311. _log.Add($"{row:D8} {message}");
  312. OnLog?.Invoke(this, $"{row:D8} {message}");
  313. }
  314. private void WriteError(int row, string message)
  315. {
  316. _log.Add($"{row:D8} Error: {message}");
  317. OnLog?.Invoke(this, $"{row:D8} Error: {message}");
  318. OnError?.Invoke(this, $"{row:D8} {message}");
  319. }
  320. private class ImportLookup
  321. {
  322. public ImportLookup(Type type, string id, ImportLoadEvent onload)
  323. {
  324. Type = type;
  325. Fields = new List<string>();
  326. ID = id;
  327. OnLoad = onload;
  328. }
  329. public Type Type { get; }
  330. public List<string> Fields { get; }
  331. public string ID { get; }
  332. public event ImportLoadEvent OnLoad;
  333. public CoreTable Results { get; private set; }
  334. public void Refresh()
  335. {
  336. if (!Fields.Contains("ID"))
  337. Fields.Add("ID");
  338. if (OnLoad != null)
  339. Results = OnLoad?.Invoke(this, Type, Fields.ToArray(), ID);
  340. else
  341. {
  342. var client = ClientFactory.CreateClient(Type);
  343. var columns = Columns.Create(Type);
  344. foreach (var field in Fields)
  345. columns.Add(field);
  346. if (!columns.ColumnNames().Contains("ID"))
  347. columns.Add("ID");
  348. Results = client.Query(null, columns);
  349. }
  350. }
  351. }
  352. }
  353. }