DynamicImportGrid.cs 10 KB

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