forcewake / FlatFile

FlatFile is a library to work with flat files
MIT License
106 stars 39 forks source link

Attribute mapping with multiple record types #44

Open lw-schick opened 7 years ago

lw-schick commented 7 years ago

Is there a way to use attribute mapping with multiple record types?

Sample

[FixedLengthFile]
public abstract class MyDataBase
{
    protected MyDataBase(char lineType)
    {
        if (lineType <= 0) throw new ArgumentOutOfRangeException(nameof(lineType));

        _lineType = lineType;
    }

    private readonly char _lineType;

    [FixedLengthField(1, 1)]
    public char LineType
    {
        get { return _lineType; }
        set
        {
            if (value != _lineType)
                throw new NotSupportedException($"The value must be '{_lineType}'.");
        }
    }
}

[FixedLengthFile]
public sealed class MyDataHeader : MyDataBase
{
    public MyDataHeader()
        : base('H')
    { }

    [FixedLengthField(2, 13, Padding = Padding.Right, PaddingChar = ' ')]
    public string FormatVersion { get; set; }

    [FixedLengthField(15, 22, Padding = Padding.Right, PaddingChar = ' ')]
    public string Filename { get; set; }

    [FixedLengthField(37, 6, PaddingChar = '0')]
    public int JobId { get; set; }

    [FixedLengthField(43, 10, PaddingChar = '0')]
    public int NoOfTransactionLines { get; set; }

    [FixedLengthField(53, 12, PaddingChar = '0')]
    public int SumOfPoints { get; set; }
}

[FixedLengthFile]
public sealed class MyDataTransaction : MyDataBase
{
    public MyDataTransaction()
        : base('T')
    { }

    [FixedLengthField(2, 6, PaddingChar = '0')]
    public int JobId { get; set; }

    [FixedLengthField(8, 10, PaddingChar = '0')]
    public int TransactionEntryNo { get; set; }

    [FixedLengthField(18, 2, PaddingChar = '0')]
    public int TransactionType { get; set; }

    [FixedLengthField(20, 10, PaddingChar = '0')]
    public int Points { get; set; }
}

Now I have no idea how to read this. Could be something like:

var factory = new FixedLengthFileEngineFactory();
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(FixedFileSample)))
{
    var flatFile = factory.GetEngine<MyDataBase>();

    var records = flatFile.Read<MyDataBase>(stream).ToArray();
}

But I cannot make the type MyDataHeader and MyDataTransaction known to the engine class. The C# Xml serializer supports this with [XmlIncludeAttribute]

itsxallwater commented 5 years ago

I believe we're looking for help on this in #73 as well.