source: extensions/PiwigoLib/PiwigoLib/DTO/Helper/PwgEnumHelper.cs @ 13520

Last change on this file since 13520 was 13520, checked in by bayral, 12 years ago

new project for windows live publish plugin
Well advance single uploader

File size: 1.8 KB
Line 
1using System;
2using System.Reflection;
3using System.Xml.Serialization;
4using System.Collections.Generic;
5
6namespace Com.Piwigo.Lib.DTO.Helper
7{
8    public static class PwgEnumHelper<T>
9    {
10        static PwgEnumHelper()
11        {
12            if (!typeof(T).IsEnum) {
13                throw new ArgumentException(String.Format("PwgEnumHelper<T>(): The type {0} is not a enum.", typeof(T).Name));
14            }
15        }
16
17        internal static String StringValueOf(T value)
18        {
19            FieldInfo fi = value.GetType().GetField(value.ToString());
20            XmlEnumAttribute[] attributes = (XmlEnumAttribute[])fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);
21            if (attributes.Length > 0)
22            {
23                return attributes[0].Name;
24            }
25            else
26            {
27                return value.ToString();
28            }
29        }
30
31        internal static T enumValueOf(String value) 
32        {
33            Type enumType = typeof(T);
34            Array values = Enum.GetValues(enumType);
35            foreach (T enumValue in values)
36            {
37                if (StringValueOf(enumValue).Equals(value))
38                {
39                    return enumValue;
40                }
41            }
42
43            throw new ArgumentException(String.Format("PwgEnumHelper<{0}>.enumValueOf({1}): The String is not a description or value of the specified enum.", typeof(T).Name, value));
44        }
45
46        public static List<KeyValuePair<T, String>> buildChoiceList()
47        {
48            List<KeyValuePair<T, String>> lst = new List<KeyValuePair<T, String>>();
49
50            foreach (T item in Enum.GetValues(typeof(T)))
51                {
52                lst.Add(new KeyValuePair<T, String>(item, StringValueOf(item)));
53                }
54 
55            return lst;
56        }
57    }
58}
Note: See TracBrowser for help on using the repository browser.