mercredi 28 octobre 2015

Automatically determine MaxLength and use it for padding

I have a model with a bunch of fields defined like this:

public class Transaction
{
    public DateTime R03DateFrom { get; set; }
    public DateTime? R03DateTo { get; set; }
    [MaxLength(80)]
    public string R03Place { get; set; }
    [MaxLength(20)]
    public string R03Code { get; set; }
    // And so on....
}

At a certain point I need to export some of this data to fixed width files, and if a string has a MaxLength of x, then in the output file it should always be output right-padded with spaces up to x characters.

I'm hoping to re-use the fact that the string's MaxLength is always defined in the Model in order to flow this information through to the export.

At the moment, a typical export row function looks like this (ExDateTime is an extension method that formats the date in yyyyMMddhhmm format):

    private string GetR03Row()
    {
        return GetRowCode() + "03" +
               R03DateFrom.ExDateTime() +
               R03DateTo.ExDateTime() +
               (R03Place??"").PadRight(80) +
               (R03Code??"").PadRight(20);
    }

I'd like to replace the line

(R03Place??"").PadRight(80)

with something that uses the MaxLength attribute.

Every string will have a MaxLength.





Aucun commentaire:

Enregistrer un commentaire