-
-
Notifications
You must be signed in to change notification settings - Fork 461
/
FullObjectGraphTraversalStrategy.cs
269 lines (228 loc) · 11.6 KB
/
FullObjectGraphTraversalStrategy.cs
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
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using YamlDotNet.Core;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies
{
/// <summary>
/// An implementation of <see cref="IObjectGraphTraversalStrategy"/> that traverses
/// readable properties, collections and dictionaries.
/// </summary>
public class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy
{
private readonly int maxRecursion;
private readonly ITypeInspector typeDescriptor;
private readonly ITypeResolver typeResolver;
private INamingConvention namingConvention;
public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention)
{
if (maxRecursion <= 0)
{
throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1");
}
if (typeDescriptor == null)
{
throw new ArgumentNullException("typeDescriptor");
}
this.typeDescriptor = typeDescriptor;
if (typeResolver == null)
{
throw new ArgumentNullException("typeResolver");
}
this.typeResolver = typeResolver;
this.maxRecursion = maxRecursion;
this.namingConvention = namingConvention;
}
void IObjectGraphTraversalStrategy.Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context)
{
Traverse("<root>", graph, visitor, context, new Stack<ObjectPathSegment>(maxRecursion));
}
protected struct ObjectPathSegment
{
public object name;
public IObjectDescriptor value;
public ObjectPathSegment(object name, IObjectDescriptor value)
{
this.name = name;
this.value = value;
}
}
protected virtual void Traverse<TContext>(object name, IObjectDescriptor value, IObjectGraphVisitor<TContext> visitor, TContext context, Stack<ObjectPathSegment> path)
{
if (path.Count >= maxRecursion)
{
var message = new StringBuilder();
message.AppendLine("Too much recursion when traversing the object graph.");
message.AppendLine("The path to reach this recursion was:");
var lines = new Stack<KeyValuePair<string, string>>(path.Count);
var maxNameLength = 0;
foreach (var segment in path)
{
var segmentName = TypeConverter.ChangeType<string>(segment.name);
maxNameLength = Math.Max(maxNameLength, segmentName.Length);
lines.Push(new KeyValuePair<string, string>(segmentName, segment.value.Type.FullName));
}
foreach (var line in lines)
{
message
.Append(" -> ")
.Append(line.Key.PadRight(maxNameLength))
.Append(" [")
.Append(line.Value)
.AppendLine("]");
}
throw new MaximumRecursionLevelReachedException(message.ToString());
}
if (!visitor.Enter(value, context))
{
return;
}
path.Push(new ObjectPathSegment(name, value));
try
{
var typeCode = value.Type.GetTypeCode();
switch (typeCode)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.String:
case TypeCode.Char:
case TypeCode.DateTime:
visitor.VisitScalar(value, context);
break;
case TypeCode.Empty:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode));
default:
if (value.IsDbNull())
{
visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context);
}
if (value.Value == null || value.Type == typeof(TimeSpan))
{
visitor.VisitScalar(value, context);
break;
}
var underlyingType = Nullable.GetUnderlyingType(value.Type);
if (underlyingType != null)
{
// This is a nullable type, recursively handle it with its underlying type.
// Note that if it contains null, the condition above already took care of it
Traverse("Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path);
}
else
{
TraverseObject(value, visitor, context, path);
}
break;
}
}
finally
{
path.Pop();
}
}
protected virtual void TraverseObject<TContext>(IObjectDescriptor value, IObjectGraphVisitor<TContext> visitor, TContext context, Stack<ObjectPathSegment> path)
{
if (typeof(IDictionary).IsAssignableFrom(value.Type))
{
TraverseDictionary(value, visitor, typeof(object), typeof(object), context, path);
return;
}
var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IDictionary<,>));
if (genericDictionaryType != null)
{
var adaptedDictionary = new GenericDictionaryToNonGenericAdapter(value.Value, genericDictionaryType);
var genericArguments = genericDictionaryType.GetGenericArguments();
TraverseDictionary(new ObjectDescriptor(adaptedDictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path);
return;
}
if (typeof(IEnumerable).IsAssignableFrom(value.Type))
{
TraverseList(value, visitor, context, path);
return;
}
TraverseProperties(value, visitor, context, path);
}
protected virtual void TraverseDictionary<TContext>(IObjectDescriptor dictionary, IObjectGraphVisitor<TContext> visitor, Type keyType, Type valueType, TContext context, Stack<ObjectPathSegment> path)
{
visitor.VisitMappingStart(dictionary, keyType, valueType, context);
var isDynamic = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject");
foreach (DictionaryEntry entry in (IDictionary)dictionary.Value)
{
var keyValue = isDynamic ? namingConvention.Apply(entry.Key.ToString()) : entry.Key;
var key = GetObjectDescriptor(keyValue, keyType);
var value = GetObjectDescriptor(entry.Value, valueType);
if (visitor.EnterMapping(key, value, context))
{
var keyAsString = TypeConverter.ChangeType<string>(key);
Traverse(keyValue, key, visitor, context, path);
Traverse(keyValue, value, visitor, context, path);
}
}
visitor.VisitMappingEnd(dictionary, context);
}
private void TraverseList<TContext>(IObjectDescriptor value, IObjectGraphVisitor<TContext> visitor, TContext context, Stack<ObjectPathSegment> path)
{
var enumerableType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IEnumerable<>));
var itemType = enumerableType != null ? enumerableType.GetGenericArguments()[0] : typeof(object);
visitor.VisitSequenceStart(value, itemType, context);
var index = 0;
foreach (var item in (IEnumerable)value.Value)
{
Traverse(index, GetObjectDescriptor(item, itemType), visitor, context, path);
++index;
}
visitor.VisitSequenceEnd(value, context);
}
protected virtual void TraverseProperties<TContext>(IObjectDescriptor value, IObjectGraphVisitor<TContext> visitor, TContext context, Stack<ObjectPathSegment> path)
{
visitor.VisitMappingStart(value, typeof(string), typeof(object), context);
foreach (var propertyDescriptor in typeDescriptor.GetProperties(value.Type, value.Value))
{
var propertyValue = propertyDescriptor.Read(value.Value);
if (visitor.EnterMapping(propertyDescriptor, propertyValue, context))
{
Traverse(propertyDescriptor.Name, new ObjectDescriptor(propertyDescriptor.Name, typeof(string), typeof(string)), visitor, context, path);
Traverse(propertyDescriptor.Name, propertyValue, visitor, context, path);
}
}
visitor.VisitMappingEnd(value, context);
}
private IObjectDescriptor GetObjectDescriptor(object value, Type staticType)
{
return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType);
}
}
}