BaseImporter.cs 15 KB

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