BaseImporter.cs 15 KB

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