Tuesday, May 5, 2009

Linq, Attribute and Reflection, all in one

 

Greetings

I was goofing around with some reflection stuff, and wanted to use LINQ to build an xml document for me. It started off as three different steps, and whittled its way down to one.

  1. Gets a list of all of the properties in the current class that have the [ServiceProperty] attribute
  2. Creates an XDocument containing information about the property including the value, and all of the meta-data added by the [ServiceProperty] attribute

The only thing I don’t like is that it builds the entire wrapper, even if attribute is null. When the attribute is null, we don’t care about anything, and should just continue. But, as is, property.GetValue() executes even when we don’t need it.

   1: XDocument doc = new XDocument(



   2:     new XDeclaration("1.0", "utf-8", "yes"),



   3:     new XElement("properties",



   4:                  (



   5:                      from property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)



   6:                      let wrapper = new



   7:                                        {



   8:                                            Property = property,



   9:                                            Attribute =Attribute.GetCustomAttribute(property, typeof(ServicePropertyAttribute)) as ServicePropertyAttribute,



  10:                                            Value = property.GetValue(this, BindingFlags.Public | BindingFlags.Instance, null, null,



  11:                                            CultureInfo.InvariantCulture)



  12:                                        }



  13:                      where wrapper.Attribute != null



  14:                      select



  15:                          new XElement("property",



  16:                                       new XAttribute("name", wrapper.Property.Name),



  17:                                       new XElement("display-name", wrapper.Attribute.DisplayName),



  18:                                       new XElement("default-value", wrapper.Attribute.DefaultValue),



  19:                                       new XElement("description", wrapper.Attribute.Description),



  20:                                       new XElement("required", wrapper.Attribute.Required),



  21:                                       new XElement("value", wrapper.Value),



  22:                                       new XElement("data-type", wrapper.Property.PropertyType.FullName)



  23:                          )



  24:                  )



  25:         )



  26:     );




image

No comments: