CSVPosterEngine.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using CsvHelper;
  2. using InABox.Core;
  3. using InABox.Core.Postable;
  4. using InABox.Scripting;
  5. using Microsoft.Win32;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace InABox.Poster.CSV
  14. {
  15. public class CSVPosterEngine<TPostable> : PosterEngine<TPostable, ICSVPoster<TPostable>, CSVPosterSettings>
  16. where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
  17. {
  18. protected override bool DoProcess(IEnumerable<TPostable> posts)
  19. {
  20. var settings = GetSettings();
  21. ICSVExport results;
  22. if(settings.ScriptEnabled && !string.IsNullOrWhiteSpace(settings.Script))
  23. {
  24. var document = new ScriptDocument(settings.Script);
  25. document.Properties.Add(new ScriptProperty("Results", null));
  26. if (!document.Compile())
  27. {
  28. throw new Exception("Script failed to compile!");
  29. }
  30. if(!document.Execute(methodname: "Process", parameters: new object[] { posts }))
  31. {
  32. return false;
  33. }
  34. var resultsObject = document.GetValue("Results");
  35. results = (resultsObject as ICSVExport)
  36. ?? throw new Exception($"Script 'Results' property expected to be ICSVExport, got {resultsObject}");
  37. }
  38. else
  39. {
  40. results = Poster.Process(posts);
  41. }
  42. var dlg = new SaveFileDialog()
  43. {
  44. FileName = settings.DefaultOutputFile,
  45. Filter = "CSV Files (*.csv)|*.csv"
  46. };
  47. if(dlg.ShowDialog() == true)
  48. {
  49. using var writer = new StreamWriter(dlg.FileName);
  50. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  51. csv.Context.RegisterClassMap(results.ClassMap.ClassMap);
  52. var method = typeof(CsvWriter).GetMethods()
  53. .Where(x => x.Name == nameof(CsvWriter.WriteRecords) && x.GetGenericArguments().Length == 1).First()
  54. .MakeGenericMethod(results.Type);
  55. method.Invoke(csv, new object?[] { results.Records });
  56. return true;
  57. }
  58. else
  59. {
  60. throw new PostCancelledException();
  61. }
  62. }
  63. }
  64. }