1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
/**
* Namespace: System.Web.UI
* Class: PropertyConverter
*
* Author: Gaurav Vaish
* Maintainer: gvaish@iitk.ac.in
* Implementation: yes
* Contact: <gvaish@iitk.ac.in>
* Status: 100%
*
* (C) Gaurav Vaish (2001)
*/
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
namespace System.Web.UI
{
public sealed class PropertyConverter
{
private static Type[] parseMethodTypes;
private static Type[] parseMethodTypesWithSOP;
static PropertyConverter()
{
parseMethodTypes = new Type[1];
parseMethodTypes[0] = typeof(string);
parseMethodTypesWithSOP = new Type[2];
parseMethodTypesWithSOP[0] = typeof(string);
parseMethodTypesWithSOP[1] = typeof(IServiceProvider);
}
private PropertyConverter()
{
// Prevent any instance
}
public static object EnumFromString(Type enumType, string enumValue)
{
object retVal = null;
try
{
retVal = Enum.Parse(enumType, enumValue, true);
} catch
{
retVal = null;
}
return retVal;
}
public static string EnumToString(Type enumType, object enumValue)
{
string retVal = Enum.Format(enumType, enumValue, "G");
return retVal.Replace('_','-');
}
public static object ObjectFromString(Type objType, MemberInfo propertyInfo, string objValue)
{
if(objValue == null)
return null;
if(! (!objType.Equals(typeof(Boolean)) || objValue.Length > 0) )
{
return null;
}
if(objType.IsEnum)
{
return EnumFromString(objType, objValue);
}
if(objType.Equals(typeof(string)))
{
return objValue;
}
PropertyDescriptor pc = null;
if(propertyInfo != null)
{
pc = (TypeDescriptor.GetProperties(propertyInfo.ReflectedType))[propertyInfo.Name];
}
if(pc != null)
{
TypeConverter converter = pc.Converter;
if(converter!=null && converter.CanConvertFrom(typeof(string)))
{
return converter.ConvertFromInvariantString(objValue);
}
}
MethodInfo mi = objType.GetMethod("Parse", parseMethodTypesWithSOP);
object o = null;
if(mi != null)
{
object[] parameters = new object[2];
parameters[0] = objValue;
parameters[1] = CultureInfo.InvariantCulture;
try
{
o = Utils.InvokeMethod(mi, null, parameters);
} catch
{
}
}
if(o == null)
{
mi = objType.GetMethod("Parse", parseMethodTypes);
if(mi!=null)
{
object[] parameters = new object[1];
parameters[0] = objValue;
try
{
o = Utils.InvokeMethod(mi, null, parameters);
} catch
{
}
}
}
if(o == null)
{
throw new HttpException(/*HttpRuntime.FormatResourceString(*/"Type_not_creatable_from_string"/*, objType.FullName, objValue, propertyInfo.Name)*/);
}
return o;
}
}
}
|