All files
[pithos-ms-client] / trunk / Libraries / Json40r2 / Source / Src / Newtonsoft.Json / Serialization / JsonTypeReflector.cs
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.ComponentModel;
28 using System.Globalization;
29 using System.Linq;
30 using System.Reflection;
31 using System.Runtime.Serialization;
32 using System.Security.Permissions;
33 using Newtonsoft.Json.Utilities;
34
35 namespace Newtonsoft.Json.Serialization
36 {
37 #if !SILVERLIGHT && !PocketPC && !NET20
38   internal interface IMetadataTypeAttribute
39   {
40     Type MetadataClassType { get; }
41   }
42 #endif
43
44   internal static class JsonTypeReflector
45   {
46     public const string IdPropertyName = "$id";
47     public const string RefPropertyName = "$ref";
48     public const string TypePropertyName = "$type";
49     public const string ArrayValuesPropertyName = "$values";
50
51     public const string ShouldSerializePrefix = "ShouldSerialize";
52     public const string SpecifiedPostfix = "Specified";
53
54     private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute);
55 #if !SILVERLIGHT && !PocketPC && !NET20
56     private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
57
58     private const string MetadataTypeAttributeTypeName =
59       "System.ComponentModel.DataAnnotations.MetadataTypeAttribute, System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
60     private static Type _cachedMetadataTypeAttributeType;
61 #endif
62 #if SILVERLIGHT
63     private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> TypeConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetTypeConverterTypeFromAttribute);
64
65     private static Type GetTypeConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
66     {
67       TypeConverterAttribute converterAttribute = GetAttribute<TypeConverterAttribute>(attributeProvider);
68       if (converterAttribute == null)
69         return null;
70
71       return Type.GetType(converterAttribute.ConverterTypeName);
72     }
73
74     private static Type GetTypeConverterType(ICustomAttributeProvider attributeProvider)
75     {
76       return TypeConverterTypeCache.Get(attributeProvider);
77     }
78 #endif
79
80     public static JsonContainerAttribute GetJsonContainerAttribute(Type type)
81     {
82       return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type);
83     }
84
85     public static JsonObjectAttribute GetJsonObjectAttribute(Type type)
86     {
87       return GetJsonContainerAttribute(type) as JsonObjectAttribute;
88     }
89
90     public static JsonArrayAttribute GetJsonArrayAttribute(Type type)
91     {
92       return GetJsonContainerAttribute(type) as JsonArrayAttribute;
93     }
94
95 #if !PocketPC && !NET20
96     public static DataContractAttribute GetDataContractAttribute(Type type)
97     {
98       return CachedAttributeGetter<DataContractAttribute>.GetAttribute(type);
99     }
100 #endif
101
102     public static MemberSerialization GetObjectMemberSerialization(Type objectType)
103     {
104       JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);
105
106       if (objectAttribute == null)
107       {
108 #if !PocketPC && !NET20
109         DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
110
111         if (dataContractAttribute != null)
112           return MemberSerialization.OptIn;
113 #endif
114
115         return MemberSerialization.OptOut;
116       }
117
118       return objectAttribute.MemberSerialization;
119     }
120
121     private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider)
122     {
123       return JsonConverterTypeCache.Get(attributeProvider);
124     }
125
126     private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
127     {
128       JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider);
129       return (converterAttribute != null)
130         ? converterAttribute.ConverterType
131         : null;
132     }
133
134     public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
135     {
136       Type converterType = GetJsonConverterType(attributeProvider);
137
138       if (converterType != null)
139       {
140         JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);
141
142         if (!memberConverter.CanConvert(targetConvertedType))
143           throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name));
144
145         return memberConverter;
146       }
147
148       return null;
149     }
150
151 #if !PocketPC
152     public static TypeConverter GetTypeConverter(Type type)
153     {
154 #if !SILVERLIGHT
155       return TypeDescriptor.GetConverter(type);
156 #else
157       Type converterType = GetTypeConverterType(type);
158
159       if (converterType != null)
160         return (TypeConverter)ReflectionUtils.CreateInstance(converterType);
161
162       return null;
163 #endif
164     }
165 #endif
166
167 #if !SILVERLIGHT && !PocketPC && !NET20
168     private static Type GetAssociatedMetadataType(Type type)
169     {
170       return AssociatedMetadataTypesCache.Get(type);
171     }
172
173     private static Type GetAssociateMetadataTypeFromAttribute(Type type)
174     {
175       Type metadataTypeAttributeType = GetMetadataTypeAttributeType();
176       if (metadataTypeAttributeType == null)
177         return null;
178
179       object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault();
180       if (attribute == null)
181         return null;
182
183       IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration)
184                                                        ? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute)
185                                                        : new LateBoundMetadataTypeAttribute(attribute);
186
187       return metadataTypeAttribute.MetadataClassType;
188     }
189
190     private static Type GetMetadataTypeAttributeType()
191     {
192       // always attempt to get the metadata type attribute type
193       // the assembly may have been loaded since last time
194       if (_cachedMetadataTypeAttributeType == null)
195       {
196         Type metadataTypeAttributeType = Type.GetType(MetadataTypeAttributeTypeName);
197
198         if (metadataTypeAttributeType != null)
199           _cachedMetadataTypeAttributeType = metadataTypeAttributeType;
200         else
201           return null;
202       }
203       
204       return _cachedMetadataTypeAttributeType;
205     }
206
207     private static T GetAttribute<T>(Type type) where T : Attribute
208     {
209       Type metadataType = GetAssociatedMetadataType(type);
210       if (metadataType != null)
211       {
212         T attribute = ReflectionUtils.GetAttribute<T>(metadataType, true);
213         if (attribute != null)
214           return attribute;
215       }
216
217       return ReflectionUtils.GetAttribute<T>(type, true);
218     }
219
220     private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
221     {
222       Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
223       if (metadataType != null)
224       {
225         MemberInfo metadataTypeMemberInfo = metadataType.GetMember(memberInfo.Name,
226           memberInfo.MemberType,
227           BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).SingleOrDefault();
228
229         if (metadataTypeMemberInfo != null)
230         {
231           T attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true);
232           if (attribute != null)
233             return attribute;
234         }
235       }
236
237       return ReflectionUtils.GetAttribute<T>(memberInfo, true);
238     }
239
240     public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
241     {
242       Type type = attributeProvider as Type;
243       if (type != null)
244         return GetAttribute<T>(type);
245
246       MemberInfo memberInfo = attributeProvider as MemberInfo;
247       if (memberInfo != null)
248         return GetAttribute<T>(memberInfo);
249
250       return ReflectionUtils.GetAttribute<T>(attributeProvider, true);
251     }
252 #else
253     public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
254     {
255       return ReflectionUtils.GetAttribute<T>(attributeProvider, true);
256     }
257 #endif
258
259     private static bool? _dynamicCodeGeneration;
260
261     public static bool DynamicCodeGeneration
262     {
263       get
264       {
265         if (_dynamicCodeGeneration == null)
266         {
267 #if !PocketPC && !SILVERLIGHT
268           try
269           {
270             new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
271             new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand();
272             new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
273             _dynamicCodeGeneration = true;
274           }
275           catch (Exception)
276           {
277             _dynamicCodeGeneration = false;
278           }
279 #else
280           _dynamicCodeGeneration = false;
281 #endif
282         }
283
284         return _dynamicCodeGeneration.Value;
285       }
286     }
287
288     public static ReflectionDelegateFactory ReflectionDelegateFactory
289     {
290       get
291       {
292 #if !PocketPC && !SILVERLIGHT
293         if (DynamicCodeGeneration)
294           return DynamicReflectionDelegateFactory.Instance;
295 #endif
296
297         return LateBoundReflectionDelegateFactory.Instance;
298       }
299     }
300   }
301 }