ICSVPoster.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using CsvHelper.Configuration;
  2. using InABox.Core;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq.Expressions;
  6. using System.Text;
  7. namespace InABox.Poster.CSV
  8. {
  9. public interface ICSVClassMap
  10. {
  11. ClassMap ClassMap { get; }
  12. }
  13. public interface ICSVClassMap<T> : ICSVClassMap
  14. {
  15. new ClassMap<T> ClassMap { get; }
  16. ClassMap ICSVClassMap.ClassMap => ClassMap;
  17. void Map(string name, Expression<Func<T, object>> expr);
  18. }
  19. public class CSVClassMap<T> : ClassMap<T>, ICSVClassMap<T>
  20. {
  21. public ClassMap<T> ClassMap => this;
  22. public void Map(string name, Expression<Func<T, object>> expr)
  23. {
  24. Map(expr).Name(name);
  25. }
  26. }
  27. public interface ICSVExport
  28. {
  29. Type Type { get; }
  30. ICSVClassMap ClassMap { get; }
  31. IEnumerable<object> Records { get; }
  32. }
  33. public interface ICSVExport<T> : ICSVExport
  34. where T : class
  35. {
  36. new Type Type => typeof(T);
  37. new CSVClassMap<T> ClassMap { get; }
  38. new IEnumerable<T> Records { get; }
  39. Type ICSVExport.Type => Type;
  40. ICSVClassMap ICSVExport.ClassMap => ClassMap;
  41. IEnumerable<object> ICSVExport.Records => Records;
  42. }
  43. public class CSVExport<T> : ICSVExport<T>
  44. where T : class
  45. {
  46. public CSVClassMap<T> ClassMap { get; } = new CSVClassMap<T>();
  47. public IEnumerable<T> Records => Items;
  48. public List<T> Items { get; } = new List<T>();
  49. public void DefineMapping(List<Tuple<string, Expression<Func<T, object>>>> mappings)
  50. {
  51. foreach(var (name, expr) in mappings)
  52. {
  53. ClassMap.Map(name, expr);
  54. }
  55. }
  56. public void Map(string name, Expression<Func<T, object>> expr)
  57. {
  58. ClassMap.Map(name, expr);
  59. }
  60. public void Add(T item)
  61. {
  62. Items.Add(item);
  63. }
  64. public void AddRange(IEnumerable<T> items)
  65. {
  66. Items.AddRange(items);
  67. }
  68. }
  69. /// <summary>
  70. /// Defines an interface for posters that can export to CSV.
  71. /// </summary>
  72. /// <typeparam name="TEntity"></typeparam>
  73. public interface ICSVPoster<TEntity> : IPoster<TEntity, CSVPosterSettings<TEntity>>
  74. where TEntity : Entity, IPostable
  75. {
  76. ICSVExport Process(IEnumerable<TEntity> entities);
  77. }
  78. }