using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.ComponentModel; namespace LoreSoft.MathExpressions.Metadata { /// /// A class to read attributes from type members. /// public static class AttributeReader { /// /// Gets the description from the on an enum. /// /// An enum type. /// The value to get the description from. /// The or the name of the instance. /// public static string GetDescription(T instance) { if (instance == null) throw new ArgumentNullException("instance"); string result = instance.ToString(); Type type = instance.GetType(); MemberInfo[] members = type.GetMember(result); if (members == null || members.Length == 0) return result; return GetDescription(members[0]); } /// /// Gets the description from the on a MemberInfo. /// /// The member info to look for the description. /// The or the name of the member. /// public static string GetDescription(MemberInfo info) { if (info == null) throw new ArgumentNullException("info"); string result = info.Name; object[] attributes = info.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes == null || attributes.Length == 0) return result; DescriptionAttribute description = attributes[0] as DescriptionAttribute; if (description == null || string.IsNullOrEmpty(description.Description)) return result; return description.Description; } /// /// Gets the abbreviation from the on an enum. /// /// An enum type. /// The enum to get the abbreviation from. /// The or the name of the memeber. /// public static string GetAbbreviation(T instance) { if (instance == null) throw new ArgumentNullException("instance"); string result = instance.ToString(); Type type = instance.GetType(); MemberInfo[] members = type.GetMember(result); if (members == null || members.Length == 0) return result; return GetAbbreviation(members[0]); } /// /// Gets the abbreviation from the on a instance. /// /// The instance info look for the abbreviation. /// The or the name of the instance. /// public static string GetAbbreviation(MemberInfo info) { if (info == null) throw new ArgumentNullException("info"); string result = info.Name; object[] attributes = info.GetCustomAttributes(typeof(AbbreviationAttribute), false); if (attributes == null || attributes.Length == 0) return result; AbbreviationAttribute abbreviation = attributes[0] as AbbreviationAttribute; if (abbreviation == null || string.IsNullOrEmpty(abbreviation.Text)) return result; return abbreviation.Text; } } }