Update PointConverter.cs
[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.Serialization;
37 using System.Text;
38 using System.Xml;
39
40 namespace System.Runtime.Serialization.Json
41 {
42         class TypeMap
43         {
44                 static bool IsInvalidNCName (string name)
45                 {
46                         if (name == null || name.Length == 0)
47                                 return true;
48                         try {
49                                 XmlConvert.VerifyNCName (name);
50                         } catch (XmlException) {
51                                 return true;
52                         }
53                         return false;
54                 }
55
56                 public static TypeMap CreateTypeMap (Type type)
57                 {
58                         object [] atts = type.GetCustomAttributes (typeof (DataContractAttribute), true);
59                         if (atts.Length == 1)
60                                 return CreateTypeMap (type, (DataContractAttribute) atts [0]);
61
62                         atts = type.GetCustomAttributes (typeof (SerializableAttribute), false);
63                         if (atts.Length == 1)
64                                 return CreateTypeMap (type, null);
65
66                         if (IsPrimitiveType (type))
67                                 return null;
68
69                         return CreateDefaultTypeMap (type);
70                 }
71
72                 static bool IsPrimitiveType (Type type)
73                 {
74                         if (type.IsEnum)
75                                 return true;
76                         if (Type.GetTypeCode (type) != TypeCode.Object)
77                                 return true; // FIXME: it is likely hacky
78                         return false;
79                 }
80
81                 static TypeMap CreateDefaultTypeMap (Type type)
82                 {
83                         var l = new List<TypeMapMember> ();
84                         foreach (var fi in type.GetFields ())
85                                 if (!fi.IsStatic)
86                                         l.Add (new TypeMapField (fi, null));
87                         foreach (var pi in type.GetProperties ())
88                                 if (pi.CanRead && pi.CanWrite && !pi.GetGetMethod ().IsStatic && pi.GetIndexParameters ().Length == 0)
89                                         l.Add (new TypeMapProperty (pi, null));
90                         l.Sort ((x, y) => x.Order != y.Order ? x.Order - y.Order : String.Compare (x.Name, y.Name, StringComparison.Ordinal));
91                         return new TypeMap (type, null, l.ToArray ());
92                 }
93
94                 internal static bool IsDictionary (Type type)
95                 {
96                         if (type.GetInterface ("System.Collections.IDictionary", false) != null)
97                                 return true;
98                         if (type.GetInterface ("System.Collections.Generic.IDictionary`2", false) != null)
99                                 return true;
100                         return false;
101                 }
102
103                 internal static bool IsCollection (Type type)
104                 {
105                         if (IsPrimitiveType (type) || IsDictionary (type))
106                                 return false;
107                         if (type.GetInterface ("System.Collections.IEnumerable", false) != null)
108                                 return true;
109                         return false;
110                 }
111
112                 static TypeMap CreateTypeMap (Type type, DataContractAttribute dca)
113                 {
114                         if (dca != null && dca.Name != null && IsInvalidNCName (dca.Name))
115                                 throw new InvalidDataContractException (String.Format ("DataContractAttribute for type '{0}' has an invalid name", type));
116
117                         List<TypeMapMember> members = new List<TypeMapMember> ();
118
119                         foreach (FieldInfo fi in type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
120                                 if (dca != null) {
121                                         object [] atts = fi.GetCustomAttributes (typeof (DataMemberAttribute), true);
122                                         if (atts.Length == 0)
123                                                 continue;
124                                         DataMemberAttribute dma = (DataMemberAttribute) atts [0];
125                                         members.Add (new TypeMapField (fi, dma));
126                                 } else {
127                                         if (fi.GetCustomAttributes (typeof (IgnoreDataMemberAttribute), false).Length > 0)
128                                                 continue;
129                                         members.Add (new TypeMapField (fi, null));
130                                 }
131                         }
132
133                         if (dca != null) {
134                                 foreach (PropertyInfo pi in type.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
135                                         object [] atts = pi.GetCustomAttributes (typeof (DataMemberAttribute), true);
136                                         if (atts.Length == 0)
137                                                 continue;
138                                         if (pi.GetIndexParameters ().Length > 0)
139                                                 continue;
140                                         if (IsCollection (pi.PropertyType)) {
141                                                 if (!pi.CanRead)
142                                                         throw new InvalidDataContractException (String.Format ("Property {0} must have a getter", pi));
143                                         }
144                                         else if (!pi.CanRead || !pi.CanWrite)
145                                                 throw new InvalidDataContractException (String.Format ("Non-collection property {0} must have both getter and setter", pi));
146                                         DataMemberAttribute dma = (DataMemberAttribute) atts [0];
147                                         members.Add (new TypeMapProperty (pi, dma));
148                                 }
149                         }
150
151                         members.Sort (delegate (TypeMapMember m1, TypeMapMember m2) { return m1.Order != m2.Order ? m1.Order - m2.Order : String.CompareOrdinal (m1.Name, m2.Name); });
152                         return new TypeMap (type, dca == null ? null : dca.Name, members.ToArray ());
153                 }
154
155                 Type type;
156                 string element;
157                 TypeMapMember [] members;
158
159                 static readonly Type [] deser_methods_args = new Type [] { typeof (StreamingContext) };
160                 const BindingFlags binding_flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
161
162                 public TypeMap (Type type, string element, TypeMapMember [] orderedMembers)
163                 {
164                         this.type = type;
165                         this.element = element;
166                         this.members = orderedMembers;
167
168                         foreach (var mi in type.GetMethods (binding_flags)) {
169                                 if (mi.GetCustomAttributes (typeof (OnDeserializingAttribute), false).Length > 0)
170                                         OnDeserializing = mi;
171                                 else if (mi.GetCustomAttributes (typeof (OnDeserializedAttribute), false).Length > 0)
172                                         OnDeserialized = mi;
173                                 else if (mi.GetCustomAttributes (typeof (OnSerializingAttribute), false).Length > 0)
174                                         OnSerializing = mi;
175                                 else if (mi.GetCustomAttributes (typeof (OnSerializedAttribute), false).Length > 0)
176                                         OnSerialized = mi;
177                         }
178                 }
179
180                 public MethodInfo OnDeserializing { get; set; }
181                 public MethodInfo OnDeserialized { get; set; }
182                 public MethodInfo OnSerializing { get; set; }
183                 public MethodInfo OnSerialized { get; set; }
184
185                 public virtual void Serialize (JsonSerializationWriter outputter, object graph, string type)
186                 {
187                         if (OnSerializing != null)
188                                 OnSerializing.Invoke (graph, new object [] {new StreamingContext (StreamingContextStates.All)});
189
190                         outputter.Writer.WriteAttributeString ("type", type);
191                         foreach (TypeMapMember member in members) {
192                                 object memberObj = member.GetMemberOf (graph);
193                                 // FIXME: consider EmitDefaultValue
194                                 outputter.Writer.WriteStartElement (member.Name);
195                                 outputter.WriteObjectContent (memberObj, false, false);
196                                 outputter.Writer.WriteEndElement ();
197                         }
198
199                         if (OnSerialized != null)
200                                 OnSerialized.Invoke (graph, new object [] {new StreamingContext (StreamingContextStates.All)});
201                 }
202
203                 internal static object CreateInstance (Type type)
204                 {
205                         if (TypeMap.IsDictionary (type)) {
206                                 if (type.IsGenericType)
207                                         return Activator.CreateInstance (typeof (Dictionary<,>).MakeGenericType (type.GetGenericArguments ()));
208                                 else
209                                         return new Hashtable ();
210                         } else if (TypeMap.IsCollection (type)) {
211                                 if (type.IsGenericType)
212                                         return Activator.CreateInstance (typeof (List<>).MakeGenericType (type.GetGenericArguments ()));
213                                 else
214                                         return new ArrayList ();
215                         }
216                         else
217                                 return FormatterServices.GetUninitializedObject (type);
218                 }
219
220                 public virtual object Deserialize (JsonSerializationReader jsr)
221                 {
222                         XmlReader reader = jsr.Reader;
223                         bool isNull = reader.GetAttribute ("type") == "null";
224
225                         object ret = isNull ? null : CreateInstance (type);
226                         if (ret != null && OnDeserializing != null)
227                                 OnDeserializing.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
228                         Dictionary<TypeMapMember,bool> filled = new Dictionary<TypeMapMember,bool> ();
229
230                         reader.ReadStartElement ();
231                         for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
232                                 bool consumed = false;
233                                 for (int i = 0; i < members.Length; i++) {
234                                         TypeMapMember mm = members [i];
235                                         if (mm.Name == reader.LocalName && reader.NamespaceURI == String.Empty) {
236                                                 if (filled.ContainsKey (mm))
237                                                         throw new SerializationException (String.Format ("Object content '{0}' for '{1}' already appeared in the reader", reader.LocalName, type));
238                                                 mm.SetMemberValue (ret, jsr.ReadObject (mm.Type));
239                                                 filled [mm] = true;
240                                                 consumed = true;
241                                                 break;
242                                         }
243                                 }
244                                 if (!consumed)
245                                         reader.Skip ();
246                         }
247                         reader.ReadEndElement ();
248                         if (ret != null && OnDeserialized != null)
249                                 OnDeserialized.Invoke (ret, new object [] {new StreamingContext (StreamingContextStates.All)});
250                         return ret;
251                 }
252         }
253
254         abstract class TypeMapMember
255         {
256                 MemberInfo mi;
257                 DataMemberAttribute dma;
258
259                 protected TypeMapMember (MemberInfo mi, DataMemberAttribute dma)
260                 {
261                         this.mi = mi;
262                         this.dma = dma;
263                 }
264
265                 public string Name {
266                         get { return dma == null ? mi.Name : dma.Name ?? mi.Name; }
267                 }
268
269                 public bool EmitDefaultValue {
270                         get { return dma != null && dma.EmitDefaultValue; }
271                 }
272
273                 public bool IsRequired {
274                         get { return dma != null && dma.IsRequired; }
275                 }
276
277                 public int Order {
278                         get { return dma != null ? dma.Order : -1; }
279                 }
280
281                 public abstract Type Type { get; }
282
283                 public abstract object GetMemberOf (object owner);
284
285                 public abstract void SetMemberValue (object owner, object value);
286         }
287
288         class TypeMapField : TypeMapMember
289         {
290                 FieldInfo field;
291
292                 public TypeMapField (FieldInfo fi, DataMemberAttribute dma)
293                         : base (fi, dma)
294                 {
295                         this.field = fi;
296                 }
297
298                 public override Type Type {
299                         get { return field.FieldType; }
300                 }
301
302                 public override object GetMemberOf (object owner)
303                 {
304                         return field.GetValue (owner);
305                 }
306
307                 public override void SetMemberValue (object owner, object value)
308                 {
309                         field.SetValue (owner, value);
310                 }
311         }
312
313         class TypeMapProperty : TypeMapMember
314         {
315                 PropertyInfo property;
316
317                 public TypeMapProperty (PropertyInfo pi, DataMemberAttribute dma)
318                         : base (pi, dma)
319                 {
320                         this.property = pi;
321                 }
322
323                 public override Type Type {
324                         get { return property.PropertyType; }
325                 }
326
327                 public override object GetMemberOf (object owner)
328                 {
329                         return property.GetValue (owner, null);
330                 }
331
332                 public override void SetMemberValue (object owner, object value)
333                 {
334                         property.SetValue (owner, value, null);
335                 }
336         }
337 }