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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Microsoft.Internal.Web.Utils;
namespace System.Web.Helpers
{
internal class ObjectVisitor
{
private static readonly Dictionary<Type, string> _typeNames = new Dictionary<Type, string>
{
{ typeof(string), "string" },
{ typeof(object), "object" },
{ typeof(int), "int" },
{ typeof(byte), "byte" },
{ typeof(short), "short" },
{ typeof(long), "long" },
{ typeof(decimal), "decimal" },
{ typeof(float), "float" },
{ typeof(double), "double" },
{ typeof(bool), "bool" },
{ typeof(char), "char" },
{ typeof(void), "void" }
};
private static readonly char[] _separators = { '&', '[', '*' };
private readonly int _recursionLimit;
private readonly int _enumerationLimit;
private Dictionary<object, string> _visited = new Dictionary<object, string>();
public ObjectVisitor(int recursionLimit, int enumerationLimit)
{
Debug.Assert(enumerationLimit > 0);
Debug.Assert(recursionLimit >= 0);
_enumerationLimit = enumerationLimit;
_recursionLimit = recursionLimit;
}
protected string GetObjectId(object value)
{
string id;
if (_visited.TryGetValue(value, out id))
{
return id;
}
return null;
}
public virtual void Visit(object value, int depth)
{
if (value == null || DBNull.Value.Equals(value))
{
VisitNull();
return;
}
// Check to see if the we've already visited this object
string id;
if (_visited.TryGetValue(value, out id))
{
VisitVisitedObject(id, value);
return;
}
string stringValue = value as string;
if (stringValue != null)
{
VisitStringValue(stringValue);
return;
}
if (TryConvertToString(value, out stringValue))
{
VisitConvertedValue(value, stringValue);
return;
}
// This exceptin occurs when we try to access the property and it fails
// for some reason. The actual exception is wrapped in the ObjectVisitorException
ObjectVisitorException exception = value as ObjectVisitorException;
if (exception != null)
{
VisitObjectVisitorException(exception);
return;
}
// Mark the object as visited
id = CreateObjectId(value);
_visited.Add(value, id);
NameValueCollection nameValueCollection = value as NameValueCollection;
if (nameValueCollection != null)
{
VisitNameValueCollection(nameValueCollection, depth);
return;
}
IDictionary dictionary = value as IDictionary;
if (dictionary != null)
{
VisitDictionary(dictionary, depth);
return;
}
IEnumerable enumerable = value as IEnumerable;
if (enumerable != null)
{
VisitEnumerable(enumerable, depth);
return;
}
VisitComplexObject(value, depth + 1);
}
public virtual void VisitObjectVisitorException(ObjectVisitorException exception)
{
}
public virtual void VisitConvertedValue(object value, string convertedValue)
{
VisitStringValue(convertedValue);
}
public virtual void VisitVisitedObject(string id, object value)
{
}
public virtual void VisitNull()
{
}
public virtual void VisitStringValue(string stringValue)
{
}
public virtual void VisitComplexObject(object value, int depth)
{
if (depth > _recursionLimit)
{
return;
}
Debug.Assert(value != null, "Value should not be null");
var dynamicObject = value as IDynamicMetaObjectProvider;
// Only look at dynamic objects that do not implement ICustomTypeDescriptor
if (dynamicObject != null && !(dynamicObject is ICustomTypeDescriptor))
{
var memberNames = DynamicHelper.GetMemberNames(dynamicObject);
if (memberNames != null)
{
// Always use the runtime type for dynamic objects since there is no metadata
VisitMembers(memberNames,
name => null,
name => DynamicHelper.GetMemberValue(dynamicObject, name),
depth);
}
}
else
{
// REVIEW: We should try to filter out properties of certain types
// Dump properties using type descriptor
var props = TypeDescriptor.GetProperties(value);
var propNames = from PropertyDescriptor p in props
select p.Name;
VisitMembers(propNames,
name => props.Find(name, ignoreCase: true).PropertyType,
name => GetPropertyDescriptorValue(value, name, props),
depth);
// Dump fields
var fields = value.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(field => field.Name);
VisitMembers(fields.Keys,
name => fields[name].FieldType,
name => GetFieldValue(value, name, fields),
depth);
}
}
public virtual void VisitNameValueCollection(NameValueCollection collection, int depth)
{
VisitKeyValues(collection, collection.AllKeys.Cast<object>(), key => collection[(string)key], depth);
}
public virtual void VisitDictionary(IDictionary dictionary, int depth)
{
VisitKeyValues(dictionary, dictionary.Keys.Cast<object>(), key => dictionary[key], depth);
}
public virtual void VisitEnumerable(IEnumerable enumerable, int depth)
{
if (depth > _recursionLimit)
{
return;
}
Type enumerableType = enumerable.GetType();
bool isIndexedEnumeration = ImplementsInterface(enumerableType, typeof(IList<>))
|| ImplementsInterface(enumerableType, typeof(IList));
int index = 0;
foreach (var item in enumerable)
{
if (index >= _enumerationLimit)
{
VisitEnumeratonLimitExceeded();
break;
}
if (isIndexedEnumeration)
{
VisitIndexedEnumeratedValue(index, item, depth);
}
else
{
VisitEnumeratedValue(item, depth);
}
index++;
}
}
public virtual void VisitEnumeratedValue(object item, int depth)
{
Visit(item, depth);
}
public virtual void VisitIndexedEnumeratedValue(int index, object item, int depth)
{
Visit(item, depth);
}
public virtual void VisitEnumeratonLimitExceeded()
{
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to fail surface any exceptions throw from getting property accessors")]
public virtual void VisitMembers(IEnumerable<string> names, Func<string, Type> typeSelector, Func<string, object> valueSelector, int depth)
{
foreach (string name in names)
{
Type type = null;
object value = null;
try
{
// Get the type and value
type = typeSelector(name);
value = valueSelector(name);
// If the type is null try using the runtime type
if (value != null && type == null)
{
type = value.GetType();
}
}
catch (Exception ex)
{
// Set the value as an exception we know about
value = new ObjectVisitorException(null, ex);
}
finally
{
VisitMember(name, type, value, depth);
}
}
}
public virtual void VisitMember(string name, Type type, object value, int depth)
{
Visit(value, depth);
}
public virtual void VisitKeyValues(object value, IEnumerable<object> keys, Func<object, object> valueSelector, int depth)
{
if (depth > _recursionLimit)
{
return;
}
foreach (var key in keys)
{
VisitKeyValue(key, valueSelector(key), depth);
}
}
public virtual void VisitKeyValue(object key, object value, int depth)
{
// Dump the key and value
Visit(key, depth);
Visit(value, depth);
}
protected virtual string CreateObjectId(object value)
{
// REVIEW: Maybe use a guid?
return value.GetHashCode().ToString(CultureInfo.InvariantCulture);
}
internal static string GetTypeName(Type type)
{
// See if we have the type name stored
string typeName;
if (_typeNames.TryGetValue(type, out typeName))
{
return typeName;
}
if (type.IsGenericType)
{
// Get the generic type name without arguments
string genericTypeName = GetGenericTypeName(type);
// Create a user friendly type name
var arguments = from argType in type.GetGenericArguments()
select GetTypeName(argType);
return String.Format(CultureInfo.InvariantCulture, "{0}<{1}>", genericTypeName, String.Join(", ", arguments));
}
if (type.IsByRef || type.IsArray || type.IsPointer)
{
// Get the element type name
string elementTypeName = GetTypeName(type.GetElementType());
// Append the separator
int sepIndex = type.Name.IndexOfAny(_separators);
return elementTypeName + type.Name.Substring(sepIndex);
}
// Fallback to using the type name as is
return type.Name;
}
private static string GetGenericTypeName(Type type)
{
Debug.Assert(type.IsGenericType, "Type is not a generic type");
// Check for anonymous types
if (IsAnonymousType(type))
{
return "AnonymousType";
}
string genericTypeDefinitionName = type.GetGenericTypeDefinition().Name;
int index = genericTypeDefinitionName.IndexOf('`');
Debug.Assert(index >= 0);
// Get the generic type name without the `
return genericTypeDefinitionName.Substring(0, index);
}
// Copied from System.Web.WebPages/Util/TypeHelpers.cs
private static bool IsAnonymousType(Type type)
{
Debug.Assert(type != null, "Type should not be null");
// TODO: The only way to detect anonymous types right now.
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
private static bool ImplementsInterface(Type type, Type targetInterfaceType)
{
Func<Type, bool> implementsInterface = t => targetInterfaceType.IsAssignableFrom(t);
if (targetInterfaceType.IsGenericType)
{
implementsInterface = t => t.IsGenericType && targetInterfaceType.IsAssignableFrom(t.GetGenericTypeDefinition());
}
return implementsInterface(type) || type.GetInterfaces().Any(implementsInterface);
}
private static object GetFieldValue(object value, string name, IDictionary<string, FieldInfo> fields)
{
FieldInfo fieldInfo;
// Get the value from the dictionary
bool result = fields.TryGetValue(name, out fieldInfo);
Debug.Assert(result, "Entry should exist");
return fieldInfo.GetValue(value);
}
private static object GetPropertyDescriptorValue(object value, string name, PropertyDescriptorCollection props)
{
PropertyDescriptor propertyDescriptor = props.Find(name, ignoreCase: true);
Debug.Assert(propertyDescriptor != null, "Property descriptor shouldn't be null");
return propertyDescriptor.GetValue(value);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to surface any exceptions while trying to convert from string")]
private static bool TryConvertToString(object value, out string stringValue)
{
stringValue = null;
try
{
IConvertible convertibe = value as IConvertible;
if (convertibe != null)
{
stringValue = convertibe.ToString(CultureInfo.CurrentCulture);
return true;
}
TypeConverter converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertFrom(typeof(string)))
{
stringValue = converter.ConvertToString(value);
return true;
}
Type type = value.GetType();
if (type == typeof(object))
{
stringValue = value.ToString();
return true;
}
Type valueAsType = value as Type;
if (valueAsType != null)
{
stringValue = "typeof(" + GetTypeName(valueAsType) + ")";
return true;
}
}
catch (Exception)
{
// If we failed to convert the type for any reason return false
}
return false;
}
[Serializable]
public class ObjectVisitorException : Exception
{
public ObjectVisitorException()
{
}
public ObjectVisitorException(string message)
: base(message)
{
}
public ObjectVisitorException(string message, Exception inner)
: base(message, inner)
{
}
protected ObjectVisitorException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
}
}
}
|