1 // created on 24/04/2003 at 15:35
\r
3 // System.Runtime.Serialization.Formatters.Soap.SoapReader
\r
6 // Jean-Marc Andre (jean-marc.andre@polymtl.ca)
\r
10 // Permission is hereby granted, free of charge, to any person obtaining
\r
11 // a copy of this software and associated documentation files (the
\r
12 // "Software"), to deal in the Software without restriction, including
\r
13 // without limitation the rights to use, copy, modify, merge, publish,
\r
14 // distribute, sublicense, and/or sell copies of the Software, and to
\r
15 // permit persons to whom the Software is furnished to do so, subject to
\r
16 // the following conditions:
\r
18 // The above copyright notice and this permission notice shall be
\r
19 // included in all copies or substantial portions of the Software.
\r
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
\r
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
\r
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
\r
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
\r
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
\r
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
\r
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
33 using System.Xml.Schema;
\r
34 using System.Reflection;
\r
35 using System.Collections;
\r
36 using System.Runtime.Remoting;
\r
37 using System.Runtime.Serialization;
\r
38 using System.Runtime.Remoting.Messaging;
\r
39 using System.Runtime.Remoting.Metadata;
\r
41 namespace System.Runtime.Serialization.Formatters.Soap {
\r
42 internal sealed class SoapReader {
\r
46 private SerializationBinder _binder;
\r
47 private SoapTypeMapper mapper;
\r
48 private ObjectManager objMgr;
\r
49 private StreamingContext _context;
\r
50 private long _nextAvailableId = long.MaxValue;
\r
51 private ISurrogateSelector _surrogateSelector;
\r
52 private XmlTextReader xmlReader;
\r
53 private Hashtable _fieldIndices;
\r
54 private long _topObjectId = 1;
\r
58 public MemberInfo[] MemberInfos;
\r
59 public Hashtable Indices;
\r
66 private long NextAvailableId
\r
71 return _nextAvailableId;
\r
77 #region Constructors
\r
79 public SoapReader(SerializationBinder binder, ISurrogateSelector selector, StreamingContext context)
\r
82 objMgr = new ObjectManager(selector, context);
\r
84 _surrogateSelector = selector;
\r
85 _fieldIndices = new Hashtable();
\r
90 #region Public Methods
\r
92 public object Deserialize(Stream inStream, ISoapMessage soapMessage)
\r
94 ArrayList headers = null;
\r
95 xmlReader = new XmlTextReader(inStream);
\r
96 xmlReader.WhitespaceHandling = WhitespaceHandling.None;
\r
97 mapper = new SoapTypeMapper(_binder);
\r
101 // SOAP-ENV:Envelope
\r
102 xmlReader.MoveToContent();
\r
103 xmlReader.ReadStartElement ();
\r
104 xmlReader.MoveToContent();
\r
107 while (!(xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Body" && xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace))
\r
109 if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header" && xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace)
\r
111 if (headers == null) headers = new ArrayList ();
\r
112 DeserializeHeaders (headers);
\r
116 xmlReader.MoveToContent();
\r
120 xmlReader.ReadStartElement();
\r
121 xmlReader.MoveToContent();
\r
124 if (soapMessage != null)
\r
126 if (DeserializeMessage (soapMessage)) {
\r
127 _topObjectId = NextAvailableId;
\r
128 RegisterObject (_topObjectId, soapMessage, null, 0, null, null);
\r
130 xmlReader.MoveToContent();
\r
132 if (headers != null)
\r
133 soapMessage.Headers = (Header[]) headers.ToArray (typeof(Header));
\r
136 while (xmlReader.NodeType != XmlNodeType.EndElement)
\r
140 xmlReader.ReadEndElement ();
\r
141 xmlReader.MoveToContent();
\r
143 // SOAP-ENV:Envelope
\r
144 xmlReader.ReadEndElement ();
\r
148 if(xmlReader != null) xmlReader.Close();
\r
156 public SoapTypeMapper Mapper {
\r
157 get { return mapper; }
\r
160 public XmlTextReader XmlReader {
\r
161 get { return xmlReader; }
\r
164 #region Private Methods
\r
166 private object TopObject
\r
171 objMgr.RaiseDeserializationEvent();
\r
172 return objMgr.GetObject(_topObjectId);
\r
176 private bool IsNull()
\r
178 string tmp = xmlReader["null", XmlSchema.InstanceNamespace];
\r
179 return (tmp == null || tmp == string.Empty)?false:true;
\r
182 private long GetId()
\r
186 string strId = xmlReader["id"];
\r
187 if(strId == null || strId == String.Empty) return 0;
\r
188 id = Convert.ToInt64(strId.Substring(4));
\r
192 private long GetHref()
\r
196 string strHref = xmlReader["href"];
\r
197 if(strHref == null || strHref == string.Empty) return 0;
\r
198 href = Convert.ToInt64(strHref.Substring(5));
\r
202 private Type GetComponentType()
\r
204 string strValue = xmlReader["type", XmlSchema.InstanceNamespace];
\r
205 if(strValue == null) {
\r
206 if(GetId() != 0) return typeof(string);
\r
209 return GetTypeFromQName (strValue);
\r
212 private bool DeserializeMessage(ISoapMessage message)
\r
214 string typeNamespace, assemblyName;
\r
216 if(xmlReader.Name == SoapTypeMapper.SoapEnvelopePrefix + ":Fault")
\r
222 SoapServices.DecodeXmlNamespaceForClrTypeNamespace(
\r
223 xmlReader.NamespaceURI,
\r
226 message.MethodName = xmlReader.LocalName;
\r
227 message.XmlNameSpace = xmlReader.NamespaceURI;
\r
229 ArrayList paramNames = new ArrayList();
\r
230 ArrayList paramValues = new ArrayList();
\r
231 long paramValuesId = NextAvailableId;
\r
232 int[] indices = new int[1];
\r
234 if (!xmlReader.IsEmptyElement)
\r
236 int initialDepth = xmlReader.Depth;
\r
239 while(xmlReader.Depth > initialDepth)
\r
241 long paramId, paramHref;
\r
242 object objParam = null;
\r
243 paramNames.Add (xmlReader.Name);
\r
244 Type paramType = null;
\r
246 if (message.ParamTypes != null) {
\r
247 if (i >= message.ParamTypes.Length)
\r
248 throw new SerializationException ("Not enough parameter types in SoapMessages");
\r
249 paramType = message.ParamTypes [i];
\r
253 objParam = DeserializeComponent(
\r
260 indices[0] = paramValues.Add(objParam);
\r
261 if(paramHref != 0)
\r
263 RecordFixup(paramValuesId, paramHref, paramValues.ToArray(), null, null, null, indices);
\r
265 else if(paramId != 0)
\r
267 // RegisterObject(paramId, objParam, null, paramValuesId, null, indices);
\r
274 xmlReader.ReadEndElement();
\r
281 message.ParamNames = (string[]) paramNames.ToArray(typeof(string));
\r
282 message.ParamValues = paramValues.ToArray();
\r
283 RegisterObject(paramValuesId, message.ParamValues, null, 0, null, null);
\r
287 void DeserializeHeaders (ArrayList headers)
\r
289 xmlReader.ReadStartElement ();
\r
290 xmlReader.MoveToContent ();
\r
292 while (xmlReader.NodeType != XmlNodeType.EndElement)
\r
294 if (xmlReader.NodeType != XmlNodeType.Element) { xmlReader.Skip(); continue; }
\r
296 if (xmlReader.GetAttribute ("root", SoapTypeMapper.SoapEncodingNamespace) == "1")
\r
297 headers.Add (DeserializeHeader ());
\r
301 xmlReader.MoveToContent ();
\r
304 xmlReader.ReadEndElement ();
\r
307 Header DeserializeHeader ()
\r
309 Header h = new Header (xmlReader.LocalName, null);
\r
310 h.HeaderNamespace = xmlReader.NamespaceURI;
\r
311 h.MustUnderstand = xmlReader.GetAttribute ("mustUnderstand", SoapTypeMapper.SoapEnvelopeNamespace) == "1";
\r
314 long fieldId, fieldHref;
\r
315 long idHeader = NextAvailableId;
\r
316 FieldInfo fieldInfo = typeof(Header).GetField ("Value");
\r
318 value = DeserializeComponent (null, out fieldId, out fieldHref, idHeader, fieldInfo, null);
\r
321 if(fieldHref != 0 && value == null)
\r
323 RecordFixup (idHeader, fieldHref, h, null, null, fieldInfo, null);
\r
325 else if(value != null && value.GetType().IsValueType && fieldId != 0)
\r
327 RecordFixup (idHeader, fieldId, h, null, null, fieldInfo, null);
\r
329 else if(fieldId != 0)
\r
331 RegisterObject (fieldId, value, null, idHeader, fieldInfo, null);
\r
334 RegisterObject (idHeader, h, null, 0, null, null);
\r
339 private object DeserializeArray(long id)
\r
341 // Special case for base64 byte arrays
\r
342 if (GetComponentType () == typeof(byte[])) {
\r
343 byte[] data = Convert.FromBase64String (xmlReader.ReadElementString());
\r
344 RegisterObject(id, data, null, 0, null, null);
\r
348 // Get the array properties
\r
349 string strArrayType = xmlReader["arrayType", SoapTypeMapper.SoapEncodingNamespace];
\r
350 string[] arrayInfo = strArrayType.Split(':');
\r
351 int arraySuffixInfo = arrayInfo[1].LastIndexOf('[');
\r
352 String arrayElementType = arrayInfo[1].Substring(0, arraySuffixInfo);
\r
353 String arraySuffix = arrayInfo[1].Substring(arraySuffixInfo);
\r
354 string[] arrayDims = arraySuffix.Substring(1,arraySuffix.Length-2).Trim().Split(',');
\r
355 int numberOfDims = arrayDims.Length;
\r
356 int[] lengths = new int[numberOfDims];
\r
358 for (int i=0; i < numberOfDims; i++)
\r
360 lengths[i] = Convert.ToInt32(arrayDims[i]);
\r
363 int[] indices = new int[numberOfDims];
\r
365 // Create the array
\r
366 Type arrayType = mapper.GetType (arrayElementType, xmlReader.LookupNamespace(arrayInfo[0]));
\r
367 Array array = Array.CreateInstance(
\r
371 for(int i = 0; i < numberOfDims; i++)
\r
373 indices[i] = array.GetLowerBound(i);
\r
376 // Deserialize the array items
\r
377 int arrayDepth = xmlReader.Depth;
\r
379 while(xmlReader.Depth > arrayDepth)
\r
381 Type itemType = GetComponentType();
\r
382 if(itemType == null)
\r
383 itemType = array.GetType().GetElementType();
\r
384 long itemId, itemHref;
\r
386 object objItem = DeserializeComponent(itemType,
\r
394 object obj = objMgr.GetObject(itemHref);
\r
396 array.SetValue(obj, indices);
\r
398 RecordFixup(id, itemHref, array, null, null, null, indices);
\r
400 else if(objItem != null && objItem.GetType().IsValueType && itemId != 0)
\r
402 RecordFixup(id, itemId, array, null, null, null, indices);
\r
404 else if(itemId != 0)
\r
406 RegisterObject(itemId, objItem, null, id, null, indices);
\r
407 array.SetValue(objItem, indices);
\r
411 array.SetValue(objItem, indices);
\r
414 // Get the next indice
\r
415 for(int dim = array.Rank - 1; dim >= 0; dim--)
\r
418 if(indices[dim] > array.GetUpperBound(dim))
\r
422 indices[dim] = array.GetLowerBound(dim);
\r
431 RegisterObject(id, array, null, 0, null, null);
\r
432 xmlReader.ReadEndElement();
\r
438 private object Deserialize()
\r
440 object objReturn = null;
\r
441 Type type = mapper.GetType (xmlReader.LocalName, xmlReader.NamespaceURI);
\r
445 id = (id == 0)?1:id;
\r
447 if(type == typeof(Array))
\r
449 objReturn = DeserializeArray(id);
\r
453 objReturn = DeserializeObject(type, id, 0, null, null);
\r
461 private object DeserializeObject(
\r
465 MemberInfo parentMemberInfo,
\r
468 SerializationInfo info = null;
\r
469 bool NeedsSerializationInfo = false;
\r
472 // in case of String & TimeSpan we should allways use 'ReadInternalSoapValue' method
\r
473 // in case of other internal types, we should use ReadInternalSoapValue' only if it is NOT
\r
474 // the root object, means it is a data member of another object that is being serialized.
\r
475 bool shouldReadInternal = (type == typeof(String) || type == typeof(TimeSpan) );
\r
476 if(shouldReadInternal || mapper.IsInternalSoapType (type) && (indices != null || parentMemberInfo != null) )
\r
478 object obj = mapper.ReadInternalSoapValue (this, type);
\r
481 RegisterObject(id, obj, info, parentId, parentMemberInfo, indices);
\r
485 object objReturn =
\r
486 FormatterServices.GetUninitializedObject(type);
\r
488 #if NET_2_0 && !TARGET_JVM
\r
489 objMgr.RaiseOnDeserializingEvent (objReturn);
\r
491 if(objReturn is ISerializable)
\r
492 NeedsSerializationInfo = true;
\r
494 if(_surrogateSelector != null && NeedsSerializationInfo == false)
\r
496 ISurrogateSelector selector;
\r
497 ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate(
\r
501 NeedsSerializationInfo |= (surrogate != null);
\r
504 if(NeedsSerializationInfo)
\r
507 DeserializeISerializableObject(objReturn, id, out info, out hasFixup);
\r
512 DeserializeSimpleObject(objReturn, id, out hasFixup);
\r
513 if(!hasFixup && objReturn is IObjectReference)
\r
514 objReturn = ((IObjectReference)objReturn).GetRealObject(_context);
\r
517 RegisterObject(id, objReturn, info, parentId, parentMemberInfo, indices);
\r
518 xmlReader.ReadEndElement();
\r
523 private object DeserializeSimpleObject(
\r
530 Type currentType = obj.GetType();
\r
531 TypeMetadata tm = GetTypeMetadata (currentType);
\r
533 object[] data = new object[tm.MemberInfos.Length];
\r
535 xmlReader.MoveToContent ();
\r
536 while (xmlReader.NodeType != XmlNodeType.EndElement)
\r
538 if (xmlReader.NodeType != XmlNodeType.Element) {
\r
543 object fieldObject;
\r
544 long fieldId, fieldHref;
\r
546 object indexob = tm.Indices [xmlReader.LocalName];
\r
547 if (indexob == null)
\r
548 throw new SerializationException ("Field \"" + xmlReader.LocalName + "\" not found in class " + currentType.FullName);
\r
550 int index = (int) indexob;
\r
551 FieldInfo fieldInfo = (tm.MemberInfos[index]) as FieldInfo;
\r
554 DeserializeComponent(fieldInfo.FieldType,
\r
561 data[index] = fieldObject;
\r
563 if(fieldHref != 0 && fieldObject == null)
\r
565 RecordFixup(id, fieldHref, obj, null, null, fieldInfo, null);
\r
569 if(fieldObject != null && fieldObject.GetType().IsValueType && fieldId != 0)
\r
571 RecordFixup(id, fieldId, obj, null, null, fieldInfo, null);
\r
578 RegisterObject(fieldId, fieldObject, null, id, fieldInfo, null);
\r
582 FormatterServices.PopulateObjectMembers (obj, tm.MemberInfos, data);
\r
587 private object DeserializeISerializableObject(
\r
590 out SerializationInfo info,
\r
594 long fieldId, fieldHref;
\r
595 info = new SerializationInfo(obj.GetType(), new FormatterConverter());
\r
598 int initialDepth = xmlReader.Depth;
\r
600 while(xmlReader.Depth > initialDepth)
\r
602 Type fieldType = GetComponentType();
\r
603 string fieldName = XmlConvert.DecodeName (xmlReader.LocalName);
\r
604 object objField = DeserializeComponent(
\r
611 if(fieldHref != 0 && objField == null)
\r
613 RecordFixup(id, fieldHref, obj, info, fieldName, null, null);
\r
617 else if(fieldId != 0 && objField.GetType().IsValueType)
\r
619 RecordFixup(id, fieldId, obj, info, fieldName, null, null);
\r
626 RegisterObject(fieldId, objField, null, id, null, null);
\r
629 info.AddValue(fieldName, objField, (fieldType != null)?fieldType:typeof(object));
\r
636 private object DeserializeComponent(
\r
637 Type componentType,
\r
638 out long componentId,
\r
639 out long componentHref,
\r
641 MemberInfo parentMemberInfo,
\r
654 Type xsiType = GetComponentType();
\r
655 if(xsiType != null) componentType = xsiType;
\r
657 if(xmlReader.HasAttributes)
\r
659 componentId = GetId();
\r
660 componentHref = GetHref();
\r
663 if(componentId != 0)
\r
666 string str = xmlReader.ReadElementString();
\r
667 objMgr.RegisterObject (str, componentId);
\r
670 if(componentHref != 0)
\r
672 // Move the cursor to the next node
\r
674 return objMgr.GetObject(componentHref);
\r
677 if(componentType == null)
\r
678 return xmlReader.ReadElementString();
\r
680 componentId = NextAvailableId;
\r
681 objReturn = DeserializeObject(
\r
690 public void RecordFixup(
\r
691 long parentObjectId,
\r
692 long childObjectId,
\r
693 object parentObject,
\r
694 SerializationInfo info,
\r
696 MemberInfo memberInfo,
\r
701 objMgr.RecordDelayedFixup(parentObjectId, fieldName, childObjectId);
\r
703 else if (parentObject is Array)
\r
705 if (indices.Length == 1)
\r
706 objMgr.RecordArrayElementFixup (parentObjectId, indices[0], childObjectId);
\r
708 objMgr.RecordArrayElementFixup (parentObjectId, (int[])indices.Clone(), childObjectId);
\r
712 objMgr.RecordFixup (parentObjectId, memberInfo, childObjectId);
\r
716 private void RegisterObject (
\r
718 object objectInstance,
\r
719 SerializationInfo info,
\r
720 long parentObjectId,
\r
721 MemberInfo parentObjectMember,
\r
724 if (parentObjectId == 0) indices = null;
\r
726 if (!objectInstance.GetType().IsValueType || parentObjectId == 0)
\r
727 objMgr.RegisterObject (objectInstance, objectId, info, 0, null, null);
\r
730 if(objMgr.GetObject(objectId) != null)
\r
731 throw new SerializationException("Object already registered");
\r
732 if (indices != null) indices = (int[])indices.Clone();
\r
733 objMgr.RegisterObject (
\r
738 parentObjectMember,
\r
743 TypeMetadata GetTypeMetadata (Type type)
\r
745 TypeMetadata tm = _fieldIndices[type] as TypeMetadata;
\r
746 if (tm != null) return tm;
\r
748 tm = new TypeMetadata ();
\r
749 tm.MemberInfos = FormatterServices.GetSerializableMembers (type, _context);
\r
751 tm.Indices = new Hashtable();
\r
752 for(int i = 0; i < tm.MemberInfos.Length; i++) {
\r
753 SoapFieldAttribute at = (SoapFieldAttribute) InternalRemotingServices.GetCachedSoapAttribute (tm.MemberInfos[i]);
\r
754 tm.Indices [XmlConvert.EncodeLocalName (at.XmlElementName)] = i;
\r
757 _fieldIndices[type] = tm;
\r
761 public Type GetTypeFromQName (string qname)
\r
763 string[] strName = qname.Split(':');
\r
764 string namespaceURI = xmlReader.LookupNamespace (strName[0]);
\r
765 return mapper.GetType (strName[1], namespaceURI);
\r