2 * Namespace: System.Web.UI
\r
3 * Class: PropertyConverter
\r
5 * Author: Gaurav Vaish
\r
6 * Maintainer: gvaish@iitk.ac.in
\r
7 * Implementation: yes
\r
8 * Contact: <gvaish@iitk.ac.in>
\r
11 * (C) Gaurav Vaish (2001)
\r
15 using System.ComponentModel;
\r
16 using System.Globalization;
\r
17 using System.Reflection;
\r
19 namespace System.Web.UI
\r
21 public sealed class PropertyConverter
\r
23 private static Type[] parseMethodTypes;
\r
24 private static Type[] parseMethodTypesWithSOP;
\r
26 static PropertyConverter()
\r
28 parseMethodTypes = new Type[1];
\r
29 parseMethodTypes[0] = typeof(string);
\r
30 parseMethodTypesWithSOP = new Type[2];
\r
31 parseMethodTypesWithSOP[0] = typeof(string);
\r
32 parseMethodTypesWithSOP[1] = typeof(IServiceProvider);
\r
35 private PropertyConverter()
\r
37 // Prevent any instance
\r
40 public static object EnumFromString(Type enumType, string enumValue)
\r
42 object retVal = null;
\r
45 retVal = Enum.Parse(enumType, enumValue, true);
\r
53 public static string EnumToString(Type enumType, object enumValue)
\r
55 string retVal = Enum.Format(enumType, enumValue, "G");
\r
56 return retVal.Replace('_','-');
\r
59 public static object ObjectFromString(Type objType, MemberInfo propertyInfo, string objValue)
\r
61 if(objValue == null)
\r
63 if(! (!objType.Equals(typeof(Boolean)) || objValue.Length > 0) )
\r
69 return EnumFromString(objType, objValue);
\r
71 if(objType.Equals(typeof(string)))
\r
75 PropertyDescriptor pc = null;
\r
76 if(propertyInfo != null)
\r
78 pc = (TypeDescriptor.GetProperties(propertyInfo.ReflectedType))[propertyInfo.Name];
\r
82 TypeConverter converter = pc.Converter;
\r
83 if(converter!=null && converter.CanConvertFrom(typeof(string)))
\r
85 return converter.ConvertFromInvariantString(objValue);
\r
88 MethodInfo mi = objType.GetMethod("Parse", parseMethodTypesWithSOP);
\r
92 object[] parameters = new object[2];
\r
93 parameters[0] = objValue;
\r
94 parameters[1] = CultureInfo.InvariantCulture;
\r
97 o = Utils.InvokeMethod(mi, null, parameters);
\r
104 mi = objType.GetMethod("Parse", parseMethodTypes);
\r
107 object[] parameters = new object[1];
\r
108 parameters[0] = objValue;
\r
111 o = Utils.InvokeMethod(mi, null, parameters);
\r
119 throw new HttpException(/*HttpRuntime.FormatResourceString(*/"Type_not_creatable_from_string"/*, objType.FullName, objValue, propertyInfo.Name)*/);
\r