C# Print TableEntity Properties, but ignore those properties with attribute [IgnoreProperty]

Viewed 152

I am trying to print out an object that implements TableEntity class, without those that should be Ignored regarding the persistence. The approach I generally use to print out objects is to use the StatePrinter.

public class MyEntity : TableEntity
{
    public string MyProperty { get; set; }

    [IgnoreProperty]
    public string MyIgnoredProperty { get; set; }

    public override string ToString()
    {
        Stateprinter printer = new Stateprinter();
        return printer.PrintObject(this);
    }
}

While this works pretty good for any kind of classes, with this MyEntity class it also prints the MyIgnoredProperty. Is there a clever way to also ignore the properties that have [IgnoredProperty] as attribute when printing out the object?

1 Answers

You can configure what fields/properties the Stateprinter cares about by configuring what "field harvester" to use.

Here's a simple field harvester that only returns public properties without the 'IgnoreProperty' attribute.

class PersistencePropertiesHarvester : IFieldHarvester
{
    public bool CanHandleType(Type type)
    {
        return typeof(TableEntity).IsAssignableFrom(type);
    }

    public List<SanitizedFieldInfo> GetFields(Type type)
    {
        var fields = new HarvestHelper().GetFieldsAndProperties(type);
        return fields.Where(IsPerstistenceProperty).ToList();
    }

    private static bool IsPerstistenceProperty(SanitizedFieldInfo field)
    {
        return
            // Only return properties ...
            field.FieldInfo.MemberType == MemberTypes.Property          
            &&
            // ... that has a public get method ...
            (field.FieldInfo as PropertyInfo)?.GetGetMethod(false) != null
            &&
            // ... that does not have the IgnoreProperty attribute
            field.FieldInfo.GetCustomAttribute<IgnoreProperty>() == null
            ;           
    }
}

Then you use it like this:

public class MyEntity : TableEntity
{
    public string MyProperty { get; set; }

    [IgnoreProperty]
    public string MyIgnoredProperty { get; set; }

    public override string ToString()
    {
        Stateprinter printer = new Stateprinter();
        printer.Configuration.Add(new PersistencePropertiesHarvester());
        return printer.PrintObject(this);
    }
}

And the result of new MyEntity().ToString() is now

new MyEntity()
{
    MyProperty = null
}
Related