123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- using CsvHelper;
- using InABox.Core;
- using InABox.Scripting;
- using Microsoft.Win32;
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace InABox.Poster.CSV
- {
- public class CSVPosterEngine<TPostable> : PosterEngine<TPostable, ICSVPoster<TPostable>, CSVPosterSettings<TPostable>>
- where TPostable : Entity, IPostable
- {
- public override bool Process(IEnumerable<TPostable> posts)
- {
- var settings = GetSettings();
- ICSVExport results;
- if(!string.IsNullOrWhiteSpace(settings.Script))
- {
- var document = new ScriptDocument(settings.Script);
- document.Properties.Add(new ScriptProperty("Results", null));
- document.Compile();
- document.Execute(methodname: "Process");
- var resultsObject = document.GetValue("Results");
- results = (resultsObject as ICSVExport)
- ?? throw new Exception($"Script Results property expected to be ICSVExport, got {resultsObject}");
- }
- else
- {
- results = Poster.Process(posts);
- }
- var dlg = new SaveFileDialog()
- {
- FileName = settings.DefaultOutputFile,
- Filter = "CSV Files (*.csv)|*.csv"
- };
- if(dlg.ShowDialog() == true)
- {
- using var writer = new StreamWriter(dlg.FileName);
- using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
- csv.Context.RegisterClassMap(results.ClassMap.ClassMap);
- var method = typeof(CsvWriter).GetMethods()
- .Where(x => x.Name == nameof(CsvWriter.WriteRecords) && x.GetGenericArguments().Length == 1).First()
- .MakeGenericMethod(results.Type);
- method.Invoke(csv, new object?[] { results.Records });
- return true;
- }
- return false;
- }
- }
- }
|