17 using System.Collections.Generic;
19 using System.Reflection;
21 using erminas.SmartAPI.CMS.Project;
22 using erminas.SmartAPI.Exceptions;
23 using erminas.SmartAPI.Utils;
25 namespace erminas.SmartAPI.CMS.Converter
27 [AttributeUsage(AttributeTargets.Class, AllowMultiple =
false, Inherited =
false)]
28 internal class EnumConversionHelperAttribute :
Attribute
32 internal static class StringEnumConversionRegistry
34 private static readonly Dictionary<Type, MethodInfo> FROM_STRING_METHODS =
new Dictionary<Type, MethodInfo>();
35 private static readonly Dictionary<Type, MethodInfo> TO_STRING_METHODS =
new Dictionary<Type, MethodInfo>();
37 static StringEnumConversionRegistry()
40 typeof (StringEnumConversionRegistry).Assembly.GetTypes()
43 type.GetCustomAttributes(
44 typeof (EnumConversionHelperAttribute),
false).Any());
46 foreach (var curConverter
in converters)
50 var toStringConversion = curConverter.GetMethod(
"ToRQLString",
51 BindingFlags.Static | BindingFlags.Public);
53 var fromStringConversion =
54 curConverter.GetMethods(BindingFlags.Static | BindingFlags.Public)
57 methodInfo.GetParameters()
58 .SingleOrDefault(info => info.ParameterType == typeof (
string)) !=
62 toStringConversion.GetParameters()
63 .Single(info => info.ParameterType == fromStringConversion.ReturnType);
65 if (toStringConversion.ReturnType != typeof (
string))
67 throw new Exception(
string.Format(
"Illegal return type for ToRQLString method in class {0}",
71 FROM_STRING_METHODS[fromStringConversion.ReturnType] = fromStringConversion;
72 TO_STRING_METHODS[fromStringConversion.ReturnType] = toStringConversion;
76 string.Format(
"Class {0} is not a legal converter", curConverter.Name), e);
81 public static T ConvertFromString<T>(
string value)
85 return (T) FROM_STRING_METHODS[typeof (T)].Invoke(null,
new object[] {value});
86 }
catch (KeyNotFoundException)
93 public static string ConvertToRQLString<T>(T value) where T :
struct, IConvertible
97 return (
string) TO_STRING_METHODS[typeof (T)].Invoke(null,
new object[] {value});
98 }
catch (KeyNotFoundException)
106 internal class StringEnumConverter<T> : IAttributeConverter<T> where T : struct, IConvertible
108 public T ConvertFrom(
IProjectObject parent, XmlElement element, RedDotAttribute attribute)
110 var strValue = element.GetAttributeValue(attribute.ElementName);
111 return StringEnumConversionRegistry.ConvertFromString<T>(strValue);
114 public bool IsReadOnly {
get;
set; }
116 public void WriteTo(
IProjectObject parent, IXmlReadWriteWrapper writeElement, RedDotAttribute attribute, T value)
118 writeElement.SetAttributeValue(attribute.ElementName, StringEnumConversionRegistry.ConvertToRQLString(value));