BaseImporter.cs 16 KB

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