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