2 // XmlFormatterDeserializer.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2005 Novell, Inc. http://www.novell.com
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
30 using System.Collections.Generic;
33 using System.Reflection;
34 using System.Runtime.Serialization.Formatters.Binary;
36 using System.Xml.Schema;
38 using QName = System.Xml.XmlQualifiedName;
40 namespace System.Runtime.Serialization
42 internal class XmlFormatterDeserializer
44 KnownTypeCollection types;
45 IDataContractSurrogate surrogate;
46 DataContractResolver resolver, default_resolver; // new in 4.0.
47 // 3.5 SP1 supports deserialization by reference (id->obj).
48 // Though unlike XmlSerializer, it does not support forward-
49 // reference resolution i.e. a referenced object must appear
50 // before any references to it.
51 Dictionary<string,object> references = new Dictionary<string,object> ();
52 Dictionary<QName,Type> resolved_qnames = new Dictionary<QName,Type> ();
54 public static object Deserialize (XmlReader reader, Type declaredType,
55 KnownTypeCollection knownTypes, IDataContractSurrogate surrogate, DataContractResolver resolver, DataContractResolver defaultResolver,
56 string name, string ns, bool verifyObjectName)
58 reader.MoveToContent ();
60 if (reader.NodeType != XmlNodeType.Element ||
61 reader.LocalName != name ||
62 reader.NamespaceURI != ns)
63 throw new SerializationException (String.Format ("Expected element '{0}' in namespace '{1}', but found {2} node '{3}' in namespace '{4}'", name, ns, reader.NodeType, reader.LocalName, reader.NamespaceURI));
64 // Verify (knownTypes, declaredType, name, ns, reader);
65 return new XmlFormatterDeserializer (knownTypes, surrogate, resolver, defaultResolver).Deserialize (declaredType, reader);
68 // Verify the top element name and namespace.
69 private static void Verify (KnownTypeCollection knownTypes, Type type, string name, string Namespace, XmlReader reader)
71 QName graph_qname = new QName (reader.LocalName, reader.NamespaceURI);
72 if (graph_qname.Name == name && graph_qname.Namespace == Namespace)
75 // <BClass .. i:type="EClass" >..</BClass>
76 // Expecting type EClass : allowed
77 // See test Serialize1b, and Serialize1c (for
80 // Run through inheritance heirarchy ..
81 for (Type baseType = type; baseType != null; baseType = baseType.BaseType)
82 if (knownTypes.GetQName (baseType) == graph_qname)
85 QName typeQName = knownTypes.GetQName (type);
86 throw new SerializationException (String.Format (
87 "Expecting element '{0}' from namespace '{1}'. Encountered 'Element' with name '{2}', namespace '{3}'",
88 typeQName.Name, typeQName.Namespace, graph_qname.Name, graph_qname.Namespace));
91 private XmlFormatterDeserializer (
92 KnownTypeCollection knownTypes,
93 IDataContractSurrogate surrogate,
94 DataContractResolver resolver,
95 DataContractResolver defaultResolver)
97 this.types = knownTypes;
98 this.surrogate = surrogate;
99 this.resolver = resolver;
100 this.default_resolver = defaultResolver;
103 public Dictionary<string,object> References {
104 get { return references; }
107 // This method handles z:Ref, xsi:nil and primitive types, and then delegates to DeserializeByMap() for anything else.
108 public object Deserialize (Type type, XmlReader reader)
110 QName graph_qname = types.GetQName (type);
111 string itype = reader.GetAttribute ("type", XmlSchema.InstanceNamespace);
113 string[] parts = itype.Split (':');
114 if (parts.Length > 1)
115 graph_qname = new QName (parts [1], reader.LookupNamespace (reader.NameTable.Get (parts[0])));
117 graph_qname = new QName (itype, reader.NamespaceURI);
120 string label = reader.GetAttribute ("Ref", KnownTypeCollection.MSSimpleNamespace);
123 if (!references.TryGetValue (label, out o))
124 throw new SerializationException (String.Format ("Deserialized object with reference Id '{0}' was not found", label));
129 bool isNil = reader.GetAttribute ("nil", XmlSchema.InstanceNamespace) == "true";
133 if (!type.IsValueType)
135 else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>))
138 throw new SerializationException (String.Format ("Value type {0} cannot be null.", type));
141 if (resolver != null) {
143 if (resolved_qnames.TryGetValue (graph_qname, out t))
145 else { // i.e. resolve name only once.
146 type = resolver.ResolveName (graph_qname.Name, graph_qname.Namespace, type, default_resolver) ?? type;
147 resolved_qnames.Add (graph_qname, type);
152 if (KnownTypeCollection.GetPrimitiveTypeFromName (graph_qname.Name) != null) {
153 string id = reader.GetAttribute ("Id", KnownTypeCollection.MSSimpleNamespace);
156 if (reader.IsEmptyElement) {
157 reader.Read (); // advance
158 if (type.IsValueType)
159 return Activator.CreateInstance (type);
161 // FIXME: Workaround for creating empty objects of the correct type.
162 value = String.Empty;
165 value = reader.ReadElementContentAsString ();
166 object ret = KnownTypeCollection.PredefinedTypeStringToObject (value, graph_qname.Name, reader);
168 if (references.ContainsKey (id))
169 throw new InvalidOperationException (String.Format ("Object with Id '{0}' already exists as '{1}'", id, references [id]));
170 references.Add (id, ret);
175 return DeserializeByMap (graph_qname, type, reader);
178 object DeserializeByMap (QName name, Type type, XmlReader reader)
180 SerializationMap map = resolved_qnames.ContainsKey (name) ? types.FindUserMap (type) : types.FindUserMap (name); // use type when the name is "resolved" one. Otherwise use name (there are cases that type cannot be resolved by type).
181 if (map == null && (name.Name.StartsWith ("ArrayOf", StringComparison.Ordinal) ||
182 name.Namespace == KnownTypeCollection.MSArraysNamespace ||
183 name.Namespace.StartsWith (KnownTypeCollection.DefaultClrNamespaceBase, StringComparison.Ordinal))) {
184 var it = GetTypeFromNamePair (name.Name, name.Namespace);
186 map = types.FindUserMap (name);
189 throw new SerializationException (String.Format ("Unknown type {0} is used for DataContract with reference of name {1}. Any derived types of a data contract or a data member should be added to KnownTypes.", type, name));
191 return map.DeserializeObject (reader, this);
194 Type GetTypeFromNamePair (string name, string ns)
196 Type p = KnownTypeCollection.GetPrimitiveTypeFromName (name); // FIXME: namespace?
199 bool makeArray = false;
200 if (name.StartsWith ("ArrayOf", StringComparison.Ordinal)) {
201 name = name.Substring (7); // strip "ArrayOf"
202 if (ns == KnownTypeCollection.MSArraysNamespace)
203 return GetTypeFromNamePair (name, String.Empty).MakeArrayType ();
207 string dnsb = KnownTypeCollection.DefaultClrNamespaceBase;
208 string clrns = ns.StartsWith (dnsb, StringComparison.Ordinal) ? ns.Substring (dnsb.Length) : ns;
210 foreach (var ass in AppDomain.CurrentDomain.GetAssemblies ()) {
215 types = ass.GetTypes ();
216 } catch (System.Reflection.ReflectionTypeLoadException rtle) {
220 types = ass.GetTypes ();
225 foreach (var t in types) {
226 // there can be null entries or exception throw to access the attribute -
227 // at least when some referenced assemblies could not be loaded (affects moonlight)
232 var dca = t.GetCustomAttribute<DataContractAttribute> (true);
233 if (dca != null && dca.Name == name && dca.Namespace == ns)
234 return makeArray ? t.MakeArrayType () : t;
236 catch (TypeLoadException tle) {
237 Console.Error.WriteLine (tle);
240 catch (FileNotFoundException fnfe) {
241 Console.Error.WriteLine (fnfe);
245 if (clrns != null && t.Name == name && t.Namespace == clrns)
246 return makeArray ? t.MakeArrayType () : t;
249 throw new XmlException (String.Format ("Type not found; name: {0}, namespace: {1}", name, ns));