12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using CsvHelper;
- using InABox.Core;
- using InABox.Core.Postable;
- 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>
- where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
- {
- protected override bool DoProcess(IEnumerable<TPostable> posts)
- {
- var settings = GetSettings();
- ICSVExport results;
- if(settings.ScriptEnabled && !string.IsNullOrWhiteSpace(settings.Script))
- {
- var document = new ScriptDocument(settings.Script);
- document.Properties.Add(new ScriptProperty("Results", null));
- if (!document.Compile())
- {
- throw new Exception("Script failed to compile!");
- }
- if(!document.Execute(methodname: "Process", parameters: new object[] { posts }))
- {
- return false;
- }
- 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;
- }
- else
- {
- throw new PostCancelledException();
- }
- }
- }
- }
|