Merge pull request #799 from kebby/master
[mono.git] / mcs / class / System.ServiceModel.Web / System.Runtime.Serialization.Json / TypeMap.cs
1 //
2 // TypeMap.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections;
30 using System.Collections.Generic;
31 using System.Collections.ObjectModel;
32 using System.Globalization;
33 using System.IO;
34 using System.Linq;
35 using System.Reflection;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.Serialization;
38 using System.Text;
39 using System.Xml;
40
41 namespace System.Runtime.Serialization.Json
42 {
43         class TypeMap
44         {
45                 static bool IsInvalidNCName (string name)
46                 {
47                         if (name == null || name.Length == 0)
48                                 return true;
49                         try {
50                                 XmlConvert.VerifyNCName (name);
51                         } catch (XmlException) {
52                                 return true;
53                         }
54                         return false;
55                 }
56
57                 public static TypeMap CreateTypeMap (Type type)
58                 {
59                         object [] atts = type.GetCustomAttributes (typeof (DataContractAttribute), true);
60                         if (atts.Length == 1)
61                                 return CreateTypeMap (type, (DataContractAttribute) atts [0]);
62
63                         atts = type.GetCustomAttributes (typeof (SerializableAttribute), false);
64                         if (atts.Length == 1)
65                                 return CreateTypeMap (type, null);
66
67                         if (IsPrimitiveType (type))
68                                 return null;
69
70                         return CreateDefaultTypeMap (type);
71                 }
72
73                 static bool IsPrimitiveType (Type type)
74                 {
75                         if (type.IsEnum)
76                                 return true;
77                         if (Type.GetTypeCode (type) != TypeCode.Object)
78                                 return true; // FIXME: it is likely hacky
79                         return false;
80                 }
81
82                 static TypeMap CreateDefaultTypeMap (Type type)
83                 {
84                         var l = new List<TypeMapMember> ();
85                         foreach (var fi in type.GetFields ())
86                                 if (!fi.IsStatic)
87                                         l.Add (new TypeMapField (fi, null));
88                         foreach (var pi in type.GetProperties ())
89                                 if (pi.CanRead && pi.CanWrite && !pi.GetGetMethod (true).IsStatic && pi.GetIndexParameters ().Length == 0)
90                                         l.Add (new TypeMapProperty (pi, null));
91                         l.Sort ((x, y) => x.Order != y.Order ? x.Order - y.Order : String.Compare (x.Name, y.Name, StringComparison.Ordinal));
92                         return new TypeMap (type, null, l.ToArray ());
93                 }
94
95                 internal static bool IsDictionary (Type type)
96                 {
97                         if (type.GetInterface ("System.Collections.IDictionary", false) != null)
98                                 return true;
99                         if (type.GetInterface ("System.Collections.Generic.IDictionary`2", false) != null)
100                                 return true;
101                         return false;
102                 }
103
104                 internal static bool IsCollection (Type type)
105                 {
106                         if (IsPrimitiveType (type) || IsDictionary (type))
107                                 return false;
108                         if (type.GetInterface ("System.Collections.IEnumerable", false) != null)
109                                 return true;
110                         return false;
111                 }
112
113                 static TypeMap CreateTypeMap (Type type, DataContractAttribute dca)
114                 {
115                         if (dca != null && dca.Name != null && IsInvalidNCName (dca.Name))
116                                 throw new InvalidDataContractException (String.Format ("DataContractAttribute for type '{0}' has an invalid name", type));
117
118                         List<TypeMapMember> members = new List<TypeMapMember> ();
119
120                         foreach (FieldInfo fi in type.GetFields (binding_flags)) {
121                                 if (fi.GetCustomAttributes (typeof (CompilerGeneratedAttribute), false).Length > 0)
122                                         continue;
123                                 if (dca != null) {
124                                         object [] atts = fi.GetCustomAttributes (typeof (DataMemberAttribute), true);
125                                         if (atts.Length == 0)
126                                                 continue;
127                                         DataMemberAttribute dma = (DataMemberAttribute) atts [0];
128                                         members.Add (new TypeMapField (fi, dma));
129                                 } else {
130                                         if (fi.GetCustomAttributes (typeof (IgnoreDataMemberAttribute), false).Length > 0)
131                                                 continue;
132                                         members.Add (new TypeMapField (fi, null));
133                                 }
134                         }
135
136                         if (dca != null) {
137                                 foreach (PropertyInfo pi in type.GetProperties (binding_flags)) {
138                                         object [] atts = pi.GetCustomAttributes (typeof (DataMemberAttribute), true);
139                                         if (atts.Length == 0)
140                                                 continue;
141                                         if (pi.GetIndexParameters ().Length > 0)
142                                                 continue;
143                                         if (IsCollection (pi.PropertyType)) {
144                                                 if (!pi.CanRead)
145                                                         throw new InvalidDataContractException (String.Format ("Property {0} must have a getter", pi));
146                                         }
147                                         else if (!pi.CanRead || !pi.CanWrite)
148                                                 throw new InvalidDataContractException (String.Format ("Non-collection property {0} must have both getter and setter", pi));
149                                         DataMemberAttribute dma = (DataMemberAttribute) atts [0];
150                                         members.Add (new TypeMapProperty (pi, dma));
151                                 }
152                         }
153
154                         members.Sort (delegate (TypeMapMember m1, TypeMapMember m2) { return m1.Order != m2.Order ? m1.Order - m2.Order : String.CompareOrdinal (m1.Name, m2.Name); });
155                         return new TypeMap (type, dca == null ? null : dca.Name, members.ToArray ());
156                 }
157
158                 Type type;
159                 string element;
160                 TypeMapMember [] members;
161
162                 static readonly Type [] deser_methods_args = new Type [] { typeof (StreamingContext) };
163                 const BindingFlags binding_flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
164
165                 public TypeMap (Type type, string element, TypeMapMember [] orderedMembers)
166                 {
167                         this.type = type;
168                         this.element = element;
169                         this.members = orderedMembers;
170
171                         foreach (var mi in type.GetMethods (binding_flags)) {
172                                 if (mi.GetCustomAttributes (typeof (OnDeserializingAttribute), false).Length > 0)
173                                         OnDeserializing = mi;
174                                 else if (mi.GetCustomAttributes (typeof (OnDeserializedAttribute), false).Length > 0)
175                                         OnDeserialized = mi;
176                                 else if (mi.GetCustomAttributes (typeof (OnSerializingAttribute), false).Length > 0)
177                                         OnSerializing = mi;
178                                 else if (mi.GetCustomAttributes (typeof (OnSerializedAttribute), false).Length > 0)
179                                         OnSerialized = mi;
180                         }
181                 }
182
183                 public MethodInfo OnDeserializing { get; set; }
184                 public MethodInfo OnDeserialized { get; set; }
185                 public MethodInfo OnSerializing { get; set; }
186                 public MethodInfo OnSerialized { get; set; }
187
188                 public virtual void Serialize (JsonSerializationWriter outputter, object graph, string type)
189                 {
190                         if (OnSerializing != null)
191                                 OnSerializing.Invoke (graph, new object [] {new StreamingContext (StreamingContextStates.All)});
192
193                         outputter.Writer.WriteAttributeString ("type", type);
194                         foreach (TypeMapMember member in members) {
195                                 object memberObj = member.GetMemberOf (graph);
196                                 // FIXME: consider EmitDefaultValue
197                                 outputter.Writer.WriteStartElement (member.Name);
198                                 outputter.WriteObjectContent (memberObj, false, false);
199                                 outputter.Writer.WriteEndElement ();
200                         }
201
202                         if (OnSerialized != null)
203                                 OnSerialized.Invoke (graph, new object [] {new StreamingContext (StreamingContextStates.All)});
204                 }
205
206                 internal static object CreateInstance (Type type)
207                 {
208                         if (TypeMap.IsDictionary (type)) {
209                                 if (type.IsGenericType)
210                                         return Activator.CreateInstance (typeof (Dictionary<,>).MakeGenericType (type.GetGenericArguments ()));
211                                 else
212                                         return new Hashtable ();
213                         } else if (TypeMap.IsCollection (type)) {
214                                 if (type.IsGenericType)
215                                         return Activator.CreateInstance (typeof (List<>).MakeGenericType (type.GetGenericArguments ()));
216                                 else
217                                         return new ArrayList ();
218                         }
219                         else
220                                 return FormatterServices.GetUninitializedObject (type);
221                 }
222
223                 public virtual object Deserialize (JsonSerializationReader jsr)
224                 {
225                         XmlReader reader = jsr.Reader;
226                         bool isNull = reader.GetAttribute ("type") == "null";
227
228                         object ret = isNull ? null : CreateInstance (type);
229                         if (ret != null && OnDeserializing != null)
230                                 OnDeserializing.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
231                         Dictionary<TypeMapMember,bool> filled = new Dictionary<TypeMapMember,bool> ();
232
233                         reader.ReadStartElement ();
234                         for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
235                                 bool consumed = false;
236                                 for (int i = 0; i < members.Length; i++) {
237                                         TypeMapMember mm = members [i];
238                                         if (mm.Name == reader.LocalName && reader.NamespaceURI == String.Empty) {
239                                                 if (filled.ContainsKey (mm))
240                                                         throw new SerializationException (String.Format ("Object content '{0}' for '{1}' already appeared in the reader", reader.LocalName, type));
241                                                 mm.SetMemberValue (ret, jsr.ReadObject (mm.Type));
242                                                 filled [mm] = true;
243                                                 consumed = true;
244                                                 break;
245                                         }
246                                 }
247                                 if (!consumed)
248                                         reader.Skip ();
249                         }
250                         reader.ReadEndElement ();
251                         if (ret != null && OnDeserialized != null)
252                                 OnDeserialized.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
253                         return ret;
254                 }
255         }
256
257         abstract class TypeMapMember
258         {
259                 MemberInfo mi;
260                 DataMemberAttribute dma;
261
262                 protected TypeMapMember (MemberInfo mi, DataMemberAttribute dma)
263                 {
264                         this.mi = mi;
265                         this.dma = dma;
266                 }
267
268                 public string Name {
269                         get { return dma == null ? mi.Name : dma.Name ?? mi.Name; }
270                 }
271
272                 public bool EmitDefaultValue {
273                         get { return dma != null && dma.EmitDefaultValue; }
274                 }
275
276                 public bool IsRequired {
277                         get { return dma != null && dma.IsRequired; }
278                 }
279
280                 public int Order {
281                         get { return dma != null ? dma.Order : -1; }
282                 }
283
284                 public abstract Type Type { get; }
285
286                 public abstract object GetMemberOf (object owner);
287
288                 public abstract void SetMemberValue (object owner, object value);
289         }
290
291         class TypeMapField : TypeMapMember
292         {
293                 FieldInfo field;
294
295                 public TypeMapField (FieldInfo fi, DataMemberAttribute dma)
296                         : base (fi, dma)
297                 {
298                         this.field = fi;
299                 }
300
301                 public override Type Type {
302                         get { return field.FieldType; }
303                 }
304
305                 public override object GetMemberOf (object owner)
306                 {
307                         return field.GetValue (owner);
308                 }
309
310                 public override void SetMemberValue (object owner, object value)
311                 {
312                         field.SetValue (owner, value);
313                 }
314         }
315
316         class TypeMapProperty : TypeMapMember
317         {
318                 PropertyInfo property;
319
320                 public TypeMapProperty (PropertyInfo pi, DataMemberAttribute dma)
321                         : base (pi, dma)
322                 {
323                         this.property = pi;
324                 }
325
326                 public override Type Type {
327                         get { return property.PropertyType; }
328                 }
329
330                 public override object GetMemberOf (object owner)
331                 {
332                         return property.GetValue (owner, null);
333                 }
334
335                 public override void SetMemberValue (object owner, object value)
336                 {
337                         property.SetValue (owner, value, null);
338                 }
339         }
340 }