Monday, September 13, 2010

Non constant attributes parameters?

Given my previous post

Simple maths can boost your app performance

did some more thoughts over it in this post 

.Net compiler says no!!

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type   

public class CustomAttribute:Attribute {

    public CriteriaOperator CriteriaOperator { get; set; }

 

    public CustomAttribute(CriteriaOperator criteriaOperator) {

        CriteriaOperator = criteriaOperator;

    }

}

[CustomAttribute(CriteriaOperator.Parse("Name=?","eXpand"))]

public class Class1 {

 

}

the above cannot be compiled

BUT XAF SAYS YES

Why? Cause it has its own type system the XafTypesInfo system. And the types are added it to it at runtime. Meaning? We can do anything!!!

Take for example the following implementation of the above

core classes

public class MyController:ViewController {

    public override void CustomizeTypesInfo(ITypesInfo typesInfo)

    {

        base.CustomizeTypesInfo(typesInfo);

        var typeInfos = XafTypesInfo.Instance.FindTypeInfo(typeof(AttributeRegistrator)).Descendants.Where(info => !(info.IsAbstract));

        foreach (var typeInfo in typeInfos) {

            var logicRegistrator = (AttributeRegistrator)ReflectionHelper.CreateObject(typeInfo.Type);

            foreach (var attribute in logicRegistrator.GetAttributes(typeInfo)) {

                typeInfo.AddAttribute(attribute);

            }

        }

    }

}

 

public abstract class AttributeRegistrator {

    public abstract IEnumerable<Attribute> GetAttributes(ITypeInfo typesInfo);

}

implemention

public class CustomAttributeRegistrator:AttributeRegistrator {

    public override IEnumerable<Attribute> GetAttributes(ITypeInfo typesInfo) {

        if (typesInfo==typeof(Class1))

            yield return new CustomAttribute(CriteriaOperator.Parse("Name=?", "eXpand"))

    }

}

Cause modern programming is based on attributes the AttributeRegistrator example is most usefull when for example multiple developers wan to to work on the same class, the example was stolen from eXpand featurecenter application were that case is valid :) (Many developers work on the same file)

Subscribe to XAF feed
Subscribe to community feed

DiggIt!
blog comments powered by Disqus