mardi 22 novembre 2016

Get values of properties of nested object

I'm trying to calculate the percentage of filled properties of object. But calculate only for properties with my attribute [CheckOnComplete] . So, I have something like

public class Details
{
    [CheckOnComplete]
    public int PropertyOne{get;set;}
    [CheckOnComplete]
    public int PropertyTwo{get;set;}

    public MyClass Detail{get;set;}
}

public class MyClass
{
    [CheckOnComplete]
    public int PropertyThree{get;set;}
    [CheckOnComplete]
    public int PropertyFour{get;set;}   

    public int PropertyFive{get;set;}   
}

And I have done so far this method to get percentage of completeness

public static int GetComplete<T>(T model) 
{
    Type type = model.GetType();
    double countRequeredProperties = 0;
    double countFilledProperties = 0;

    foreach (var propertyInfo in type.GetProperties()) {
        object[] attributes = propertyInfo.GetCustomAttributes(typeof(CompleteAttribute), true);
        if (attributes.Length != 0) {
            double attributeValue = Math.Abs(((CompleteAttribute)attributes[0]).Value);
            countRequeredProperties += attributeValue;
            var value = propertyInfo.GetValue(model);
            if (!EqualsDefaultValue(value)) {
                countFilledProperties += attributeValue;
            }
        }
    }
    if (countRequeredProperties == 0)
        return 0;
    return (int)(countFilledProperties / countRequeredProperties * 100);
}

In this case I will get result = 100

var details = new Details
{
    PropertyOne = 1,
    PropertyTwo = 2,
};
var result = GetComplete(details); 

In this case I will get result = 50

var details = new Details
{
    PropertyOne = 1
};
var result = GetComplete(details);

But how can I get summary value for details and nested object Detail

var myClass = new MyClass
{
    PropertyThree = 3,
    PropertyFour = 4
};

var details = new Details
{
    PropertyOne = 1,
    Detail = myClass
};
var result = GetComplete(details);

Here I want to get result = 75 because I have 4 properties with attribute(2 in Details class and 2 in nested object Detail) but only 3 of them have values.

Please give me some advices how do calculate that? Thanks.





Aucun commentaire:

Enregistrer un commentaire