CSVPosterEngine.cs 2.3 KB

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