Merge pull request #901 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / class / System.ServiceModel.Web / System.Runtime.Serialization.Json / JsonSerializationReader.cs
1 //
2 // JsonSerializationReader.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.Text;
37 using System.Xml;
38
39 namespace System.Runtime.Serialization.Json
40 {
41         class JsonSerializationReader
42         {
43                 DataContractJsonSerializer serializer;
44                 XmlReader reader;
45                 int serialized_object_count;
46                 bool verify_object_name;
47                 Dictionary<Type, TypeMap> typemaps = new Dictionary<Type, TypeMap> ();
48                 Type root_type;
49
50                 public JsonSerializationReader (DataContractJsonSerializer serializer, XmlReader reader, Type rootType, bool verifyObjectName)
51                 {
52                         this.serializer = serializer;
53                         this.reader = reader;
54                         this.root_type = rootType;
55                         this.verify_object_name = verifyObjectName;
56                 }
57
58                 public XmlReader Reader {
59                         get { return reader; }
60                 }
61
62                 public object ReadRoot ()
63                 {
64                         TypeMap rootMap = GetTypeMap (root_type);
65
66                         object v = ReadObject (root_type);
67                         return v;
68                 }
69
70                 public object ReadObject (Type type)
71                 {
72                         if (serialized_object_count ++ == serializer.MaxItemsInObjectGraph)
73                                 throw SerializationError (String.Format ("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph));
74
75                         bool nullable = false;
76                         if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) {
77                                 nullable = true;
78                                 type = Nullable.GetUnderlyingType (type);
79                         }
80
81                         bool isNull = reader.GetAttribute ("type") == "null";
82
83                         switch (Type.GetTypeCode (type)) {
84                         case TypeCode.DBNull:
85                                 string dbn = reader.ReadElementContentAsString ();
86                                 if (dbn != String.Empty)
87                                         throw new SerializationException (String.Format ("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn));
88                                 return DBNull.Value;
89                         case TypeCode.String:
90                                 if (isNull) {
91                                         reader.ReadElementContentAsString ();
92                                         return null;
93                                 }
94                                 else
95                                         return reader.ReadElementContentAsString ();
96                         case TypeCode.Char:
97                                 var c = reader.ReadElementContentAsString ();
98                                 if (c.Length > 1)
99                                         throw new XmlException ("Invalid JSON char");
100                                 return Char.Parse(c);
101                         case TypeCode.Single:
102                         case TypeCode.Double:
103                         case TypeCode.Decimal:
104                                         return ReadValueType (type, nullable);
105                         case TypeCode.Byte:
106                         case TypeCode.SByte:
107                         case TypeCode.Int16:
108                         case TypeCode.Int32:
109                         case TypeCode.UInt16:
110                         case TypeCode.UInt32:
111                         case TypeCode.Int64:
112                                 if (type.IsEnum)
113                                         return Enum.ToObject (type, Convert.ChangeType (reader.ReadElementContentAsLong (), Enum.GetUnderlyingType (type), null));
114                                 else
115                                         return ReadValueType (type, nullable);
116                         case TypeCode.UInt64:
117                                 if (type.IsEnum)
118                                         return Enum.ToObject (type, Convert.ChangeType (reader.ReadElementContentAsDecimal (), Enum.GetUnderlyingType (type), null));
119                                 else
120                                         return ReadValueType (type, nullable);
121                         case TypeCode.Boolean:
122                                 return ReadValueType (type, nullable);
123                         case TypeCode.DateTime:
124                                 // it does not use ReadElementContentAsDateTime(). Different string format.
125                                 var s = reader.ReadElementContentAsString ();
126                                 if (s.Length < 2 || !s.StartsWith ("/Date(", StringComparison.Ordinal) || !s.EndsWith (")/", StringComparison.Ordinal)) {
127                                         if (nullable)
128                                                 return null;
129                                         throw new XmlException ("Invalid JSON DateTime format. The value format should be '/Date(UnixTime)/'");
130                                 }
131
132                                 // The date can contain [SIGN]LONG, [SIGN]LONG+HOURSMINUTES or [SIGN]LONG-HOURSMINUTES
133                                 // the format for HOURSMINUTES is DDDD
134                                 int tidx = s.IndexOf ('-', 8);
135                                 if (tidx == -1)
136                                         tidx = s.IndexOf ('+', 8);
137                                 int minutes = 0;
138                                 if (tidx == -1){
139                                         s = s.Substring (6, s.Length - 8);
140                                 } else {
141                                         int offset;
142                                         int.TryParse (s.Substring (tidx+1, s.Length-3-tidx), out offset);
143
144                                         minutes = (offset % 100) + (offset / 100) * 60;
145                                         if (s [tidx] == '-')
146                                                 minutes = -minutes;
147
148                                         s = s.Substring (6, tidx-6);
149                                 }
150                                 var date = new DateTime (1970, 1, 1).AddMilliseconds (long.Parse (s));
151                                 if (minutes != 0)
152                                         date = date.AddMinutes (minutes);
153                                 return date;
154                         default:
155                                 if (type == typeof (Guid)) {
156                                         return new Guid (reader.ReadElementContentAsString ());
157                                 } else if (type == typeof (Uri)) {
158                                         if (isNull) {
159                                                 reader.ReadElementContentAsString ();
160                                                 return null;
161                                         }
162                                         else
163                                                 return new Uri (reader.ReadElementContentAsString (), UriKind.RelativeOrAbsolute);
164                                 } else if (type == typeof (XmlQualifiedName)) {
165                                         s = reader.ReadElementContentAsString ();
166                                         int idx = s.IndexOf (':');
167                                         return idx < 0 ? new XmlQualifiedName (s) : new XmlQualifiedName (s.Substring (0, idx), s.Substring (idx + 1));
168                                 } else if (type != typeof (object)) {
169                                         // strongly-typed object
170                                         if (reader.IsEmptyElement) {
171                                                 // empty -> null array or object
172                                                 reader.Read ();
173                                                 return null;
174                                         }
175
176                                         Type ct = GetCollectionElementType (type);
177                                         if (ct != null) {
178                                                 return DeserializeGenericCollection (type, ct);
179                                         } else {
180                                                 TypeMap map = GetTypeMap (type);
181                                                 return map.Deserialize (this);
182                                         }
183                                 }
184                                 else
185                                         return ReadInstanceDrivenObject ();
186                         }
187                 }
188                 
189                 object ReadValueType (Type type, bool nullable)
190                 {
191                         string s = reader.ReadElementContentAsString ();
192                         return nullable && s.Trim ().Length == 0 ? null : Convert.ChangeType (s, type, null);
193                 }
194                 
195
196                 Type GetRuntimeType (string name)
197                 {
198                         name = ToRuntimeTypeName (name);
199                         if (serializer.KnownTypes != null)
200                                 foreach (Type t in serializer.KnownTypes)
201                                         if (t.FullName == name)
202                                                 return t;
203                         var ret = root_type.Assembly.GetType (name, false) ?? Type.GetType (name, false);
204                         if (ret != null)
205                                 return ret;
206
207                         // We probably have to iterate all the existing
208                         // assemblies that are loaded in current domain.
209                         foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
210                                 ret = ass.GetType (name, false);
211                                 if (ret != null)
212                                         return ret;
213                         }
214
215                         return null;
216                 }
217
218                 object ReadInstanceDrivenObject ()
219                 {
220                         string type = reader.GetAttribute ("type");
221                         switch (type) {
222                         case "null":
223                                 reader.Skip ();
224                                 return null;
225                         case "object":
226                                 string runtimeType = reader.GetAttribute ("__type");
227                                 if (runtimeType != null) {
228                                         Type t = GetRuntimeType (runtimeType);
229                                         if (t == null)
230                                                 throw SerializationError (String.Format ("Cannot load type '{0}'", runtimeType));
231                                         return ReadObject (t);
232                                 }
233                                 break;
234                         }
235                         string v = reader.ReadElementContentAsString ();
236                         switch (type) {
237                         case "boolean":
238                                 switch (v) {
239                                 case "true":
240                                         return true;
241                                 case "false":
242                                         return false;
243                                 default:
244                                         throw SerializationError (String.Format ("Invalid JSON boolean value: {0}", v));
245                                 }
246                         case "string":
247                                 return v;
248                         case "number":
249                                 int i;
250                                 if (int.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out i))
251                                         return i;
252                                 long l;
253                                 if (long.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out l))
254                                         return l;
255                                 ulong ul;
256                                 if (ulong.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out ul))
257                                         return ul;
258                                 double dbl;
259                                 if (double.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dbl))
260                                         return dbl;
261                                 decimal dec;
262                                 if (decimal.TryParse (v, NumberStyles.None, CultureInfo.InvariantCulture, out dec))
263                                         return dec;
264                                 throw SerializationError (String.Format ("Invalid JSON input: {0}", v));
265                         default:
266                                 throw SerializationError (String.Format ("Unexpected type: {0}", type));
267                         }
268                 }
269
270                 string FormatTypeName (Type type)
271                 {
272                         return type.Namespace == null ? type.Name : String.Format ("{0}:#{1}", type.Name, type.Namespace);
273                 }
274
275                 string ToRuntimeTypeName (string s)
276                 {
277                         int idx = s.IndexOf (":#", StringComparison.Ordinal);
278                         return idx < 0 ? s : String.Concat (s.Substring (idx + 2), ".", s.Substring (0, idx));
279                 }
280
281                 IEnumerable<Type> GetInterfaces2 (Type type)
282                 {
283                         if (type.IsInterface)
284                                 yield return type;
285                         foreach (var t in type.GetInterfaces ())
286                                 yield return t;
287                 }
288
289                 Type GetCollectionElementType (Type type)
290                 {
291                         if (type.IsArray)
292                                 return type.GetElementType ();
293                         if (type.IsGenericType) {
294                                 // returns T for IEnumerable<T>
295                                 foreach (Type i in GetInterfaces2 (type))
296                                         if (i.IsGenericType && i.GetGenericTypeDefinition ().Equals (typeof (IEnumerable<>)))
297                                                 return i.GetGenericArguments () [0];
298                         }
299                         if (typeof (IEnumerable).IsAssignableFrom (type))
300                                 // return typeof(object) for mere collection.
301                                 return typeof (object);
302                         else
303                                 return null;
304                 }
305
306                 object DeserializeGenericCollection (Type collectionType, Type elementType)
307                 {
308                         reader.ReadStartElement ();
309                         object ret;
310                         if (collectionType.IsInterface)
311                                 collectionType = typeof (List<>).MakeGenericType (elementType);
312                         if (TypeMap.IsDictionary (collectionType)) {
313                                 object dic = Activator.CreateInstance (collectionType);
314                                 var itemSetter = dic.GetType ().GetProperty ("Item");
315                                 var keyarr = new object [1];
316
317                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
318                                         if (!reader.IsStartElement ("item"))
319                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
320
321                                         // reading a KeyValuePair in the form of <Key .../><Value .../>
322                                         reader.Read ();
323                                         reader.MoveToContent ();
324                                         object key = ReadObject (elementType.GetGenericArguments () [0]);
325                                         reader.MoveToContent ();
326                                         object val = ReadObject (elementType.GetGenericArguments () [1]);
327                                         reader.Read ();
328                                         keyarr [0] = key;
329                                         itemSetter.SetValue (dic, val, keyarr);
330                                 }
331                                 ret = dic;
332                         } else if (typeof (IList).IsAssignableFrom (collectionType)) {
333 #if NET_2_1
334                                 Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
335 #else
336                                 Type listType = collectionType.IsArray ? typeof (ArrayList) : null;
337 #endif
338                                 IList c = (IList) Activator.CreateInstance (listType ?? collectionType);
339                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
340                                         if (!reader.IsStartElement ("item"))
341                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
342                                         Type et = elementType == typeof (object) || elementType.IsAbstract ? null : elementType;
343                                         object elem = ReadObject (et ?? typeof (object));
344                                         c.Add (elem);
345                                 }
346 #if NET_2_1
347                                 if (collectionType.IsArray) {
348                                         Array array = Array.CreateInstance (elementType, c.Count);
349                                         c.CopyTo (array, 0);
350                                         ret = array;
351                                 }
352                                 else
353                                         ret = c;
354 #else
355                                 ret = collectionType.IsArray ? ((ArrayList) c).ToArray (elementType) : c;
356 #endif
357                         } else {
358                                 object c = Activator.CreateInstance (collectionType);
359                                 MethodInfo add = collectionType.GetMethod ("Add", new Type [] {elementType});
360                                 if (add == null) {
361                                         var icoll = typeof (ICollection<>).MakeGenericType (elementType);
362                                         if (icoll.IsAssignableFrom (c.GetType ()))
363                                                 add = icoll.GetMethod ("Add");
364                                 }
365                                 
366                                 for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
367                                         if (!reader.IsStartElement ("item"))
368                                                 throw SerializationError (String.Format ("Expected element 'item', but found '{0}' in namespace '{1}'", reader.LocalName, reader.NamespaceURI));
369                                         object elem = ReadObject (elementType);
370                                         add.Invoke (c, new object [] {elem});
371                                 }
372                                 ret = c;
373                         }
374
375                         reader.ReadEndElement ();
376                         return ret;
377                 }
378
379                 TypeMap GetTypeMap (Type type)
380                 {
381                         TypeMap map;
382                         if (!typemaps.TryGetValue (type, out map)) {
383                                 map = TypeMap.CreateTypeMap (type);
384                                 typemaps [type] = map;
385                         }
386                         return map;
387                 }
388
389                 Exception SerializationError (string basemsg)
390                 {
391                         IXmlLineInfo li = reader as IXmlLineInfo;
392                         if (li == null || !li.HasLineInfo ())
393                                 return new SerializationException (basemsg);
394                         else
395                                 return new SerializationException (String.Format ("{0}. Error at {1} ({2},{3})", basemsg, reader.BaseURI, li.LineNumber, li.LinePosition));
396                 }
397         }
398 }