// // Intelligencia.Utilities // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Reflection; using System.ComponentModel; using System.Collections.Generic; using System.Web.UI.WebControls; namespace Intelligencia.Utilities { /// /// Helper class for creating list items from an enum data source. /// public class EnumDataSource { private EnumDataSource() { } /// /// Create an array of ListItem's from an Enum. /// /// /// /// This method returns an array of ListItem objects ready for passing to the /// AddRange method of a ListItemCollection. /// /// /// public enum PrivacyLevel /// { /// [Description("For your eyes only")] /// EyesOnly, /// /// [Description("Top secret")] /// TopSecret, /// /// Classified /// } /// /// ... /// ListItem[] items = EnumDataSource.Create(typeof(PrivacyLevel)); /// myDropDown.Items.AddRange(items); /// ... /// /// This will result in a dropdown list with the following: /// 0 "For your eyes only" /// 1 "Top secret" /// 2 "Classified" /// /// /// The Type of the Enum to create list items from. /// An array of ListItem objects, one for each Enum value. public static ListItem[] Create(Type enumSource) { // First check the cache in a thread-safe manner. if (!_cache.ContainsKey(enumSource)) { lock (_cache) { if (!_cache.ContainsKey(enumSource)) { // Not found in the cache, so create a new, empty list List values = new List(); // Enumerate over all fields. The Enum values appear as // fields in the Enum type. foreach (FieldInfo field in enumSource.GetFields()) { // Pick out only the literal fields, which represent // the Enum values. if (field.IsLiteral) { // Look up any Description attributes DescriptionAttribute[] attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; // Add either the description or the literal name values.Add(new ListItem(attribute.Length > 0 ? attribute[0].Description : field.Name, ((int)field.GetRawConstantValue()).ToString())); } } // Add the results to the cache for next time. _cache.Add(enumSource, values.ToArray()); } // Not using the fall through, because we want this inside the lock(). return _cache[enumSource]; } } else { return _cache[enumSource]; } } // A private static cache of the mappings from Enum type to ListItem[] private static Dictionary _cache = new Dictionary(); } }