DynamicImportGrid.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Windows;
  8. using System.Windows.Forms.Design;
  9. using System.Windows.Media.Imaging;
  10. using InABox.Core;
  11. using InABox.Scripting;
  12. using InABox.WPF;
  13. using Microsoft.CodeAnalysis.CSharp.Syntax;
  14. using Microsoft.Win32;
  15. namespace InABox.DynamicGrid
  16. {
  17. public delegate bool OnImportItem(object o);
  18. public class CustomiseImportArgs
  19. {
  20. public string FileName { get; set; }
  21. }
  22. public delegate void OnCustomiseImport(object sender, CustomiseImportArgs e);
  23. public class DynamicImportGrid : DynamicDataGrid<Importer>
  24. {
  25. private static readonly BitmapImage run = Wpf.Resources.rightarrow.AsBitmapImage();
  26. private DynamicImageColumn ImportColumn;
  27. private bool _canImport = true;
  28. public bool CanImport
  29. {
  30. get => _canImport;
  31. set
  32. {
  33. if(_canImport != value)
  34. {
  35. _canImport = value;
  36. ImportColumn.Position = _canImport ? DynamicActionColumnPosition.End : DynamicActionColumnPosition.Hidden;
  37. Refresh(true, false);
  38. }
  39. }
  40. }
  41. protected override void Init()
  42. {
  43. base.Init();
  44. ImportColumn = new DynamicImageColumn(ImportImage, ImportAction);
  45. ActionColumns.Add(ImportColumn);
  46. HiddenColumns.Add(x => x.EntityName);
  47. HiddenColumns.Add(x => x.ImporterDescription);
  48. HiddenColumns.Add(x => x.FileName);
  49. HiddenColumns.Add(x => x.Definition);
  50. HiddenColumns.Add(x => x.HasHeader);
  51. HiddenColumns.Add(x => x.HeaderRows);
  52. HiddenColumns.Add(x => x.ColumnWidths);
  53. HiddenColumns.Add(x => x.Script);
  54. }
  55. protected override void DoReconfigure(FluentList<DynamicGridOption> options)
  56. {
  57. base.DoReconfigure(options);
  58. options.AddRange(DynamicGridOption.RecordCount, DynamicGridOption.ShowHelp);
  59. }
  60. public Type EntityType { get; set; }
  61. public Guid EntityID { get; set; }
  62. public event OnImportItem OnImportItem;
  63. public event OnCustomiseImport OnCustomiseImport;
  64. public event ImportSaveEvent OnSave;
  65. public event ImportLoadEvent OnLoad;
  66. protected override void ShowHelp(string slug)
  67. {
  68. base.ShowHelp("Import_Data");
  69. }
  70. private BitmapImage? ImportImage(CoreRow? arg)
  71. {
  72. return arg != null ? run : null;
  73. }
  74. private static int[] ExtractColumnWidths(string widths)
  75. {
  76. if (string.IsNullOrWhiteSpace(widths))
  77. return new[] { 1024 };
  78. try
  79. {
  80. return widths.Split(',').Select(int.Parse).ToArray();
  81. }
  82. catch
  83. {
  84. return new[] { 1024 };
  85. }
  86. }
  87. public static bool CreateImporter(Importer importer,
  88. [NotNullWhen(true)]
  89. ref string? filename,
  90. [NotNullWhen(true)]
  91. out IImporter iimporter,
  92. Action<CustomiseImportArgs>? customiseImport = null,
  93. Func<object, bool>? onImport = null)
  94. {
  95. iimporter = null;
  96. var definition =
  97. ImportFactory.Definitions.FirstOrDefault(x => x.Description.Equals(importer.ImporterDescription));
  98. var entityType = CoreUtils.GetEntity(importer.EntityName);
  99. if (definition != null)
  100. {
  101. ScriptDocument? helper = null;
  102. try
  103. {
  104. if (!importer.Script.IsNullOrWhiteSpace())
  105. {
  106. helper = new ScriptDocument(importer.Script);
  107. if (!helper.Compile())
  108. {
  109. MessageBox.Show("Unable to Compile Import Helper Script!");
  110. return false;
  111. }
  112. }
  113. }
  114. catch (Exception e)
  115. {
  116. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  117. }
  118. if(filename is null)
  119. {
  120. var fullFileName = importer.FileName;
  121. var path = Path.GetDirectoryName(fullFileName);
  122. var extension = Path.GetExtension(fullFileName);
  123. var args = new CustomiseImportArgs { FileName = Path.GetFileNameWithoutExtension(fullFileName) };
  124. customiseImport?.Invoke(args);
  125. var filename2 = CoreUtils.SanitiseFileName(args.FileName);
  126. var dlg = new OpenFileDialog
  127. {
  128. Filter = definition.Filter,
  129. FileName = Path.Combine(path, filename2) + (extension.StartsWith(".") ? "" : ".") + extension
  130. };
  131. if (!string.IsNullOrWhiteSpace(dlg.FileName) && Directory.Exists(Path.GetDirectoryName(dlg.FileName)))
  132. dlg.InitialDirectory = Path.GetDirectoryName(dlg.FileName);
  133. if(dlg.ShowDialog() == true)
  134. {
  135. filename = dlg.FileName;
  136. }
  137. else
  138. {
  139. return false;
  140. }
  141. }
  142. else
  143. {
  144. var path = Path.GetDirectoryName(filename);
  145. var extension = Path.GetExtension(filename);
  146. var args = new CustomiseImportArgs { FileName = Path.GetFileNameWithoutExtension(filename) };
  147. customiseImport?.Invoke(args);
  148. var filename2 = CoreUtils.SanitiseFileName(args.FileName);
  149. filename = Path.ChangeExtension(Path.Combine(path, filename2), extension);
  150. }
  151. iimporter = ImportFactory.Create(definition, entityType);
  152. if (iimporter is IFixedWidthImporter fixedImporter)
  153. fixedImporter.ColumnWidths = ExtractColumnWidths(importer.ColumnWidths);
  154. iimporter.HasHeader = importer.HasHeader;
  155. iimporter.HeaderRow = Math.Max(1, importer.HeaderRows);
  156. iimporter.BeforeProcess += (sender, values) =>
  157. {
  158. if (helper != null)
  159. return helper.Execute("Module", "BeforeProcess", new object[] { values });
  160. return true;
  161. };
  162. iimporter.AfterProcess += (sender, item, values) =>
  163. {
  164. var bOK = true;
  165. if (helper != null)
  166. bOK = helper.Execute("Module", "AfterProcess", new[] { item, values });
  167. bOK = !bOK || onImport is null || onImport.Invoke(item);
  168. return bOK;
  169. };
  170. var settings = importer.Definition;
  171. var mappings = Serialization.Deserialize<List<ImportMapping>>(settings);
  172. iimporter.Mappings.AddRange(mappings);
  173. return true;
  174. }
  175. else
  176. {
  177. return false;
  178. }
  179. }
  180. private bool ImportAction(CoreRow? arg)
  181. {
  182. if (arg != null)
  183. {
  184. var importer = arg.ToObject<Importer>();
  185. string? filename = null;
  186. if (CreateImporter(importer,
  187. ref filename,
  188. out var iimporter,
  189. (args) => OnCustomiseImport?.Invoke(this, args),
  190. (o) => OnImportItem?.Invoke(o) != false))
  191. {
  192. iimporter.OnLoad += OnLoad;
  193. iimporter.OnSave += OnSave;
  194. Progress.Show("Importing Data");
  195. using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
  196. Progress.SetMessage("Opening File");
  197. if (iimporter.Open(stream))
  198. {
  199. if (iimporter.ReadHeader())
  200. {
  201. var mismatches = iimporter.Mappings.Where(x =>
  202. !string.IsNullOrWhiteSpace(x.Field) &&
  203. !iimporter.Fields.Contains(x.Field)
  204. ).Select(x => x.Field).ToArray();
  205. if (!mismatches.Any())
  206. {
  207. var imported = iimporter.Import();
  208. Progress.Close();
  209. MessageBox.Show(string.Format("Imported {0} records!", imported));
  210. var LogFile = Path.ChangeExtension(filename, ".log");
  211. File.AppendAllLines(LogFile, iimporter.Log.ToArray());
  212. Process.Start(new ProcessStartInfo(LogFile) { UseShellExecute = true });
  213. }
  214. else
  215. {
  216. Progress.Close();
  217. MessageBox.Show("Import Mappings do not match file headers!\n\n- " + string.Join("\n- ", mismatches),
  218. "Import Failed");
  219. }
  220. }
  221. else
  222. {
  223. Progress.Close();
  224. MessageBox.Show("Unable to Read Headers from {0}", Path.GetFileName(filename));
  225. }
  226. }
  227. else
  228. {
  229. Progress.Close();
  230. MessageBox.Show("Unable to Open {0}", Path.GetFileName(filename));
  231. }
  232. iimporter.Close();
  233. }
  234. }
  235. return false;
  236. }
  237. private bool Importer_BeforeProcess(object sender, Dictionary<string, string> values)
  238. {
  239. return true;
  240. //throw new NotImplementedException();
  241. }
  242. protected override void Reload(Filters<Importer> criteria, Columns<Importer> columns, ref SortOrder<Importer>? sort,
  243. Action<CoreTable?, Exception?> action)
  244. {
  245. criteria.Add(new Filter<Importer>(x => x.EntityName).IsEqualTo(EntityType.EntityName()));
  246. if (EntityID != Guid.Empty)
  247. criteria.Add(new Filter<Importer>(x => x.EntityID).IsEqualTo(EntityID));
  248. base.Reload(criteria, columns, ref sort, action);
  249. }
  250. protected override Importer CreateItem()
  251. {
  252. var result = base.CreateItem();
  253. result.EntityName = EntityType.EntityName();
  254. result.EntityID = EntityID;
  255. return result;
  256. }
  257. public override bool EditItems(Importer[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  258. {
  259. if (items.Length != 1)
  260. {
  261. MessageBox.Show("Please select a single item to edit!");
  262. return false;
  263. }
  264. var form = new DynamicImportForm(items[0]);
  265. if (form.ShowDialog() == true)
  266. {
  267. SaveItem(items[0]);
  268. return true;
  269. }
  270. return false;
  271. }
  272. }
  273. }