~ubuntu-branches/ubuntu/trusty/smuxi/trusty-proposed

« back to all changes in this revision

Viewing changes to lib/Newtonsoft.Json/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs

  • Committer: Package Import Robot
  • Author(s): Mirco Bauer
  • Date: 2013-05-25 22:11:31 UTC
  • mfrom: (1.2.12)
  • Revision ID: package-import@ubuntu.com-20130525221131-nd2mc0kzubuwyx20
Tags: 0.8.11-1
* [22d13d5] Imported Upstream version 0.8.11
* [6d2b95a] Refreshed patches
* [89eb66e] Added ServiceStack libraries to smuxi-engine package
* [848ab10] Enable Campfire engine
* [c6dbdc7] Always build db4o for predictable build result
* [13ec489] Exclude OS X specific libraries from dh_clideps

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#region License
2
 
// Copyright (c) 2007 James Newton-King
3
 
//
4
 
// Permission is hereby granted, free of charge, to any person
5
 
// obtaining a copy of this software and associated documentation
6
 
// files (the "Software"), to deal in the Software without
7
 
// restriction, including without limitation the rights to use,
8
 
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 
// copies of the Software, and to permit persons to whom the
10
 
// Software is furnished to do so, subject to the following
11
 
// conditions:
12
 
//
13
 
// The above copyright notice and this permission notice shall be
14
 
// included in all copies or substantial portions of the Software.
15
 
//
16
 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
 
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
 
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
 
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
 
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
 
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
 
// OTHER DEALINGS IN THE SOFTWARE.
24
 
#endregion
25
 
 
26
 
using System;
27
 
using System.Collections;
28
 
using System.Collections.Generic;
29
 
using System.ComponentModel;
30
 
using System.Globalization;
31
 
using System.Linq;
32
 
using System.Reflection;
33
 
using System.Runtime.Serialization;
34
 
using System.Security.Permissions;
35
 
using Newtonsoft.Json.Converters;
36
 
using Newtonsoft.Json.Utilities;
37
 
using Newtonsoft.Json.Linq;
38
 
using System.Runtime.CompilerServices;
39
 
 
40
 
namespace Newtonsoft.Json.Serialization
41
 
{
42
 
  internal struct ResolverContractKey : IEquatable<ResolverContractKey>
43
 
  {
44
 
    private readonly Type _resolverType;
45
 
    private readonly Type _contractType;
46
 
 
47
 
    public ResolverContractKey(Type resolverType, Type contractType)
48
 
    {
49
 
      _resolverType = resolverType;
50
 
      _contractType = contractType;
51
 
    }
52
 
 
53
 
    public override int GetHashCode()
54
 
    {
55
 
      return _resolverType.GetHashCode() ^ _contractType.GetHashCode();
56
 
    }
57
 
 
58
 
    public override bool Equals(object obj)
59
 
    {
60
 
      if (!(obj is ResolverContractKey))
61
 
        return false;
62
 
 
63
 
      return Equals((ResolverContractKey) obj);
64
 
    }
65
 
 
66
 
    public bool Equals(ResolverContractKey other)
67
 
    {
68
 
      return (_resolverType == other._resolverType && _contractType == other._contractType);
69
 
    }
70
 
  }
71
 
 
72
 
  /// <summary>
73
 
  /// Used by <see cref="JsonSerializer"/> to resolves a <see cref="JsonContract"/> for a given <see cref="Type"/>.
74
 
  /// </summary>
75
 
  public class DefaultContractResolver : IContractResolver
76
 
  {
77
 
    internal static readonly IContractResolver Instance = new DefaultContractResolver(true);
78
 
    private static readonly IList<JsonConverter> BuiltInConverters = new List<JsonConverter>
79
 
      {
80
 
#if !PocketPC && !SILVERLIGHT && !NET20
81
 
        new EntityKeyMemberConverter(),
82
 
#endif
83
 
        new BinaryConverter(),
84
 
        new KeyValuePairConverter(),
85
 
#if !SILVERLIGHT
86
 
        new XmlNodeConverter(),
87
 
        new DataSetConverter(),
88
 
        new DataTableConverter(),
89
 
#endif
90
 
        new BsonObjectIdConverter()
91
 
      };
92
 
 
93
 
    private static Dictionary<ResolverContractKey, JsonContract> _sharedContractCache;
94
 
    private static readonly object _typeContractCacheLock = new object();
95
 
 
96
 
    private Dictionary<ResolverContractKey, JsonContract> _instanceContractCache;
97
 
    private readonly bool _sharedCache;
98
 
 
99
 
    /// <summary>
100
 
    /// Gets a value indicating whether members are being get and set using dynamic code generation.
101
 
    /// This value is determined by the runtime permissions available.
102
 
    /// </summary>
103
 
    /// <value>
104
 
    ///         <c>true</c> if using dynamic code generation; otherwise, <c>false</c>.
105
 
    /// </value>
106
 
    public bool DynamicCodeGeneration
107
 
    {
108
 
      get { return JsonTypeReflector.DynamicCodeGeneration; }
109
 
    }
110
 
 
111
 
    /// <summary>
112
 
    /// Gets or sets the default members search flags.
113
 
    /// </summary>
114
 
    /// <value>The default members search flags.</value>
115
 
    public BindingFlags DefaultMembersSearchFlags { get; set; }
116
 
 
117
 
    /// <summary>
118
 
    /// Gets or sets a value indicating whether compiler generated members should be serialized.
119
 
    /// </summary>
120
 
    /// <value>
121
 
    ///         <c>true</c> if serialized compiler generated members; otherwise, <c>false</c>.
122
 
    /// </value>
123
 
    public bool SerializeCompilerGeneratedMembers { get; set; }
124
 
 
125
 
    /// <summary>
126
 
    /// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
127
 
    /// </summary>
128
 
    public DefaultContractResolver()
129
 
      : this(false)
130
 
    {
131
 
    }
132
 
 
133
 
    /// <summary>
134
 
    /// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
135
 
    /// </summary>
136
 
    /// <param name="shareCache">
137
 
    /// If set to <c>true</c> the <see cref="DefaultContractResolver"/> will use a cached shared with other resolvers of the same type.
138
 
    /// Sharing the cache will significantly performance because expensive reflection will only happen once but could cause unexpected
139
 
    /// behavior if different instances of the resolver are suppose to produce different results. When set to false it is highly
140
 
    /// recommended to reuse <see cref="DefaultContractResolver"/> instances with the <see cref="JsonSerializer"/>.
141
 
    /// </param>
142
 
    public DefaultContractResolver(bool shareCache)
143
 
    {
144
 
      DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance;
145
 
      _sharedCache = shareCache;
146
 
    }
147
 
 
148
 
    private Dictionary<ResolverContractKey, JsonContract> GetCache()
149
 
    {
150
 
      if (_sharedCache)
151
 
        return _sharedContractCache;
152
 
      else
153
 
        return _instanceContractCache;
154
 
    }
155
 
 
156
 
    private void UpdateCache(Dictionary<ResolverContractKey, JsonContract> cache)
157
 
    {
158
 
      if (_sharedCache)
159
 
        _sharedContractCache = cache;
160
 
      else
161
 
        _instanceContractCache = cache;
162
 
    }
163
 
 
164
 
    /// <summary>
165
 
    /// Resolves the contract for a given type.
166
 
    /// </summary>
167
 
    /// <param name="type">The type to resolve a contract for.</param>
168
 
    /// <returns>The contract for a given type.</returns>
169
 
    public virtual JsonContract ResolveContract(Type type)
170
 
    {
171
 
      if (type == null)
172
 
        throw new ArgumentNullException("type");
173
 
 
174
 
      JsonContract contract;
175
 
      ResolverContractKey key = new ResolverContractKey(GetType(), type);
176
 
      Dictionary<ResolverContractKey, JsonContract> cache = GetCache();
177
 
      if (cache == null || !cache.TryGetValue(key, out contract))
178
 
      {
179
 
        contract = CreateContract(type);
180
 
 
181
 
        // avoid the possibility of modifying the cache dictionary while another thread is accessing it
182
 
        lock (_typeContractCacheLock)
183
 
        {
184
 
          cache = GetCache();
185
 
          Dictionary<ResolverContractKey, JsonContract> updatedCache =
186
 
            (cache != null)
187
 
              ? new Dictionary<ResolverContractKey, JsonContract>(cache)
188
 
              : new Dictionary<ResolverContractKey, JsonContract>();
189
 
          updatedCache[key] = contract;
190
 
 
191
 
          UpdateCache(updatedCache);
192
 
        }
193
 
      }
194
 
 
195
 
      return contract;
196
 
    }
197
 
 
198
 
    /// <summary>
199
 
    /// Gets the serializable members for the type.
200
 
    /// </summary>
201
 
    /// <param name="objectType">The type to get serializable members for.</param>
202
 
    /// <returns>The serializable members for the type.</returns>
203
 
    protected virtual List<MemberInfo> GetSerializableMembers(Type objectType)
204
 
    {
205
 
#if !PocketPC && !NET20
206
 
      DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
207
 
#endif
208
 
 
209
 
      List<MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
210
 
        .Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
211
 
      List<MemberInfo> allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
212
 
        .Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
213
 
 
214
 
      List<MemberInfo> serializableMembers = new List<MemberInfo>();
215
 
      foreach (MemberInfo member in allMembers)
216
 
      {
217
 
        // exclude members that are compiler generated if set
218
 
        if (SerializeCompilerGeneratedMembers || !member.IsDefined(typeof(CompilerGeneratedAttribute), true))
219
 
        {
220
 
          if (defaultMembers.Contains(member))
221
 
          {
222
 
            // add all members that are found by default member search
223
 
            serializableMembers.Add(member);
224
 
          }
225
 
          else
226
 
          {
227
 
            // add members that are explicitly marked with JsonProperty/DataMember attribute
228
 
            if (JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member) != null)
229
 
              serializableMembers.Add(member);
230
 
#if !PocketPC && !NET20
231
 
            else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(member) != null)
232
 
              serializableMembers.Add(member);
233
 
#endif
234
 
          }
235
 
        }
236
 
      }
237
 
 
238
 
#if !PocketPC && !SILVERLIGHT && !NET20
239
 
      Type match;
240
 
      // don't include EntityKey on entities objects... this is a bit hacky
241
 
      if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out match))
242
 
        serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList();
243
 
#endif
244
 
 
245
 
      return serializableMembers;
246
 
    }
247
 
 
248
 
#if !PocketPC && !SILVERLIGHT && !NET20
249
 
    private bool ShouldSerializeEntityMember(MemberInfo memberInfo)
250
 
    {
251
 
      PropertyInfo propertyInfo = memberInfo as PropertyInfo;
252
 
      if (propertyInfo != null)
253
 
      {
254
 
        if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1")
255
 
          return false;
256
 
      }
257
 
 
258
 
      return true;
259
 
    }
260
 
#endif
261
 
 
262
 
    /// <summary>
263
 
    /// Creates a <see cref="JsonObjectContract"/> for the given type.
264
 
    /// </summary>
265
 
    /// <param name="objectType">Type of the object.</param>
266
 
    /// <returns>A <see cref="JsonObjectContract"/> for the given type.</returns>
267
 
    protected virtual JsonObjectContract CreateObjectContract(Type objectType)
268
 
    {
269
 
      JsonObjectContract contract = new JsonObjectContract(objectType);
270
 
      InitializeContract(contract);
271
 
 
272
 
      contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType);
273
 
      contract.Properties.AddRange(CreateProperties(contract));
274
 
      if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic)
275
 
        contract.ParametrizedConstructor = GetParametrizedConstructor(objectType);
276
 
 
277
 
      return contract;
278
 
    }
279
 
 
280
 
    private ConstructorInfo GetParametrizedConstructor(Type objectType)
281
 
    {
282
 
      ConstructorInfo[] constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
283
 
 
284
 
      if (constructors.Length == 1)
285
 
        return constructors[0];
286
 
      else
287
 
        return null;
288
 
    }
289
 
 
290
 
    /// <summary>
291
 
    /// Resolves the default <see cref="JsonConverter" /> for the contract.
292
 
    /// </summary>
293
 
    /// <param name="objectType">Type of the object.</param>
294
 
    /// <returns></returns>
295
 
    protected virtual JsonConverter ResolveContractConverter(Type objectType)
296
 
    {
297
 
      return JsonTypeReflector.GetJsonConverter(objectType, objectType);
298
 
    }
299
 
 
300
 
    private Func<object> GetDefaultCreator(Type createdType)
301
 
    {
302
 
      return JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
303
 
    }
304
 
 
305
 
    private void InitializeContract(JsonContract contract)
306
 
    {
307
 
      JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.UnderlyingType);
308
 
      if (containerAttribute != null)
309
 
      {
310
 
        contract.IsReference = containerAttribute._isReference;
311
 
      }
312
 
#if !PocketPC && !NET20
313
 
      else
314
 
      {
315
 
        DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.UnderlyingType);
316
 
        // doesn't have a null value
317
 
        if (dataContractAttribute != null && dataContractAttribute.IsReference)
318
 
          contract.IsReference = true;
319
 
      }
320
 
#endif
321
 
 
322
 
      contract.Converter = ResolveContractConverter(contract.UnderlyingType);
323
 
 
324
 
      // then see whether object is compadible with any of the built in converters
325
 
      contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.UnderlyingType);
326
 
 
327
 
      if (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true)
328
 
        || contract.CreatedType.IsValueType)
329
 
      {
330
 
        contract.DefaultCreator = GetDefaultCreator(contract.CreatedType);
331
 
 
332
 
        contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType &&
333
 
                                            ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null);
334
 
      }
335
 
 
336
 
      foreach (MethodInfo method in contract.UnderlyingType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
337
 
      {
338
 
        // compact framework errors when getting parameters for a generic method
339
 
        // lame, but generic methods should not be callbacks anyway
340
 
        if (method.ContainsGenericParameters)
341
 
          continue;
342
 
 
343
 
        Type prevAttributeType = null;
344
 
        ParameterInfo[] parameters = method.GetParameters();
345
 
 
346
 
#if !PocketPC
347
 
        if (IsValidCallback(method, parameters, typeof(OnSerializingAttribute), contract.OnSerializing, ref prevAttributeType))
348
 
        {
349
 
          contract.OnSerializing = method;
350
 
        }
351
 
        if (IsValidCallback(method, parameters, typeof(OnSerializedAttribute), contract.OnSerialized, ref prevAttributeType))
352
 
        {
353
 
          contract.OnSerialized = method;
354
 
        }
355
 
        if (IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), contract.OnDeserializing, ref prevAttributeType))
356
 
        {
357
 
          contract.OnDeserializing = method;
358
 
        }
359
 
        if (IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), contract.OnDeserialized, ref prevAttributeType))
360
 
        {
361
 
          contract.OnDeserialized = method;
362
 
        }
363
 
#endif
364
 
        if (IsValidCallback(method, parameters, typeof(OnErrorAttribute), contract.OnError, ref prevAttributeType))
365
 
        {
366
 
          contract.OnError = method;
367
 
        }
368
 
      }
369
 
    }
370
 
 
371
 
    /// <summary>
372
 
    /// Creates a <see cref="JsonDictionaryContract"/> for the given type.
373
 
    /// </summary>
374
 
    /// <param name="objectType">Type of the object.</param>
375
 
    /// <returns>A <see cref="JsonDictionaryContract"/> for the given type.</returns>
376
 
    protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
377
 
    {
378
 
      JsonDictionaryContract contract = new JsonDictionaryContract(objectType);
379
 
      InitializeContract(contract);
380
 
 
381
 
      return contract;
382
 
    }
383
 
 
384
 
    /// <summary>
385
 
    /// Creates a <see cref="JsonArrayContract"/> for the given type.
386
 
    /// </summary>
387
 
    /// <param name="objectType">Type of the object.</param>
388
 
    /// <returns>A <see cref="JsonArrayContract"/> for the given type.</returns>
389
 
    protected virtual JsonArrayContract CreateArrayContract(Type objectType)
390
 
    {
391
 
      JsonArrayContract contract = new JsonArrayContract(objectType);
392
 
      InitializeContract(contract);
393
 
 
394
 
      return contract;
395
 
    }
396
 
 
397
 
    /// <summary>
398
 
    /// Creates a <see cref="JsonPrimitiveContract"/> for the given type.
399
 
    /// </summary>
400
 
    /// <param name="objectType">Type of the object.</param>
401
 
    /// <returns>A <see cref="JsonPrimitiveContract"/> for the given type.</returns>
402
 
    protected virtual JsonPrimitiveContract CreatePrimitiveContract(Type objectType)
403
 
    {
404
 
      JsonPrimitiveContract contract = new JsonPrimitiveContract(objectType);
405
 
      InitializeContract(contract);
406
 
      
407
 
      return contract;
408
 
    }
409
 
 
410
 
    /// <summary>
411
 
    /// Creates a <see cref="JsonLinqContract"/> for the given type.
412
 
    /// </summary>
413
 
    /// <param name="objectType">Type of the object.</param>
414
 
    /// <returns>A <see cref="JsonLinqContract"/> for the given type.</returns>
415
 
    protected virtual JsonLinqContract CreateLinqContract(Type objectType)
416
 
    {
417
 
      JsonLinqContract contract = new JsonLinqContract(objectType);
418
 
      InitializeContract(contract);
419
 
 
420
 
      return contract;
421
 
    }
422
 
 
423
 
#if !SILVERLIGHT && !PocketPC
424
 
    /// <summary>
425
 
    /// Creates a <see cref="JsonISerializableContract"/> for the given type.
426
 
    /// </summary>
427
 
    /// <param name="objectType">Type of the object.</param>
428
 
    /// <returns>A <see cref="JsonISerializableContract"/> for the given type.</returns>
429
 
    protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
430
 
    {
431
 
      JsonISerializableContract contract = new JsonISerializableContract(objectType);
432
 
      InitializeContract(contract);
433
 
 
434
 
      ConstructorInfo constructorInfo = objectType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new [] {typeof (SerializationInfo), typeof (StreamingContext)}, null);
435
 
      if (constructorInfo != null)
436
 
      {
437
 
        MethodCall<object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(constructorInfo);
438
 
 
439
 
        contract.ISerializableCreator = (args => methodCall(null, args));
440
 
      }
441
 
 
442
 
      return contract;
443
 
    }
444
 
#endif
445
 
 
446
 
    /// <summary>
447
 
    /// Creates a <see cref="JsonStringContract"/> for the given type.
448
 
    /// </summary>
449
 
    /// <param name="objectType">Type of the object.</param>
450
 
    /// <returns>A <see cref="JsonStringContract"/> for the given type.</returns>
451
 
    protected virtual JsonStringContract CreateStringContract(Type objectType)
452
 
    {
453
 
      JsonStringContract contract = new JsonStringContract(objectType);
454
 
      InitializeContract(contract);
455
 
 
456
 
      return contract;
457
 
    }
458
 
 
459
 
    /// <summary>
460
 
    /// Determines which contract type is created for the given type.
461
 
    /// </summary>
462
 
    /// <param name="objectType">Type of the object.</param>
463
 
    /// <returns>A <see cref="JsonContract"/> for the given type.</returns>
464
 
    protected virtual JsonContract CreateContract(Type objectType)
465
 
    {
466
 
      if (JsonConvert.IsJsonPrimitiveType(objectType))
467
 
        return CreatePrimitiveContract(objectType);
468
 
 
469
 
      if (JsonTypeReflector.GetJsonObjectAttribute(objectType) != null)
470
 
        return CreateObjectContract(objectType);
471
 
 
472
 
      if (JsonTypeReflector.GetJsonArrayAttribute(objectType) != null)
473
 
        return CreateArrayContract(objectType);
474
 
 
475
 
      if (objectType.IsSubclassOf(typeof(JToken)))
476
 
        return CreateLinqContract(objectType);
477
 
 
478
 
      if (CollectionUtils.IsDictionaryType(objectType))
479
 
        return CreateDictionaryContract(objectType);
480
 
 
481
 
      if (typeof(IEnumerable).IsAssignableFrom(objectType))
482
 
        return CreateArrayContract(objectType);
483
 
 
484
 
      if (CanConvertToString(objectType))
485
 
        return CreateStringContract(objectType);
486
 
 
487
 
#if !SILVERLIGHT && !PocketPC
488
 
      if (typeof(ISerializable).IsAssignableFrom(objectType))
489
 
        return CreateISerializableContract(objectType);
490
 
#endif
491
 
 
492
 
      return CreateObjectContract(objectType);
493
 
    }
494
 
 
495
 
    internal static bool CanConvertToString(Type type)
496
 
    {
497
 
#if !PocketPC
498
 
      TypeConverter converter = ConvertUtils.GetConverter(type);
499
 
 
500
 
      // use the objectType's TypeConverter if it has one and can convert to a string
501
 
      if (converter != null
502
 
#if !SILVERLIGHT
503
 
 && !(converter is ComponentConverter)
504
 
 && !(converter is ReferenceConverter)
505
 
#endif
506
 
 && converter.GetType() != typeof(TypeConverter))
507
 
      {
508
 
        if (converter.CanConvertTo(typeof(string)))
509
 
          return true;
510
 
      }
511
 
#endif
512
 
 
513
 
      if (type == typeof(Type) || type.IsSubclassOf(typeof(Type)))
514
 
        return true;
515
 
 
516
 
#if SILVERLIGHT || PocketPC
517
 
      if (type == typeof(Guid) || type == typeof(Uri) || type == typeof(TimeSpan))
518
 
        return true;
519
 
#endif
520
 
 
521
 
      return false;
522
 
    }
523
 
 
524
 
    private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
525
 
    {
526
 
      if (!method.IsDefined(attributeType, false))
527
 
        return false;
528
 
 
529
 
      if (currentCallback != null)
530
 
        throw new Exception("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType));
531
 
 
532
 
      if (prevAttributeType != null)
533
 
        throw new Exception("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method));
534
 
 
535
 
      if (method.IsVirtual)
536
 
        throw new Exception("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType));
537
 
 
538
 
      if (method.ReturnType != typeof(void))
539
 
        throw new Exception("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method));
540
 
 
541
 
      if (attributeType == typeof(OnErrorAttribute))
542
 
      {
543
 
        if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
544
 
          throw new Exception("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof (StreamingContext), typeof(ErrorContext)));
545
 
      }
546
 
      else
547
 
      {
548
 
        if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
549
 
          throw new Exception("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext)));
550
 
      }
551
 
 
552
 
      prevAttributeType = attributeType;
553
 
 
554
 
      return true;
555
 
    }
556
 
 
557
 
    internal static string GetClrTypeFullName(Type type)
558
 
    {
559
 
      if (type.IsGenericTypeDefinition || !type.ContainsGenericParameters)
560
 
        return type.FullName;
561
 
 
562
 
      return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { type.Namespace, type.Name });
563
 
    }
564
 
 
565
 
    /// <summary>
566
 
    /// Creates properties for the given <see cref="JsonObjectContract"/>.
567
 
    /// </summary>
568
 
    /// <param name="contract">The contract to create properties for.</param>
569
 
    /// <returns>Properties for the given <see cref="JsonObjectContract"/>.</returns>
570
 
    protected virtual IList<JsonProperty> CreateProperties(JsonObjectContract contract)
571
 
    {
572
 
      List<MemberInfo> members = GetSerializableMembers(contract.UnderlyingType);
573
 
      if (members == null)
574
 
        throw new JsonSerializationException("Null collection of seralizable members returned.");
575
 
 
576
 
      JsonPropertyCollection properties = new JsonPropertyCollection(contract);
577
 
 
578
 
      foreach (MemberInfo member in members)
579
 
      {
580
 
        JsonProperty property = CreateProperty(contract, member);
581
 
 
582
 
        if (property != null)
583
 
          properties.AddProperty(property);
584
 
      }
585
 
 
586
 
      return properties;
587
 
    }
588
 
 
589
 
    /// <summary>
590
 
    /// Creates the <see cref="IValueProvider"/> used by the serializer to get and set values from a member.
591
 
    /// </summary>
592
 
    /// <param name="member">The member.</param>
593
 
    /// <returns>The <see cref="IValueProvider"/> used by the serializer to get and set values from a member.</returns>
594
 
    protected virtual IValueProvider CreateMemberValueProvider(MemberInfo member)
595
 
    {
596
 
#if !PocketPC && !SILVERLIGHT
597
 
      if (DynamicCodeGeneration)
598
 
        return new DynamicValueProvider(member);
599
 
#endif
600
 
 
601
 
      return new ReflectionValueProvider(member);
602
 
    }
603
 
 
604
 
    /// <summary>
605
 
    /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
606
 
    /// </summary>
607
 
    /// <param name="contract">The member's declaring types <see cref="JsonObjectContract"/>.</param>
608
 
    /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
609
 
    /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
610
 
    protected virtual JsonProperty CreateProperty(JsonObjectContract contract, MemberInfo member)
611
 
    {
612
 
      JsonProperty property = new JsonProperty();
613
 
      property.PropertyType = ReflectionUtils.GetMemberUnderlyingType(member);
614
 
      property.ValueProvider = CreateMemberValueProvider(member);
615
 
      
616
 
      // resolve converter for property
617
 
      // the class type might have a converter but the property converter takes presidence
618
 
      property.Converter = JsonTypeReflector.GetJsonConverter(member, property.PropertyType);
619
 
 
620
 
#if !PocketPC && !NET20
621
 
      DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(member.DeclaringType);
622
 
 
623
 
      DataMemberAttribute dataMemberAttribute;
624
 
      if (dataContractAttribute != null)
625
 
        dataMemberAttribute = JsonTypeReflector.GetAttribute<DataMemberAttribute>(member);
626
 
      else
627
 
        dataMemberAttribute = null;
628
 
#endif
629
 
 
630
 
      JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member);
631
 
      bool hasIgnoreAttribute = (JsonTypeReflector.GetAttribute<JsonIgnoreAttribute>(member) != null);
632
 
 
633
 
      string mappedName;
634
 
      if (propertyAttribute != null && propertyAttribute.PropertyName != null)
635
 
        mappedName = propertyAttribute.PropertyName;
636
 
#if !PocketPC && !NET20
637
 
      else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
638
 
        mappedName = dataMemberAttribute.Name;
639
 
#endif
640
 
      else
641
 
        mappedName = member.Name;
642
 
 
643
 
      property.PropertyName = ResolvePropertyName(mappedName);
644
 
 
645
 
      if (propertyAttribute != null)
646
 
        property.Required = propertyAttribute.Required;
647
 
#if !PocketPC && !NET20
648
 
      else if (dataMemberAttribute != null)
649
 
        property.Required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
650
 
#endif
651
 
      else
652
 
        property.Required = Required.Default;
653
 
 
654
 
      property.Ignored = (hasIgnoreAttribute ||
655
 
                      (contract.MemberSerialization == MemberSerialization.OptIn
656
 
                       && propertyAttribute == null
657
 
#if !PocketPC && !NET20
658
 
                       && dataMemberAttribute == null
659
 
#endif
660
 
));
661
 
 
662
 
      bool allowNonPublicAccess = false;
663
 
      if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
664
 
        allowNonPublicAccess = true;
665
 
      if (propertyAttribute != null)
666
 
        allowNonPublicAccess = true;
667
 
#if !PocketPC && !NET20
668
 
      if (dataMemberAttribute != null)
669
 
        allowNonPublicAccess = true;
670
 
#endif
671
 
 
672
 
      property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
673
 
      property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess);
674
 
 
675
 
      property.MemberConverter = JsonTypeReflector.GetJsonConverter(member, ReflectionUtils.GetMemberUnderlyingType(member));
676
 
 
677
 
      DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute<DefaultValueAttribute>(member);
678
 
      property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;
679
 
 
680
 
      property.NullValueHandling = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
681
 
      property.DefaultValueHandling = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
682
 
      property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
683
 
      property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
684
 
      property.TypeNameHandling = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
685
 
      property.IsReference = (propertyAttribute != null) ? propertyAttribute._isReference : null;
686
 
 
687
 
      property.ShouldSerialize = CreateShouldSerializeTest(member);
688
 
 
689
 
      return property;
690
 
    }
691
 
 
692
 
    private Predicate<object> CreateShouldSerializeTest(MemberInfo member)
693
 
    {
694
 
      MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, new Type[0]);
695
 
 
696
 
      if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool))
697
 
        return null;
698
 
 
699
 
      MethodCall<object, object> shouldSerializeCall =
700
 
        JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(shouldSerializeMethod);
701
 
 
702
 
      return o => (bool) shouldSerializeCall(o);
703
 
    }
704
 
 
705
 
    /// <summary>
706
 
    /// Resolves the name of the property.
707
 
    /// </summary>
708
 
    /// <param name="propertyName">Name of the property.</param>
709
 
    /// <returns>Name of the property.</returns>
710
 
    protected virtual string ResolvePropertyName(string propertyName)
711
 
    {
712
 
      return propertyName;
713
 
    }
714
 
  }
 
1
#region License
 
2
// Copyright (c) 2007 James Newton-King
 
3
//
 
4
// Permission is hereby granted, free of charge, to any person
 
5
// obtaining a copy of this software and associated documentation
 
6
// files (the "Software"), to deal in the Software without
 
7
// restriction, including without limitation the rights to use,
 
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
 
9
// copies of the Software, and to permit persons to whom the
 
10
// Software is furnished to do so, subject to the following
 
11
// conditions:
 
12
//
 
13
// The above copyright notice and this permission notice shall be
 
14
// included in all copies or substantial portions of the Software.
 
15
//
 
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 
23
// OTHER DEALINGS IN THE SOFTWARE.
 
24
#endregion
 
25
 
 
26
using System;
 
27
using System.Collections;
 
28
#if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE)
 
29
using System.Collections.Concurrent;
 
30
#endif
 
31
using System.Collections.Generic;
 
32
using System.ComponentModel;
 
33
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
34
using System.Dynamic;
 
35
#endif
 
36
using System.Globalization;
 
37
using System.Reflection;
 
38
using System.Runtime.Serialization;
 
39
#if !(NETFX_CORE || PORTABLE)
 
40
using System.Security.Permissions;
 
41
#endif
 
42
using System.Xml.Serialization;
 
43
using Newtonsoft.Json.Converters;
 
44
using Newtonsoft.Json.Utilities;
 
45
using Newtonsoft.Json.Linq;
 
46
using System.Runtime.CompilerServices;
 
47
#if NETFX_CORE || PORTABLE
 
48
using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider;
 
49
#endif
 
50
#if NET20
 
51
using Newtonsoft.Json.Utilities.LinqBridge;
 
52
#else
 
53
using System.Linq;
 
54
#endif
 
55
 
 
56
namespace Newtonsoft.Json.Serialization
 
57
{
 
58
  internal struct ResolverContractKey : IEquatable<ResolverContractKey>
 
59
  {
 
60
    private readonly Type _resolverType;
 
61
    private readonly Type _contractType;
 
62
 
 
63
    public ResolverContractKey(Type resolverType, Type contractType)
 
64
    {
 
65
      _resolverType = resolverType;
 
66
      _contractType = contractType;
 
67
    }
 
68
 
 
69
    public override int GetHashCode()
 
70
    {
 
71
      return _resolverType.GetHashCode() ^ _contractType.GetHashCode();
 
72
    }
 
73
 
 
74
    public override bool Equals(object obj)
 
75
    {
 
76
      if (!(obj is ResolverContractKey))
 
77
        return false;
 
78
 
 
79
      return Equals((ResolverContractKey)obj);
 
80
    }
 
81
 
 
82
    public bool Equals(ResolverContractKey other)
 
83
    {
 
84
      return (_resolverType == other._resolverType && _contractType == other._contractType);
 
85
    }
 
86
  }
 
87
 
 
88
  /// <summary>
 
89
  /// Used by <see cref="JsonSerializer"/> to resolves a <see cref="JsonContract"/> for a given <see cref="Type"/>.
 
90
  /// </summary>
 
91
  public class DefaultContractResolver : IContractResolver
 
92
  {
 
93
    private static readonly IContractResolver _instance = new DefaultContractResolver(true);
 
94
    internal static IContractResolver Instance
 
95
    {
 
96
        get { return _instance; }
 
97
    }
 
98
    private static readonly IList<JsonConverter> BuiltInConverters = new List<JsonConverter>
 
99
      {
 
100
#if !(SILVERLIGHT || NET20 || NETFX_CORE || PORTABLE)
 
101
        new EntityKeyMemberConverter(),
 
102
#endif
 
103
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
104
        new ExpandoObjectConverter(),
 
105
#endif
 
106
#if (!(SILVERLIGHT || PORTABLE) || WINDOWS_PHONE)
 
107
        new XmlNodeConverter(),
 
108
#endif
 
109
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
110
        new BinaryConverter(),
 
111
        new DataSetConverter(),
 
112
        new DataTableConverter(),
 
113
#endif
 
114
        new KeyValuePairConverter(),
 
115
        new BsonObjectIdConverter()
 
116
      };
 
117
 
 
118
    private static Dictionary<ResolverContractKey, JsonContract> _sharedContractCache;
 
119
    private static readonly object _typeContractCacheLock = new object();
 
120
 
 
121
    private Dictionary<ResolverContractKey, JsonContract> _instanceContractCache;
 
122
    private readonly bool _sharedCache;
 
123
 
 
124
    /// <summary>
 
125
    /// Gets a value indicating whether members are being get and set using dynamic code generation.
 
126
    /// This value is determined by the runtime permissions available.
 
127
    /// </summary>
 
128
    /// <value>
 
129
    ///         <c>true</c> if using dynamic code generation; otherwise, <c>false</c>.
 
130
    /// </value>
 
131
    public bool DynamicCodeGeneration
 
132
    {
 
133
      get { return JsonTypeReflector.DynamicCodeGeneration; }
 
134
    }
 
135
 
 
136
#if !NETFX_CORE
 
137
    /// <summary>
 
138
    /// Gets or sets the default members search flags.
 
139
    /// </summary>
 
140
    /// <value>The default members search flags.</value>
 
141
    public BindingFlags DefaultMembersSearchFlags { get; set; }
 
142
#else
 
143
    private BindingFlags DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public;
 
144
#endif
 
145
 
 
146
    /// <summary>
 
147
    /// Gets or sets a value indicating whether compiler generated members should be serialized.
 
148
    /// </summary>
 
149
    /// <value>
 
150
    ///         <c>true</c> if serialized compiler generated members; otherwise, <c>false</c>.
 
151
    /// </value>
 
152
    public bool SerializeCompilerGeneratedMembers { get; set; }
 
153
 
 
154
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
155
    /// <summary>
 
156
    /// Gets or sets a value indicating whether to ignore the <see cref="ISerializable"/> interface when serializing and deserializing types.
 
157
    /// </summary>
 
158
    /// <value>
 
159
    ///         <c>true</c> if the <see cref="ISerializable"/> interface will be ignored when serializing and deserializing types; otherwise, <c>false</c>.
 
160
    /// </value>
 
161
    public bool IgnoreSerializableInterface { get; set; }
 
162
 
 
163
    /// <summary>
 
164
    /// Gets or sets a value indicating whether to ignore the <see cref="SerializableAttribute"/> attribute when serializing and deserializing types.
 
165
    /// </summary>
 
166
    /// <value>
 
167
    ///         <c>true</c> if the <see cref="SerializableAttribute"/> attribute will be ignored when serializing and deserializing types; otherwise, <c>false</c>.
 
168
    /// </value>
 
169
    public bool IgnoreSerializableAttribute { get; set; }
 
170
#endif
 
171
 
 
172
    /// <summary>
 
173
    /// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
 
174
    /// </summary>
 
175
    public DefaultContractResolver()
 
176
      : this(false)
 
177
    {
 
178
    }
 
179
 
 
180
    /// <summary>
 
181
    /// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
 
182
    /// </summary>
 
183
    /// <param name="shareCache">
 
184
    /// If set to <c>true</c> the <see cref="DefaultContractResolver"/> will use a cached shared with other resolvers of the same type.
 
185
    /// Sharing the cache will significantly performance because expensive reflection will only happen once but could cause unexpected
 
186
    /// behavior if different instances of the resolver are suppose to produce different results. When set to false it is highly
 
187
    /// recommended to reuse <see cref="DefaultContractResolver"/> instances with the <see cref="JsonSerializer"/>.
 
188
    /// </param>
 
189
    public DefaultContractResolver(bool shareCache)
 
190
    {
 
191
#if !NETFX_CORE
 
192
      DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance;
 
193
#endif
 
194
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
195
      IgnoreSerializableAttribute = true;
 
196
#endif
 
197
 
 
198
      _sharedCache = shareCache;
 
199
    }
 
200
 
 
201
    private Dictionary<ResolverContractKey, JsonContract> GetCache()
 
202
    {
 
203
      if (_sharedCache)
 
204
        return _sharedContractCache;
 
205
      else
 
206
        return _instanceContractCache;
 
207
    }
 
208
 
 
209
    private void UpdateCache(Dictionary<ResolverContractKey, JsonContract> cache)
 
210
    {
 
211
      if (_sharedCache)
 
212
        _sharedContractCache = cache;
 
213
      else
 
214
        _instanceContractCache = cache;
 
215
    }
 
216
 
 
217
    /// <summary>
 
218
    /// Resolves the contract for a given type.
 
219
    /// </summary>
 
220
    /// <param name="type">The type to resolve a contract for.</param>
 
221
    /// <returns>The contract for a given type.</returns>
 
222
    public virtual JsonContract ResolveContract(Type type)
 
223
    {
 
224
      if (type == null)
 
225
        throw new ArgumentNullException("type");
 
226
 
 
227
      JsonContract contract;
 
228
      ResolverContractKey key = new ResolverContractKey(GetType(), type);
 
229
      Dictionary<ResolverContractKey, JsonContract> cache = GetCache();
 
230
      if (cache == null || !cache.TryGetValue(key, out contract))
 
231
      {
 
232
        contract = CreateContract(type);
 
233
 
 
234
        // avoid the possibility of modifying the cache dictionary while another thread is accessing it
 
235
        lock (_typeContractCacheLock)
 
236
        {
 
237
          cache = GetCache();
 
238
          Dictionary<ResolverContractKey, JsonContract> updatedCache =
 
239
            (cache != null)
 
240
              ? new Dictionary<ResolverContractKey, JsonContract>(cache)
 
241
              : new Dictionary<ResolverContractKey, JsonContract>();
 
242
          updatedCache[key] = contract;
 
243
 
 
244
          UpdateCache(updatedCache);
 
245
        }
 
246
      }
 
247
 
 
248
      return contract;
 
249
    }
 
250
 
 
251
    /// <summary>
 
252
    /// Gets the serializable members for the type.
 
253
    /// </summary>
 
254
    /// <param name="objectType">The type to get serializable members for.</param>
 
255
    /// <returns>The serializable members for the type.</returns>
 
256
    protected virtual List<MemberInfo> GetSerializableMembers(Type objectType)
 
257
    {
 
258
      bool ignoreSerializableAttribute;
 
259
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
260
      ignoreSerializableAttribute = IgnoreSerializableAttribute;
 
261
#else
 
262
      ignoreSerializableAttribute = true;
 
263
#endif
 
264
 
 
265
      MemberSerialization memberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute);
 
266
 
 
267
      List<MemberInfo> allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
 
268
        .Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
 
269
 
 
270
      List<MemberInfo> serializableMembers = new List<MemberInfo>();
 
271
      
 
272
      if (memberSerialization != MemberSerialization.Fields)
 
273
      {
 
274
#if !PocketPC && !NET20
 
275
        DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
 
276
#endif
 
277
 
 
278
        List<MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
 
279
         .Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
 
280
        
 
281
        foreach (MemberInfo member in allMembers)
 
282
        {
 
283
          // exclude members that are compiler generated if set
 
284
          if (SerializeCompilerGeneratedMembers || !member.IsDefined(typeof (CompilerGeneratedAttribute), true))
 
285
          {
 
286
            if (defaultMembers.Contains(member))
 
287
            {
 
288
              // add all members that are found by default member search
 
289
              serializableMembers.Add(member);
 
290
            }
 
291
            else
 
292
            {
 
293
              // add members that are explicitly marked with JsonProperty/DataMember attribute
 
294
              // or are a field if serializing just fields
 
295
              if (JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member.GetCustomAttributeProvider()) != null)
 
296
                serializableMembers.Add(member);
 
297
#if !PocketPC && !NET20
 
298
              else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(member.GetCustomAttributeProvider()) != null)
 
299
                serializableMembers.Add(member);
 
300
#endif
 
301
              else if (memberSerialization == MemberSerialization.Fields && member.MemberType() == MemberTypes.Field)
 
302
                serializableMembers.Add(member);
 
303
            }
 
304
          }
 
305
        }
 
306
 
 
307
#if !PocketPC && !SILVERLIGHT && !NET20
 
308
        Type match;
 
309
        // don't include EntityKey on entities objects... this is a bit hacky
 
310
        if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out match))
 
311
          serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList();
 
312
#endif
 
313
      }
 
314
      else
 
315
      {
 
316
        // serialize all fields
 
317
        foreach (MemberInfo member in allMembers)
 
318
        {
 
319
          if (member.MemberType() == MemberTypes.Field)
 
320
            serializableMembers.Add(member);
 
321
        }
 
322
      }
 
323
 
 
324
      return serializableMembers;
 
325
    }
 
326
 
 
327
#if !PocketPC && !SILVERLIGHT && !NET20
 
328
    private bool ShouldSerializeEntityMember(MemberInfo memberInfo)
 
329
    {
 
330
      PropertyInfo propertyInfo = memberInfo as PropertyInfo;
 
331
      if (propertyInfo != null)
 
332
      {
 
333
        if (propertyInfo.PropertyType.IsGenericType() && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1")
 
334
          return false;
 
335
      }
 
336
 
 
337
      return true;
 
338
    }
 
339
#endif
 
340
 
 
341
    /// <summary>
 
342
    /// Creates a <see cref="JsonObjectContract"/> for the given type.
 
343
    /// </summary>
 
344
    /// <param name="objectType">Type of the object.</param>
 
345
    /// <returns>A <see cref="JsonObjectContract"/> for the given type.</returns>
 
346
    protected virtual JsonObjectContract CreateObjectContract(Type objectType)
 
347
    {
 
348
      JsonObjectContract contract = new JsonObjectContract(objectType);
 
349
      InitializeContract(contract);
 
350
 
 
351
      bool ignoreSerializableAttribute;
 
352
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
353
      ignoreSerializableAttribute = IgnoreSerializableAttribute;
 
354
#else
 
355
      ignoreSerializableAttribute = true;
 
356
#endif
 
357
 
 
358
      contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType, ignoreSerializableAttribute);
 
359
      contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization));
 
360
 
 
361
      JsonObjectAttribute attribute = JsonTypeReflector.GetJsonObjectAttribute(contract.NonNullableUnderlyingType);
 
362
      if (attribute != null)
 
363
        contract.ItemRequired = attribute._itemRequired;
 
364
 
 
365
      // check if a JsonConstructorAttribute has been defined and use that
 
366
      if (contract.NonNullableUnderlyingType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(c => c.IsDefined(typeof(JsonConstructorAttribute), true)))
 
367
      {
 
368
        ConstructorInfo constructor = GetAttributeConstructor(contract.NonNullableUnderlyingType);
 
369
        if (constructor != null)
 
370
        {
 
371
          contract.OverrideConstructor = constructor;
 
372
          contract.ConstructorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties));
 
373
        }
 
374
      }
 
375
      else if (contract.MemberSerialization == MemberSerialization.Fields)
 
376
      {
 
377
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
378
        // mimic DataContractSerializer behaviour when populating fields by overriding default creator to create an uninitialized object
 
379
        // note that this is only possible when the application is fully trusted so fall back to using the default constructor (if available) in partial trust
 
380
        if (JsonTypeReflector.FullyTrusted)
 
381
          contract.DefaultCreator = contract.GetUninitializedObject;
 
382
#endif
 
383
      }
 
384
      else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic)
 
385
      {
 
386
        ConstructorInfo constructor = GetParametrizedConstructor(contract.NonNullableUnderlyingType);
 
387
        if (constructor != null)
 
388
        {
 
389
          contract.ParametrizedConstructor = constructor;
 
390
          contract.ConstructorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties));
 
391
        }
 
392
      }
 
393
      return contract;
 
394
    }
 
395
 
 
396
    private ConstructorInfo GetAttributeConstructor(Type objectType)
 
397
    {
 
398
      IList<ConstructorInfo> markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList();
 
399
 
 
400
      if (markedConstructors.Count > 1)
 
401
        throw new JsonException("Multiple constructors with the JsonConstructorAttribute.");
 
402
      else if (markedConstructors.Count == 1)
 
403
        return markedConstructors[0];
 
404
 
 
405
      return null;
 
406
    }
 
407
 
 
408
    private ConstructorInfo GetParametrizedConstructor(Type objectType)
 
409
    {
 
410
      IList<ConstructorInfo> constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).ToList();
 
411
 
 
412
      if (constructors.Count == 1)
 
413
        return constructors[0];
 
414
      else
 
415
        return null;
 
416
    }
 
417
 
 
418
    /// <summary>
 
419
    /// Creates the constructor parameters.
 
420
    /// </summary>
 
421
    /// <param name="constructor">The constructor to create properties for.</param>
 
422
    /// <param name="memberProperties">The type's member properties.</param>
 
423
    /// <returns>Properties for the given <see cref="ConstructorInfo"/>.</returns>
 
424
    protected virtual IList<JsonProperty> CreateConstructorParameters(ConstructorInfo constructor, JsonPropertyCollection memberProperties)
 
425
    {
 
426
      var constructorParameters = constructor.GetParameters();
 
427
 
 
428
      JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType);
 
429
 
 
430
      foreach (ParameterInfo parameterInfo in constructorParameters)
 
431
      {
 
432
        JsonProperty matchingMemberProperty = memberProperties.GetClosestMatchProperty(parameterInfo.Name);
 
433
        // type must match as well as name
 
434
        if (matchingMemberProperty != null && matchingMemberProperty.PropertyType != parameterInfo.ParameterType)
 
435
          matchingMemberProperty = null;
 
436
 
 
437
        JsonProperty property = CreatePropertyFromConstructorParameter(matchingMemberProperty, parameterInfo);
 
438
 
 
439
        if (property != null)
 
440
        {
 
441
          parameterCollection.AddProperty(property);
 
442
        }
 
443
      }
 
444
 
 
445
      return parameterCollection;
 
446
    }
 
447
 
 
448
    /// <summary>
 
449
    /// Creates a <see cref="JsonProperty"/> for the given <see cref="ParameterInfo"/>.
 
450
    /// </summary>
 
451
    /// <param name="matchingMemberProperty">The matching member property.</param>
 
452
    /// <param name="parameterInfo">The constructor parameter.</param>
 
453
    /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="ParameterInfo"/>.</returns>
 
454
    protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo)
 
455
    {
 
456
      JsonProperty property = new JsonProperty();
 
457
      property.PropertyType = parameterInfo.ParameterType;
 
458
 
 
459
      bool allowNonPublicAccess;
 
460
      SetPropertySettingsFromAttributes(property, parameterInfo.GetCustomAttributeProvider(), parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess);
 
461
 
 
462
      property.Readable = false;
 
463
      property.Writable = true;
 
464
 
 
465
      // "inherit" values from matching member property if unset on parameter
 
466
      if (matchingMemberProperty != null)
 
467
      {
 
468
        property.PropertyName = (property.PropertyName != parameterInfo.Name) ? property.PropertyName : matchingMemberProperty.PropertyName;
 
469
        property.Converter = property.Converter ?? matchingMemberProperty.Converter;
 
470
        property.MemberConverter = property.MemberConverter ?? matchingMemberProperty.MemberConverter;
 
471
        property.DefaultValue = property.DefaultValue ?? matchingMemberProperty.DefaultValue;
 
472
        property._required = property._required ?? matchingMemberProperty._required;
 
473
        property.IsReference = property.IsReference ?? matchingMemberProperty.IsReference;
 
474
        property.NullValueHandling = property.NullValueHandling ?? matchingMemberProperty.NullValueHandling;
 
475
        property.DefaultValueHandling = property.DefaultValueHandling ?? matchingMemberProperty.DefaultValueHandling;
 
476
        property.ReferenceLoopHandling = property.ReferenceLoopHandling ?? matchingMemberProperty.ReferenceLoopHandling;
 
477
        property.ObjectCreationHandling = property.ObjectCreationHandling ?? matchingMemberProperty.ObjectCreationHandling;
 
478
        property.TypeNameHandling = property.TypeNameHandling ?? matchingMemberProperty.TypeNameHandling;
 
479
      }
 
480
 
 
481
      return property;
 
482
    }
 
483
 
 
484
    /// <summary>
 
485
    /// Resolves the default <see cref="JsonConverter" /> for the contract.
 
486
    /// </summary>
 
487
    /// <param name="objectType">Type of the object.</param>
 
488
    /// <returns>The contract's default <see cref="JsonConverter" />.</returns>
 
489
    protected virtual JsonConverter ResolveContractConverter(Type objectType)
 
490
    {
 
491
      return JsonTypeReflector.GetJsonConverter(objectType.GetCustomAttributeProvider(), objectType);
 
492
    }
 
493
 
 
494
    private Func<object> GetDefaultCreator(Type createdType)
 
495
    {
 
496
      return JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
 
497
    }
 
498
 
 
499
#if !PocketPC && !NET20
 
500
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Runtime.Serialization.DataContractAttribute.#get_IsReference()")]
 
501
#endif
 
502
    private void InitializeContract(JsonContract contract)
 
503
    {
 
504
      JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(contract.NonNullableUnderlyingType);
 
505
      if (containerAttribute != null)
 
506
      {
 
507
        contract.IsReference = containerAttribute._isReference;
 
508
      }
 
509
#if !PocketPC && !NET20
 
510
      else
 
511
      {
 
512
        DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType);
 
513
        // doesn't have a null value
 
514
        if (dataContractAttribute != null && dataContractAttribute.IsReference)
 
515
          contract.IsReference = true;
 
516
      }
 
517
#endif
 
518
 
 
519
      contract.Converter = ResolveContractConverter(contract.NonNullableUnderlyingType);
 
520
 
 
521
      // then see whether object is compadible with any of the built in converters
 
522
      contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.NonNullableUnderlyingType);
 
523
 
 
524
      if (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true)
 
525
        || contract.CreatedType.IsValueType())
 
526
      {
 
527
        contract.DefaultCreator = GetDefaultCreator(contract.CreatedType);
 
528
 
 
529
        contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType() &&
 
530
                                            ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null);
 
531
      }
 
532
 
 
533
      ResolveCallbackMethods(contract, contract.NonNullableUnderlyingType);
 
534
    }
 
535
 
 
536
    private void ResolveCallbackMethods(JsonContract contract, Type t)
 
537
    {
 
538
      if (t.BaseType() != null)
 
539
        ResolveCallbackMethods(contract, t.BaseType());
 
540
 
 
541
      MethodInfo onSerializing;
 
542
      MethodInfo onSerialized;
 
543
      MethodInfo onDeserializing;
 
544
      MethodInfo onDeserialized;
 
545
      MethodInfo onError;
 
546
 
 
547
      GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError);
 
548
 
 
549
      if (onSerializing != null)
 
550
      {
 
551
#if NETFX_CORE
 
552
        if (!t.IsGenericType() || (t.GetGenericTypeDefinition() != typeof(ConcurrentDictionary<,>)))
 
553
          contract.OnSerializing = onSerializing;
 
554
#else
 
555
        contract.OnSerializing = onSerializing;
 
556
#endif
 
557
      }
 
558
 
 
559
      if (onSerialized != null)
 
560
        contract.OnSerialized = onSerialized;
 
561
 
 
562
      if (onDeserializing != null)
 
563
        contract.OnDeserializing = onDeserializing;
 
564
 
 
565
      if (onDeserialized != null)
 
566
      {
 
567
        // ConcurrentDictionary throws an error here so don't use its OnDeserialized - http://json.codeplex.com/discussions/257093
 
568
#if !(NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE)
 
569
        if (!t.IsGenericType() || (t.GetGenericTypeDefinition() != typeof(ConcurrentDictionary<,>)))
 
570
          contract.OnDeserialized = onDeserialized;
 
571
#else
 
572
        contract.OnDeserialized = onDeserialized;
 
573
#endif
 
574
      }
 
575
 
 
576
      if (onError != null)
 
577
        contract.OnError = onError;
 
578
    }
 
579
 
 
580
    private void GetCallbackMethodsForType(Type type, out MethodInfo onSerializing, out MethodInfo onSerialized, out MethodInfo onDeserializing, out MethodInfo onDeserialized, out MethodInfo onError)
 
581
    {
 
582
      onSerializing = null;
 
583
      onSerialized = null;
 
584
      onDeserializing = null;
 
585
      onDeserialized = null;
 
586
      onError = null;
 
587
 
 
588
      foreach (MethodInfo method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
 
589
      {
 
590
        // compact framework errors when getting parameters for a generic method
 
591
        // lame, but generic methods should not be callbacks anyway
 
592
        if (method.ContainsGenericParameters)
 
593
          continue;
 
594
 
 
595
        Type prevAttributeType = null;
 
596
        ParameterInfo[] parameters = method.GetParameters();
 
597
 
 
598
        if (IsValidCallback(method, parameters, typeof(OnSerializingAttribute), onSerializing, ref prevAttributeType))
 
599
        {
 
600
          onSerializing = method;
 
601
        }
 
602
        if (IsValidCallback(method, parameters, typeof(OnSerializedAttribute), onSerialized, ref prevAttributeType))
 
603
        {
 
604
          onSerialized = method;
 
605
        }
 
606
        if (IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), onDeserializing, ref prevAttributeType))
 
607
        {
 
608
          onDeserializing = method;
 
609
        }
 
610
        if (IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), onDeserialized, ref prevAttributeType))
 
611
        {
 
612
          onDeserialized = method;
 
613
        }
 
614
        if (IsValidCallback(method, parameters, typeof(OnErrorAttribute), onError, ref prevAttributeType))
 
615
        {
 
616
          onError = method;
 
617
        }
 
618
      }
 
619
    }
 
620
 
 
621
    /// <summary>
 
622
    /// Creates a <see cref="JsonDictionaryContract"/> for the given type.
 
623
    /// </summary>
 
624
    /// <param name="objectType">Type of the object.</param>
 
625
    /// <returns>A <see cref="JsonDictionaryContract"/> for the given type.</returns>
 
626
    protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
 
627
    {
 
628
      JsonDictionaryContract contract = new JsonDictionaryContract(objectType);
 
629
      InitializeContract(contract);
 
630
 
 
631
      contract.PropertyNameResolver = ResolvePropertyName;
 
632
 
 
633
      return contract;
 
634
    }
 
635
 
 
636
    /// <summary>
 
637
    /// Creates a <see cref="JsonArrayContract"/> for the given type.
 
638
    /// </summary>
 
639
    /// <param name="objectType">Type of the object.</param>
 
640
    /// <returns>A <see cref="JsonArrayContract"/> for the given type.</returns>
 
641
    protected virtual JsonArrayContract CreateArrayContract(Type objectType)
 
642
    {
 
643
      JsonArrayContract contract = new JsonArrayContract(objectType);
 
644
      InitializeContract(contract);
 
645
 
 
646
      return contract;
 
647
    }
 
648
 
 
649
    /// <summary>
 
650
    /// Creates a <see cref="JsonPrimitiveContract"/> for the given type.
 
651
    /// </summary>
 
652
    /// <param name="objectType">Type of the object.</param>
 
653
    /// <returns>A <see cref="JsonPrimitiveContract"/> for the given type.</returns>
 
654
    protected virtual JsonPrimitiveContract CreatePrimitiveContract(Type objectType)
 
655
    {
 
656
      JsonPrimitiveContract contract = new JsonPrimitiveContract(objectType);
 
657
      InitializeContract(contract);
 
658
 
 
659
      return contract;
 
660
    }
 
661
 
 
662
    /// <summary>
 
663
    /// Creates a <see cref="JsonLinqContract"/> for the given type.
 
664
    /// </summary>
 
665
    /// <param name="objectType">Type of the object.</param>
 
666
    /// <returns>A <see cref="JsonLinqContract"/> for the given type.</returns>
 
667
    protected virtual JsonLinqContract CreateLinqContract(Type objectType)
 
668
    {
 
669
      JsonLinqContract contract = new JsonLinqContract(objectType);
 
670
      InitializeContract(contract);
 
671
 
 
672
      return contract;
 
673
    }
 
674
 
 
675
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
676
    /// <summary>
 
677
    /// Creates a <see cref="JsonISerializableContract"/> for the given type.
 
678
    /// </summary>
 
679
    /// <param name="objectType">Type of the object.</param>
 
680
    /// <returns>A <see cref="JsonISerializableContract"/> for the given type.</returns>
 
681
    protected virtual JsonISerializableContract CreateISerializableContract(Type objectType)
 
682
    {
 
683
      JsonISerializableContract contract = new JsonISerializableContract(objectType);
 
684
      InitializeContract(contract);
 
685
 
 
686
      ConstructorInfo constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);
 
687
      if (constructorInfo != null)
 
688
      {
 
689
        MethodCall<object, object> methodCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(constructorInfo);
 
690
 
 
691
        contract.ISerializableCreator = (args => methodCall(null, args));
 
692
      }
 
693
 
 
694
      return contract;
 
695
    }
 
696
#endif
 
697
 
 
698
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
699
    /// <summary>
 
700
    /// Creates a <see cref="JsonDynamicContract"/> for the given type.
 
701
    /// </summary>
 
702
    /// <param name="objectType">Type of the object.</param>
 
703
    /// <returns>A <see cref="JsonDynamicContract"/> for the given type.</returns>
 
704
    protected virtual JsonDynamicContract CreateDynamicContract(Type objectType)
 
705
    {
 
706
      JsonDynamicContract contract = new JsonDynamicContract(objectType);
 
707
      InitializeContract(contract);
 
708
 
 
709
      contract.PropertyNameResolver = ResolvePropertyName;
 
710
      contract.Properties.AddRange(CreateProperties(objectType, MemberSerialization.OptOut));
 
711
 
 
712
      return contract;
 
713
    }
 
714
#endif
 
715
 
 
716
    /// <summary>
 
717
    /// Creates a <see cref="JsonStringContract"/> for the given type.
 
718
    /// </summary>
 
719
    /// <param name="objectType">Type of the object.</param>
 
720
    /// <returns>A <see cref="JsonStringContract"/> for the given type.</returns>
 
721
    protected virtual JsonStringContract CreateStringContract(Type objectType)
 
722
    {
 
723
      JsonStringContract contract = new JsonStringContract(objectType);
 
724
      InitializeContract(contract);
 
725
 
 
726
      return contract;
 
727
    }
 
728
 
 
729
    /// <summary>
 
730
    /// Determines which contract type is created for the given type.
 
731
    /// </summary>
 
732
    /// <param name="objectType">Type of the object.</param>
 
733
    /// <returns>A <see cref="JsonContract"/> for the given type.</returns>
 
734
    protected virtual JsonContract CreateContract(Type objectType)
 
735
    {
 
736
      Type t = ReflectionUtils.EnsureNotNullableType(objectType);
 
737
 
 
738
      if (JsonConvert.IsJsonPrimitiveType(t))
 
739
        return CreatePrimitiveContract(objectType);
 
740
 
 
741
      if (JsonTypeReflector.GetJsonObjectAttribute(t) != null)
 
742
        return CreateObjectContract(objectType);
 
743
 
 
744
      if (JsonTypeReflector.GetJsonArrayAttribute(t) != null)
 
745
        return CreateArrayContract(objectType);
 
746
 
 
747
      if (JsonTypeReflector.GetJsonDictionaryAttribute(t) != null)
 
748
        return CreateDictionaryContract(objectType);
 
749
 
 
750
      if (t == typeof(JToken) || t.IsSubclassOf(typeof(JToken)))
 
751
        return CreateLinqContract(objectType);
 
752
 
 
753
      if (CollectionUtils.IsDictionaryType(t))
 
754
        return CreateDictionaryContract(objectType);
 
755
 
 
756
      if (typeof(IEnumerable).IsAssignableFrom(t))
 
757
        return CreateArrayContract(objectType);
 
758
 
 
759
      if (CanConvertToString(t))
 
760
        return CreateStringContract(objectType);
 
761
 
 
762
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
763
      if (!IgnoreSerializableInterface && typeof(ISerializable).IsAssignableFrom(t))
 
764
        return CreateISerializableContract(objectType);
 
765
#endif
 
766
 
 
767
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
768
      if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(t))
 
769
        return CreateDynamicContract(objectType);
 
770
#endif
 
771
 
 
772
      return CreateObjectContract(objectType);
 
773
    }
 
774
 
 
775
    internal static bool CanConvertToString(Type type)
 
776
    {
 
777
#if !(NETFX_CORE || PORTABLE)
 
778
      TypeConverter converter = ConvertUtils.GetConverter(type);
 
779
 
 
780
      // use the objectType's TypeConverter if it has one and can convert to a string
 
781
      if (converter != null
 
782
#if !SILVERLIGHT
 
783
 && !(converter is ComponentConverter)
 
784
 && !(converter is ReferenceConverter)
 
785
#endif
 
786
 && converter.GetType() != typeof(TypeConverter))
 
787
      {
 
788
        if (converter.CanConvertTo(typeof(string)))
 
789
          return true;
 
790
      }
 
791
#endif
 
792
 
 
793
      if (type == typeof(Type) || type.IsSubclassOf(typeof(Type)))
 
794
        return true;
 
795
 
 
796
#if SILVERLIGHT || PocketPC
 
797
      if (type == typeof(Guid) || type == typeof(Uri) || type == typeof(TimeSpan))
 
798
        return true;
 
799
#endif
 
800
 
 
801
      return false;
 
802
    }
 
803
 
 
804
    private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
 
805
    {
 
806
      if (!method.IsDefined(attributeType, false))
 
807
        return false;
 
808
 
 
809
      if (currentCallback != null)
 
810
        throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType));
 
811
 
 
812
      if (prevAttributeType != null)
 
813
        throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method));
 
814
 
 
815
      if (method.IsVirtual)
 
816
        throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType));
 
817
 
 
818
      if (method.ReturnType != typeof(void))
 
819
        throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method));
 
820
 
 
821
      if (attributeType == typeof(OnErrorAttribute))
 
822
      {
 
823
        if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
 
824
          throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext)));
 
825
      }
 
826
      else
 
827
      {
 
828
        if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
 
829
          throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext)));
 
830
      }
 
831
 
 
832
      prevAttributeType = attributeType;
 
833
 
 
834
      return true;
 
835
    }
 
836
 
 
837
    internal static string GetClrTypeFullName(Type type)
 
838
    {
 
839
      if (type.IsGenericTypeDefinition() || !type.ContainsGenericParameters())
 
840
        return type.FullName;
 
841
 
 
842
      return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { type.Namespace, type.Name });
 
843
    }
 
844
 
 
845
    /// <summary>
 
846
    /// Creates properties for the given <see cref="JsonContract"/>.
 
847
    /// </summary>
 
848
    /// <param name="type">The type to create properties for.</param>
 
849
    /// /// <param name="memberSerialization">The member serialization mode for the type.</param>
 
850
    /// <returns>Properties for the given <see cref="JsonContract"/>.</returns>
 
851
    protected virtual IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
 
852
    {
 
853
      List<MemberInfo> members = GetSerializableMembers(type);
 
854
      if (members == null)
 
855
        throw new JsonSerializationException("Null collection of seralizable members returned.");
 
856
 
 
857
      JsonPropertyCollection properties = new JsonPropertyCollection(type);
 
858
 
 
859
      foreach (MemberInfo member in members)
 
860
      {
 
861
        JsonProperty property = CreateProperty(member, memberSerialization);
 
862
 
 
863
        if (property != null)
 
864
          properties.AddProperty(property);
 
865
      }
 
866
 
 
867
      IList<JsonProperty> orderedProperties = properties.OrderBy(p => p.Order ?? -1).ToList();
 
868
      return orderedProperties;
 
869
    }
 
870
 
 
871
    /// <summary>
 
872
    /// Creates the <see cref="IValueProvider"/> used by the serializer to get and set values from a member.
 
873
    /// </summary>
 
874
    /// <param name="member">The member.</param>
 
875
    /// <returns>The <see cref="IValueProvider"/> used by the serializer to get and set values from a member.</returns>
 
876
    protected virtual IValueProvider CreateMemberValueProvider(MemberInfo member)
 
877
    {
 
878
      // warning - this method use to cause errors with Intellitrace. Retest in VS Ultimate after changes
 
879
      IValueProvider valueProvider;
 
880
 
 
881
#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
 
882
      if (DynamicCodeGeneration)
 
883
        valueProvider = new DynamicValueProvider(member);
 
884
      else
 
885
        valueProvider = new ReflectionValueProvider(member);
 
886
#else
 
887
      valueProvider = new ReflectionValueProvider(member);
 
888
#endif
 
889
 
 
890
      return valueProvider;
 
891
    }
 
892
 
 
893
    /// <summary>
 
894
    /// Creates a <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.
 
895
    /// </summary>
 
896
    /// <param name="memberSerialization">The member's parent <see cref="MemberSerialization"/>.</param>
 
897
    /// <param name="member">The member to create a <see cref="JsonProperty"/> for.</param>
 
898
    /// <returns>A created <see cref="JsonProperty"/> for the given <see cref="MemberInfo"/>.</returns>
 
899
    protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
 
900
    {
 
901
      JsonProperty property = new JsonProperty();
 
902
      property.PropertyType = ReflectionUtils.GetMemberUnderlyingType(member);
 
903
      property.DeclaringType = member.DeclaringType;
 
904
      property.ValueProvider = CreateMemberValueProvider(member);
 
905
 
 
906
      bool allowNonPublicAccess;
 
907
      SetPropertySettingsFromAttributes(property, member.GetCustomAttributeProvider(), member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess);
 
908
 
 
909
      if (memberSerialization != MemberSerialization.Fields)
 
910
      {
 
911
        property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess);
 
912
        property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess, property.HasMemberAttribute);
 
913
      }
 
914
      else
 
915
      {
 
916
        // write to readonly fields
 
917
        property.Readable = true;
 
918
        property.Writable = true;
 
919
      }
 
920
      property.ShouldSerialize = CreateShouldSerializeTest(member);
 
921
 
 
922
      SetIsSpecifiedActions(property, member, allowNonPublicAccess);
 
923
 
 
924
      return property;
 
925
    }
 
926
 
 
927
    private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess)
 
928
    {
 
929
#if !PocketPC && !NET20
 
930
      DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType);
 
931
 
 
932
      MemberInfo memberInfo = null;
 
933
#if !(NETFX_CORE || PORTABLE)
 
934
      memberInfo = attributeProvider as MemberInfo;
 
935
#else
 
936
      memberInfo = attributeProvider.UnderlyingObject as MemberInfo;
 
937
#endif
 
938
 
 
939
      DataMemberAttribute dataMemberAttribute;
 
940
      if (dataContractAttribute != null && memberInfo != null)
 
941
        dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo) memberInfo);
 
942
      else
 
943
        dataMemberAttribute = null;
 
944
#endif
 
945
 
 
946
      JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(attributeProvider);
 
947
      if (propertyAttribute != null)
 
948
        property.HasMemberAttribute = true;
 
949
 
 
950
      string mappedName;
 
951
      if (propertyAttribute != null && propertyAttribute.PropertyName != null)
 
952
        mappedName = propertyAttribute.PropertyName;
 
953
#if !PocketPC && !NET20
 
954
      else if (dataMemberAttribute != null && dataMemberAttribute.Name != null)
 
955
        mappedName = dataMemberAttribute.Name;
 
956
#endif
 
957
      else
 
958
        mappedName = name;
 
959
 
 
960
      property.PropertyName = ResolvePropertyName(mappedName);
 
961
      property.UnderlyingName = name;
 
962
 
 
963
      bool hasMemberAttribute = false;
 
964
      if (propertyAttribute != null)
 
965
      {
 
966
        property._required = propertyAttribute._required;
 
967
        property.Order = propertyAttribute._order;
 
968
        hasMemberAttribute = true;
 
969
      }
 
970
#if !PocketPC && !NET20
 
971
      else if (dataMemberAttribute != null)
 
972
      {
 
973
        property._required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default;
 
974
        property.Order = (dataMemberAttribute.Order != -1) ? (int?) dataMemberAttribute.Order : null;
 
975
        hasMemberAttribute = true;
 
976
      }
 
977
#endif
 
978
 
 
979
      bool hasJsonIgnoreAttribute =
 
980
        JsonTypeReflector.GetAttribute<JsonIgnoreAttribute>(attributeProvider) != null
 
981
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
982
        || JsonTypeReflector.GetAttribute<NonSerializedAttribute>(attributeProvider) != null
 
983
#endif
 
984
        ;
 
985
 
 
986
      if (memberSerialization != MemberSerialization.OptIn)
 
987
      {
 
988
       bool hasIgnoreDataMemberAttribute = false;
 
989
        
 
990
#if !(NET20 || NET35)
 
991
        hasIgnoreDataMemberAttribute = (JsonTypeReflector.GetAttribute<IgnoreDataMemberAttribute>(attributeProvider) != null);
 
992
#endif
 
993
 
 
994
        // ignored if it has JsonIgnore or NonSerialized or IgnoreDataMember attributes
 
995
        property.Ignored = (hasJsonIgnoreAttribute || hasIgnoreDataMemberAttribute);
 
996
      }
 
997
      else
 
998
      {
 
999
        // ignored if it has JsonIgnore/NonSerialized or does not have DataMember or JsonProperty attributes
 
1000
        property.Ignored = (hasJsonIgnoreAttribute || !hasMemberAttribute);
 
1001
      }
 
1002
 
 
1003
      // resolve converter for property
 
1004
      // the class type might have a converter but the property converter takes presidence
 
1005
      property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
 
1006
      property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType);
 
1007
 
 
1008
      DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute<DefaultValueAttribute>(attributeProvider);
 
1009
      property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null;
 
1010
 
 
1011
      property.NullValueHandling = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null;
 
1012
      property.DefaultValueHandling = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null;
 
1013
      property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null;
 
1014
      property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null;
 
1015
      property.TypeNameHandling = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null;
 
1016
      property.IsReference = (propertyAttribute != null) ? propertyAttribute._isReference : null;
 
1017
 
 
1018
      property.ItemIsReference = (propertyAttribute != null) ? propertyAttribute._itemIsReference : null;
 
1019
      property.ItemConverter =
 
1020
        (propertyAttribute != null && propertyAttribute.ItemConverterType != null)
 
1021
          ? JsonConverterAttribute.CreateJsonConverterInstance(propertyAttribute.ItemConverterType)
 
1022
          : null;
 
1023
      property.ItemReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._itemReferenceLoopHandling : null;
 
1024
      property.ItemTypeNameHandling = (propertyAttribute != null) ? propertyAttribute._itemTypeNameHandling : null;
 
1025
 
 
1026
      allowNonPublicAccess = false;
 
1027
      if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic)
 
1028
        allowNonPublicAccess = true;
 
1029
      if (propertyAttribute != null)
 
1030
        allowNonPublicAccess = true;
 
1031
      if (memberSerialization == MemberSerialization.Fields)
 
1032
        allowNonPublicAccess = true;
 
1033
 
 
1034
#if !PocketPC && !NET20
 
1035
      if (dataMemberAttribute != null)
 
1036
      {
 
1037
        allowNonPublicAccess = true;
 
1038
        property.HasMemberAttribute = true;
 
1039
      }
 
1040
#endif
 
1041
    }
 
1042
 
 
1043
    private Predicate<object> CreateShouldSerializeTest(MemberInfo member)
 
1044
    {
 
1045
      MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes);
 
1046
 
 
1047
      if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool))
 
1048
        return null;
 
1049
 
 
1050
      MethodCall<object, object> shouldSerializeCall =
 
1051
        JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(shouldSerializeMethod);
 
1052
 
 
1053
      return o => (bool)shouldSerializeCall(o);
 
1054
    }
 
1055
 
 
1056
    private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess)
 
1057
    {
 
1058
      MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix);
 
1059
      if (specifiedMember == null)
 
1060
        specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix);
 
1061
 
 
1062
      if (specifiedMember == null || ReflectionUtils.GetMemberUnderlyingType(specifiedMember) != typeof(bool))
 
1063
      {
 
1064
        return;
 
1065
      }
 
1066
 
 
1067
      Func<object, object> specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(specifiedMember);
 
1068
 
 
1069
      property.GetIsSpecified = o => (bool)specifiedPropertyGet(o);
 
1070
 
 
1071
      if (ReflectionUtils.CanSetMemberValue(specifiedMember, allowNonPublicAccess, false))
 
1072
        property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(specifiedMember);
 
1073
    }
 
1074
 
 
1075
    /// <summary>
 
1076
    /// Resolves the name of the property.
 
1077
    /// </summary>
 
1078
    /// <param name="propertyName">Name of the property.</param>
 
1079
    /// <returns>Name of the property.</returns>
 
1080
    protected internal virtual string ResolvePropertyName(string propertyName)
 
1081
    {
 
1082
      return propertyName;
 
1083
    }
 
1084
 
 
1085
    /// <summary>
 
1086
    /// Gets the resolved name of the property.
 
1087
    /// </summary>
 
1088
    /// <param name="propertyName">Name of the property.</param>
 
1089
    /// <returns>Name of the property.</returns>
 
1090
    public string GetResolvedPropertyName(string propertyName)
 
1091
    {
 
1092
      // this is a new method rather than changing the visibility of ResolvePropertyName to avoid
 
1093
      // a breaking change for anyone who has overidden the method
 
1094
      return ResolvePropertyName(propertyName);
 
1095
    }
 
1096
  }
715
1097
}
 
 
b'\\ No newline at end of file'