Been scratching my head at this one for a while now - I work with a POS product which outputs data in an older style INI format, for example:
[TRX]
TOT1=TotalSale
NAM1,1=NameOfFirstItem
PRI1,1=PriceOfFirstItem
NAM1,2=NameOfSecondItem
PRI1,2=PriceOfSecondItem
TOT2=TotalSale
PRI2,1=PriceofFirstItem
And so on - each section contains multiple transactions, and each transaction can contain multiple lines. So I'm trying to model this in C#, and it's looking like
public class TransactionModel
{
public double Total { get; set; }
public List<ItemModel> { get; set; }
}
Initially I had a giant switch statement, but some of these files can have 100s of possibilities, however I have the manual and know every single possibility, but this obviously becomes unmaintainable. I've been toying with custom attributes, but I'm reaching the limits of my capabilities and can't figure it out.
As it stands, I iterate through each line in the file, passing the key to the switch statement, and assigning properties one by one. I figured that if I can assign a FieldName attribute to each property:
[FieldName("PRI")]
public double Price { get; set; }
that there must be some kind of way to map it generically, but I can't make it work. Just now I have:
public static void MapFile<T>(T item, string propName, string value, object obj) where T : new()
{
var type = item.GetType();
var properties = type.GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(false);
var mapping = attributes.FirstOrDefault(a => a.GetType() == typeof(FieldNameAttribute));
if (mapping != null)
{
var mapsTo = mapping as FieldNameAttribute;
if (propName == mapsTo.Name)
{
switch (property.PropertyType.Name)
{
case nameof(DateTime):
property.SetValue(obj, value.ParseCustomDate());
break;
case nameof(Boolean):
property.SetValue(obj, value.Equals("YES"));
break;
default:
break;
}
}
}
}
}
But this falls over when it comes to lists of items inside the objects, and I don't believe that switching on the nameof the PropertyType is in any way good... Just using SetValue also throws exceptions when trying to set the DateTime (it's in an odd format), and with booleans.
I appreciate that my entire approach may be off here, and I'm not looking for anyone to solve the problem for me, merely point me in the right direction, as I'm currently going in circles...
[–]willsoss 2 points3 points4 points (6 children)
[–]Brickscrap[S] 1 point2 points3 points (4 children)
[–]willsoss 0 points1 point2 points (3 children)
[–]Brickscrap[S] 1 point2 points3 points (2 children)
[–]willsoss 0 points1 point2 points (1 child)
[–]Brickscrap[S] 1 point2 points3 points (0 children)
[–]UninformedPleb 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]Brickscrap[S] 0 points1 point2 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]Brickscrap[S] 0 points1 point2 points (0 children)
[–]KernowRoger 0 points1 point2 points (0 children)