Search code examples
c#attributessitecoreglass-mapper

Having trouble Getting Custom attributes


I'm trying to get all attributes of each property inside a class, however I'm having trouble figuring out how to do so. I've tried a few different ways but I feel like I'm going about it wrong. Here's an example of the class and its property with attributes. Any insight would be much appreciated!

[SitecoreType(TemplateId= "{60E73011-0E01-4C13-A9A4-FAF8FF607930}", AutoMap= true)]
public class CalUserResults : BaseItem
{
    [IndexField("calcpa_user_name")]
    [SitecoreField("CalCPA User Name")]
    public virtual string CalUserName{ get; set; }
}

Specifically I'm trying to get the IndexField and SitecoreField. Thanks!

Edit things I've tried...

 CalUserResults kf = new CalUserResults();

 Glass.Mapper.Sc.Configuration.Attributes.SitecoreFieldAttribute attribute = kf.
     GetType().
     GetMethod("CalUserName").
     GetCustomAttributes(false).
     Cast<Glass.Mapper.Sc.Configuration.Attributes.SitecoreFieldAttribute>().
     SingleOrDefault();

and

trying by using FieldInfo


Solution

  • SOURCE OF THE PROBLEM:

    LINQ Cast<T> method tries to cast each of the attributes in the IEnumerable to the given type. And it fails, because your method has another attribute of IndexField type. That's why you are getting the InvalidCastException while executing the query.

    SOLUTION:

    What you need to solve the problem is to use the LINQ OfType<T> method. It filters the IEnumerable based on the success of cast operation:

     Glass.Mapper.Sc.Configuration.Attributes.SitecoreFieldAttribute attribute = kf. 
         GetType().  
         GetProperty("CalUserName").
         GetCustomAttributes(false). 
         OfType<Glass.Mapper.Sc.Configuration.Attributes.SitecoreFieldAttribute>(). 
         SingleOrDefault();
    

    P.S.: Also you may want to read When to use Cast() and Oftype() in Linq to clarify the issue and improve the understanding of LINQ.