BaseImporter.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 prop = CoreUtils.GetProperty(typeof(T), property);
  121. var type = prop.PropertyType;
  122. item.OriginalValues[property] = CoreUtils.GetPropertyValue(item, property);
  123. if (type == typeof(string))
  124. {
  125. if (prop.GetEditor() is UniqueCodeEditor || prop.GetEditor() is CodeEditor)
  126. CoreUtils.SetPropertyValue(item, property, value?.ToUpper());
  127. else
  128. CoreUtils.SetPropertyValue(item, property, value);
  129. }
  130. else
  131. {
  132. if (string.IsNullOrWhiteSpace(value))
  133. {
  134. var def = type.GetDefault();
  135. CoreUtils.SetPropertyValue(item, property, def);
  136. }
  137. else
  138. {
  139. var converter = TypeDescriptor.GetConverter(type);
  140. try
  141. {
  142. var converted = converter.ConvertFrom(value);
  143. CoreUtils.SetPropertyValue(item, property, converted);
  144. }
  145. catch (Exception e)
  146. {
  147. WriteLog(iRow, string.Format("Unable to Set Value: {0} [{1}] {2}", property, value, e.Message));
  148. }
  149. }
  150. }
  151. }
  152. }
  153. catch (Exception e)
  154. {
  155. bUpdatesOK = false;
  156. WriteLog(iRow, string.Format("Unable to Update Values: {0}", e.Message));
  157. }
  158. if (bUpdatesOK)
  159. {
  160. var bLookupsOK = true;
  161. if (keylookup != null)
  162. {
  163. try
  164. {
  165. var keyrows = keylookup.Results.Rows.ToList();
  166. foreach (var mapping in Mappings.Where(x => x.Key))
  167. {
  168. var keyvalue = CoreUtils.GetPropertyValue(item, mapping.Property);
  169. keyrows = keyrows.Where(r => string.Equals(r.Get<string>(mapping.Property)?.Trim(), keyvalue?.ToString().Trim()))
  170. .ToList();
  171. }
  172. var keyid = keyrows.Any() ? keyrows.First().Get<Guid>("ID") : Guid.Empty;
  173. CoreUtils.SetPropertyValue(item, "ID", keyid);
  174. }
  175. catch (Exception e)
  176. {
  177. bLookupsOK = false;
  178. WriteLog(iRow, string.Format("Unable to set Primary Key: {0}", e.Message));
  179. }
  180. }
  181. else
  182. {
  183. CoreUtils.SetPropertyValue(item, "ID", Guid.Empty);
  184. }
  185. try
  186. {
  187. foreach (var mapping in Mappings.Where(x => x.Lookup != ImportLookupType.None))
  188. {
  189. var parentprop = string.Join(".", mapping.Property.Split('.').Reverse().Skip(1).Reverse());
  190. var parent = CoreUtils.GetProperty(typeof(T), parentprop);
  191. var childprop = mapping.Property.Split('.').Last();
  192. var bt = parent.PropertyType.BaseType;
  193. if (bt != null)
  194. {
  195. var lookuptype = bt.GetGenericArguments().FirstOrDefault();
  196. var lookup = lookups.FirstOrDefault(x => x.Type.Equals(lookuptype));
  197. IEnumerable<CoreRow> lookuprows = lookup.Results.Rows;
  198. var lookupvalue = CoreUtils.GetPropertyValue(item, mapping.Property) as string;
  199. if (!string.IsNullOrWhiteSpace(lookupvalue))
  200. {
  201. lookuprows = lookuprows.Where(r => r.Get<string>(childprop).Equals(lookupvalue));
  202. var lookupid = lookuprows.Any() ? lookuprows.First().Get<Guid>("ID") : Guid.Empty;
  203. if (lookupid == Guid.Empty)
  204. {
  205. if (mapping.Lookup == ImportLookupType.Restrict)
  206. {
  207. bLookupsOK = false;
  208. WriteLog(iRow, string.Format("Lookup Value [{0}] not found", lookupvalue));
  209. }
  210. else if (mapping.Lookup == ImportLookupType.Create)
  211. {
  212. var newlookup = Activator.CreateInstance(lookuptype);
  213. CoreUtils.SetPropertyValue(newlookup, childprop, lookupvalue);
  214. ClientFactory.CreateClient(lookuptype).Save(newlookup, "Created by Import");
  215. lookupid = (Guid?)CoreUtils.GetPropertyValue(newlookup, "ID") ?? Guid.Empty;
  216. var newrow = lookup.Results.NewRow();
  217. lookup.Results.LoadRow(newrow, newlookup);
  218. lookup.Results.Rows.Add(newrow);
  219. CoreUtils.SetPropertyValue(item, lookup.ID, lookupid);
  220. var prefix = String.Join(".", lookup.ID.Split('.').Reverse().Skip(1).Reverse());
  221. foreach (var field in lookup.Fields)
  222. CoreUtils.SetPropertyValue(item, String.Join(".", new String[] { prefix, field }), newrow[field]);
  223. }
  224. }
  225. else
  226. {
  227. CoreUtils.SetPropertyValue(item, lookup.ID, lookupid);
  228. var prefix = String.Join(".", lookup.ID.Split('.').Reverse().Skip(1).Reverse());
  229. foreach (var field in lookup.Fields)
  230. CoreUtils.SetPropertyValue(item, String.Join(".", new String[] { prefix, field }), lookuprows.First()[field]);
  231. }
  232. }
  233. }
  234. }
  235. }
  236. catch (Exception e)
  237. {
  238. bLookupsOK = false;
  239. WriteLog(iRow, string.Format("Exception setting lookup values: {0}", e.Message));
  240. }
  241. if (bLookupsOK)
  242. {
  243. var bOK = AfterProcess != null ? AfterProcess.Invoke(this, item, values) : true;
  244. if (bOK && item.IsChanged())
  245. try
  246. {
  247. var bNewKey = keylookup != null && item.ID == Guid.Empty;
  248. if (OnSave != null)
  249. OnSave?.Invoke(this, item);
  250. else
  251. new Client<T>().Save(item, "");
  252. if (bNewKey)
  253. {
  254. var row = keylookup!.Results.NewRow();
  255. keylookup.Results.LoadRow(row, item);
  256. keylookup.Results.Rows.Add(row);
  257. }
  258. var key = new List<object?>();
  259. foreach (var mapping in Mappings.Where(x => x.Key))
  260. key.Add(CoreUtils.GetPropertyValue(item, mapping.Property));
  261. WriteLog(iRow, string.Format("Successfully Imported [{0}]", string.Join(" + ", key)));
  262. iResult++;
  263. }
  264. catch (Exception e)
  265. {
  266. WriteLog(iRow, string.Format("Unable to Save Item: {0}", e.Message));
  267. }
  268. }
  269. }
  270. }
  271. _log.Add("");
  272. return iResult;
  273. }
  274. protected void Notify(string message)
  275. {
  276. OnNotify?.Invoke(this, message);
  277. }
  278. private void WriteLog(int row, string message)
  279. {
  280. _log.Add(string.Format("{0:D8} {1}", row, message));
  281. }
  282. private class ImportLookup
  283. {
  284. public ImportLookup(Type type, string id, ImportLoadEvent onload)
  285. {
  286. Type = type;
  287. Fields = new List<string>();
  288. ID = id;
  289. OnLoad = onload;
  290. }
  291. public Type Type { get; }
  292. public List<string> Fields { get; }
  293. public string ID { get; }
  294. public event ImportLoadEvent OnLoad;
  295. public CoreTable Results { get; private set; }
  296. public void Refresh()
  297. {
  298. if (!Fields.Contains("ID"))
  299. Fields.Add("ID");
  300. if (OnLoad != null)
  301. Results = OnLoad?.Invoke(this, Type, Fields.ToArray(), ID);
  302. else
  303. {
  304. var client = ClientFactory.CreateClient(Type);
  305. var columns = Columns.Create(Type);
  306. foreach (var field in Fields)
  307. columns.Add(field);
  308. if (!columns.ColumnNames().Contains("ID"))
  309. columns.Add("ID");
  310. Results = client.Query(null, columns);
  311. }
  312. }
  313. }
  314. }
  315. }