CSVPosterEngine.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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<TPostable>>
  15. where TPostable : Entity, IPostable
  16. {
  17. public override bool Process(IEnumerable<TPostable> posts)
  18. {
  19. var settings = GetSettings();
  20. ICSVExport results;
  21. if(!string.IsNullOrWhiteSpace(settings.Script))
  22. {
  23. var document = new ScriptDocument(settings.Script);
  24. document.Properties.Add(new ScriptProperty("Results", null));
  25. document.Compile();
  26. document.Execute(methodname: "Process");
  27. var resultsObject = document.GetValue("Results");
  28. results = (resultsObject as ICSVExport)
  29. ?? throw new Exception($"Script Results property expected to be ICSVExport, got {resultsObject}");
  30. }
  31. else
  32. {
  33. results = Poster.Process(posts);
  34. }
  35. var dlg = new SaveFileDialog()
  36. {
  37. FileName = settings.DefaultOutputFile,
  38. Filter = "CSV Files (*.csv)|*.csv"
  39. };
  40. if(dlg.ShowDialog() == true)
  41. {
  42. using var writer = new StreamWriter(dlg.FileName);
  43. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  44. csv.Context.RegisterClassMap(results.ClassMap.ClassMap);
  45. var method = typeof(CsvWriter).GetMethods()
  46. .Where(x => x.Name == nameof(CsvWriter.WriteRecords) && x.GetGenericArguments().Length == 1).First()
  47. .MakeGenericMethod(results.Type);
  48. method.Invoke(csv, new object?[] { results.Records });
  49. return true;
  50. }
  51. return false;
  52. }
  53. }
  54. }