New test.
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / XmlSerializationWriter.cs
1 //
2 // System.Xml.Serialization.XmlSerializationWriter.cs
3 //
4 // Author:
5 //   Tim Coleman (tim@timcoleman.com)
6 //   Lluis Sanchez Gual (lluis@ximian.com)
7 //
8 // Copyright (C) Tim Coleman, 2002
9 //
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System;
33 using System.Collections;
34 using System.Globalization;
35 using System.Text;
36 using System.Xml;
37 using System.Xml.Schema;
38 using System.Runtime.Serialization;
39 using System.Reflection;
40
41 namespace System.Xml.Serialization 
42 {
43         public abstract class XmlSerializationWriter 
44 #if NET_2_0
45                 : XmlSerializationGeneratedCode
46 #endif
47         {
48
49                 #region Fields
50
51                 ObjectIDGenerator idGenerator;
52                 int qnameCount;
53                 bool topLevelElement = false;
54
55                 ArrayList namespaces;
56                 XmlWriter writer;
57                 Queue referencedElements;
58                 Hashtable callbacks;
59                 Hashtable serializedObjects;
60                 const string xmlNamespace = "http://www.w3.org/2000/xmlns/";
61                 const string unexpectedTypeError = "The type {0} was not expected. Use the" +
62                         " XmlInclude or SoapInclude attribute to specify types that are not known statically.";
63
64                 #endregion // Fields
65
66                 #region Constructors
67
68                 protected XmlSerializationWriter ()
69                 {
70                         qnameCount = 0;
71                         serializedObjects = new Hashtable ();
72                 }
73                 
74                 internal void Initialize (XmlWriter writer, XmlSerializerNamespaces nss)
75                 {
76                         this.writer = writer;
77                         if (nss != null)
78                         {
79                                 namespaces = new ArrayList ();
80                                 foreach (XmlQualifiedName ns in nss.ToArray())
81                                         if (ns.Name != "" && ns.Namespace != "")
82                                                 namespaces.Add (ns);
83                         }       
84                 }
85
86                 #endregion // Constructors
87
88                 #region Properties
89
90                 protected ArrayList Namespaces {
91                         get { return namespaces; }
92                         set { namespaces = value; }
93                 }
94
95                 protected XmlWriter Writer {
96                         get { return writer; }
97                         set { writer = value; }
98                 }
99
100                 #endregion // Properties
101
102                 #region Methods
103                 
104                 protected void AddWriteCallback (Type type, string typeName, string typeNs, XmlSerializationWriteCallback callback)
105                 {
106                         WriteCallbackInfo info = new WriteCallbackInfo ();
107                         info.Type = type;
108                         info.TypeName = typeName;
109                         info.TypeNs = typeNs;
110                         info.Callback = callback;
111
112                         if (callbacks == null) callbacks = new Hashtable ();
113                         callbacks.Add (type, info);
114                 }
115                 
116                 protected Exception CreateChoiceIdentifierValueException (string value, string identifier, string name, string ns)
117                 {
118                         string message = string.Format ("Value '{0}' of the choice"
119                                 + " identifier '{1}' does not match element '{2}'"
120                                 + " from namespace '{3}'.", value, identifier,
121                                 name, ns);
122                         return new InvalidOperationException (message);
123                 }
124
125                 protected Exception CreateInvalidChoiceIdentifierValueException (string type, string identifier)
126                 {
127                         string message = string.Format ("Invalid or missing choice"
128                                 + " identifier '{0}' of type '{1}'.", identifier,
129                                 type);
130                         return new InvalidOperationException (message);
131                 }
132
133                 protected Exception CreateMismatchChoiceException (string value, string elementName, string enumValue)
134                 {
135                         string message = String.Format ("Value of {0} mismatches the type of {1}, you need to set it to {2}.", elementName, value, enumValue);
136                         return new InvalidOperationException (message);
137                 }
138
139                 protected Exception CreateUnknownAnyElementException (string name, string ns)
140                 {
141                         string message = String.Format ("The XML element named '{0}' from namespace '{1}' was not expected. The XML element name and namespace must match those provided via XmlAnyElementAttribute(s).", name, ns);
142                         return new InvalidOperationException (message);
143                 }
144
145                 protected Exception CreateUnknownTypeException (object o)
146                 {
147                         return CreateUnknownTypeException (o.GetType ());
148                 }
149
150                 protected Exception CreateUnknownTypeException (Type type)
151                 {
152                         string message = String.Format ("The type {0} may not be used in this context.", type);
153                         return new InvalidOperationException (message);
154                 }
155
156                 protected static byte[] FromByteArrayBase64 (byte[] value)
157                 {
158                         return value;
159                 }
160
161                 protected static string FromByteArrayHex (byte[] value)
162                 {
163                         return XmlCustomFormatter.FromByteArrayHex (value);
164                 }
165
166                 protected static string FromChar (char value)
167                 {
168                         return XmlCustomFormatter.FromChar (value);
169                 }
170
171                 protected static string FromDate (DateTime value)
172                 {
173                         return XmlCustomFormatter.FromDate (value);
174                 }
175
176                 protected static string FromDateTime (DateTime value)
177                 {
178                         return XmlCustomFormatter.FromDateTime (value);
179                 }
180
181                 protected static string FromEnum (long value, string[] values, long[] ids)
182                 {
183                         return XmlCustomFormatter.FromEnum (value, values, ids);
184                 }
185
186                 protected static string FromTime (DateTime value)
187                 {
188                         return XmlCustomFormatter.FromTime (value);
189                 }
190
191                 protected static string FromXmlName (string name)
192                 {
193                         return XmlCustomFormatter.FromXmlName (name);
194                 }
195
196                 protected static string FromXmlNCName (string ncName)
197                 {
198                         return XmlCustomFormatter.FromXmlNCName (ncName);
199                 }
200
201                 protected static string FromXmlNmToken (string nmToken)
202                 {
203                         return XmlCustomFormatter.FromXmlNmToken (nmToken);
204                 }
205
206                 protected static string FromXmlNmTokens (string nmTokens)
207                 {
208                         return XmlCustomFormatter.FromXmlNmTokens (nmTokens);
209                 }
210
211                 protected string FromXmlQualifiedName (XmlQualifiedName xmlQualifiedName)
212                 {
213                         if (xmlQualifiedName == null || xmlQualifiedName == XmlQualifiedName.Empty)
214                                 return null;
215                                 
216                         return GetQualifiedName (xmlQualifiedName.Name, xmlQualifiedName.Namespace);
217                 }
218
219                 private string GetId (object o, bool addToReferencesList)
220                 {
221                         if (idGenerator == null) idGenerator = new ObjectIDGenerator ();
222
223                         bool firstTime;
224                         long lid = idGenerator.GetId (o, out firstTime);
225                         return String.Format (CultureInfo.InvariantCulture, "id{0}", lid);
226                 }
227
228                 
229                 bool AlreadyQueued (object ob)
230                 {
231                         if (idGenerator == null) return false;
232
233                         bool firstTime;
234                         idGenerator.HasId (ob, out firstTime);
235                         return !firstTime;
236                 }
237
238                 private string GetNamespacePrefix (string ns)
239                 {
240                         string prefix = Writer.LookupPrefix (ns);
241                         if (prefix == null) 
242                         {
243                                 prefix = String.Format (CultureInfo.InvariantCulture, "q{0}", ++qnameCount);
244                                 WriteAttribute ("xmlns", prefix, null, ns);
245                         }
246                         return prefix;
247                 }
248
249                 private string GetQualifiedName (string name, string ns)
250                 {
251                         if (ns == String.Empty) return name;
252                         
253                         string prefix = GetNamespacePrefix (ns);
254                         if (prefix == String.Empty)
255                                 return name;
256                         else
257                                 return String.Format ("{0}:{1}", prefix, name);
258                 }
259
260                 protected abstract void InitCallbacks ();
261
262                 protected void TopLevelElement ()
263                 {
264                         topLevelElement = true;
265                 }
266
267                 protected void WriteAttribute (string localName, byte[] value)
268                 {
269                         WriteAttribute (localName, String.Empty, value);
270                 }
271
272                 protected void WriteAttribute (string localName, string value)
273                 {
274                         WriteAttribute (String.Empty, localName, String.Empty, value);
275                 }
276
277                 protected void WriteAttribute (string localName, string ns, byte[] value)
278                 {
279                         if (value == null)
280                                 return;
281
282                         Writer.WriteStartAttribute (localName, ns);
283                         WriteValue (value);
284                         Writer.WriteEndAttribute ();
285                 }
286
287                 protected void WriteAttribute (string localName, string ns, string value)
288                 {
289                         WriteAttribute (null, localName, ns, value);
290                 }
291
292                 protected void WriteAttribute (string prefix, string localName, string ns, string value)
293                 {
294                         if (value == null)
295                                 return;
296
297                         Writer.WriteAttributeString (prefix, localName, ns, value);
298                 }
299
300                 protected void WriteElementEncoded (XmlNode node, string name, string ns, bool isNullable, bool any)
301                 {
302                         if (name != string.Empty)
303                         {
304                                 if (node == null)
305                                 {
306                                         if (isNullable)
307                                                 WriteNullTagEncoded (name, ns);
308                                 }
309                                 else
310                                 {
311                                         Writer.WriteStartElement (name, ns);
312                                         node.WriteTo (Writer);
313                                         Writer.WriteEndElement ();
314                                 }
315                         }
316                         else
317                                 node.WriteTo (Writer);
318                 }
319
320                 protected void WriteElementLiteral (XmlNode node, string name, string ns, bool isNullable, bool any)
321                 {
322                         if (name != string.Empty)
323                         {
324                                 if (node == null)
325                                 {
326                                         if (isNullable)
327                                                 WriteNullTagLiteral (name, ns);
328                                 }
329                                 else
330                                 {
331                                         Writer.WriteStartElement (name, ns);
332                                         node.WriteTo (Writer);
333                                         Writer.WriteEndElement ();
334                                 }
335                         }
336                         else
337                                 node.WriteTo (Writer);
338                 }
339
340                 protected void WriteElementQualifiedName (string localName, XmlQualifiedName value)
341                 {
342                         WriteElementQualifiedName (localName, String.Empty, value, null);
343                 }
344
345                 protected void WriteElementQualifiedName (string localName, string ns, XmlQualifiedName value)
346                 {
347                         WriteElementQualifiedName (localName, ns, value, null);
348                 }
349
350                 protected void WriteElementQualifiedName (string localName, XmlQualifiedName value, XmlQualifiedName xsiType)
351                 {
352                         WriteElementQualifiedName (localName, String.Empty, value, xsiType);
353                 }
354
355                 protected void WriteElementQualifiedName (string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType)
356                 {
357                         localName = XmlCustomFormatter.FromXmlNCName (localName);
358                         WriteStartElement (localName, ns);
359                         if (xsiType != null) WriteXsiType (xsiType.Name, xsiType.Namespace);
360                         Writer.WriteString (FromXmlQualifiedName (value));
361                         WriteEndElement ();
362                 }
363
364                 protected void WriteElementString (string localName, string value)
365                 {
366                         WriteElementString (localName, String.Empty, value, null);
367                 }
368
369                 protected void WriteElementString (string localName, string ns, string value)
370                 {
371                         WriteElementString (localName, ns, value, null);
372                 }
373
374                 protected void WriteElementString (string localName, string value, XmlQualifiedName xsiType)
375                 {
376                         WriteElementString (localName, String.Empty, value, xsiType);
377                 }
378
379                 protected void WriteElementString (string localName, string ns, string value, XmlQualifiedName xsiType)
380                 {
381                         if (value == null) return;
382
383                         if (xsiType != null) {
384                                 localName = XmlCustomFormatter.FromXmlNCName (localName);
385                                 WriteStartElement (localName, ns);
386                                 WriteXsiType (xsiType.Name, xsiType.Namespace);
387                                 Writer.WriteString (value);
388                                 WriteEndElement ();
389                         } 
390                         else
391                                 Writer.WriteElementString (localName, ns, value);
392                 }
393
394                 protected void WriteElementStringRaw (string localName, byte[] value)
395                 {
396                         WriteElementStringRaw (localName, String.Empty, value, null);
397                 }
398
399                 protected void WriteElementStringRaw (string localName, string value)
400                 {
401                         WriteElementStringRaw (localName, String.Empty, value, null);
402                 }
403
404                 protected void WriteElementStringRaw (string localName, byte[] value, XmlQualifiedName xsiType)
405                 {
406                         WriteElementStringRaw (localName, String.Empty, value, xsiType);
407                 }
408
409                 protected void WriteElementStringRaw (string localName, string ns, byte[] value)
410                 {
411                         WriteElementStringRaw (localName, ns, value, null);
412                 }
413
414                 protected void WriteElementStringRaw (string localName, string ns, string value)
415                 {
416                         WriteElementStringRaw (localName, ns, value, null);
417                 }
418
419                 protected void WriteElementStringRaw (string localName, string value, XmlQualifiedName xsiType)
420                 {
421                         WriteElementStringRaw (localName, String.Empty, value, null);
422                 }
423
424                 protected void WriteElementStringRaw (string localName, string ns, byte[] value, XmlQualifiedName xsiType)
425                 {
426                         if (value == null)
427                                 return;
428
429                         WriteStartElement (localName, ns);
430
431                         if (xsiType != null)
432                                 WriteXsiType (xsiType.Name, xsiType.Namespace);
433
434                         if (value.Length > 0) 
435                                 Writer.WriteBase64(value,0,value.Length);
436                         WriteEndElement ();
437                 }
438
439                 protected void WriteElementStringRaw (string localName, string ns, string value, XmlQualifiedName xsiType)
440                 {
441                         localName = XmlCustomFormatter.FromXmlNCName (localName);
442                         WriteStartElement (localName, ns);
443
444                         if (xsiType != null)
445                                 WriteXsiType (xsiType.Name, xsiType.Namespace);
446
447                         Writer.WriteRaw (value);
448                         WriteEndElement ();
449                 }
450
451                 protected void WriteEmptyTag (string name)
452                 {
453                         WriteEmptyTag (name, String.Empty);
454                 }
455
456                 protected void WriteEmptyTag (string name, string ns)
457                 {
458                         name = XmlCustomFormatter.FromXmlName (name);
459                         WriteStartElement (name, ns);
460                         WriteEndElement ();
461                 }
462
463                 protected void WriteEndElement ()
464                 {
465                         WriteEndElement (null);
466                 }
467
468                 protected void WriteEndElement (object o)
469                 {
470                         if (o != null)
471                                 serializedObjects.Remove (o);
472                                 
473                         Writer.WriteEndElement ();
474                 }
475
476                 protected void WriteId (object o)
477                 {
478                         WriteAttribute ("id", GetId (o, true));
479                 }
480
481                 protected void WriteNamespaceDeclarations (XmlSerializerNamespaces ns)
482                 {
483                         if (ns == null)
484                                 return;
485
486                         ICollection namespaces = ns.Namespaces.Values;
487                         foreach (XmlQualifiedName qn in namespaces) {
488                                 if (qn.Namespace != String.Empty && Writer.LookupPrefix (qn.Namespace) != qn.Name)
489                                         WriteAttribute ("xmlns", qn.Name, xmlNamespace, qn.Namespace);
490                         }
491                 }
492
493                 protected void WriteNullableQualifiedNameEncoded (string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType)
494                 {
495                         if (value != null)
496                                 WriteElementQualifiedName (name, ns, value, xsiType);
497                         else
498                                 WriteNullTagEncoded (name, ns);
499                 }
500
501                 protected void WriteNullableQualifiedNameLiteral (string name, string ns, XmlQualifiedName value)
502                 {
503                         if (value != null)
504                                 WriteElementQualifiedName (name, ns, value);
505                         else
506                                 WriteNullTagLiteral (name, ns);
507                 }
508
509                 protected void WriteNullableStringEncoded (string name, string ns, string value, XmlQualifiedName xsiType)
510                 {
511                         if (value != null)
512                                 WriteElementString (name, ns, value, xsiType);
513                         else
514                                 WriteNullTagEncoded (name, ns);
515                 }
516
517                 protected void WriteNullableStringEncodedRaw (string name, string ns, byte[] value, XmlQualifiedName xsiType)
518                 {
519                         if (value == null)
520                                 WriteNullTagEncoded (name, ns);
521                         else
522                                 WriteElementStringRaw (name, ns, value, xsiType);
523                 }
524
525                 protected void WriteNullableStringEncodedRaw (string name, string ns, string value, XmlQualifiedName xsiType)
526                 {
527                         if (value == null)
528                                 WriteNullTagEncoded (name, ns);
529                         else
530                                 WriteElementStringRaw (name, ns, value, xsiType);
531                 }
532
533                 protected void WriteNullableStringLiteral (string name, string ns, string value)
534                 {
535                         if (value != null)
536                                 WriteElementString (name, ns, value, null);
537                         else
538                                 WriteNullTagLiteral (name, ns);
539                 }
540
541                 protected void WriteNullableStringLiteralRaw (string name, string ns, byte[] value)
542                 {
543                         if (value == null)
544                                 WriteNullTagLiteral (name, ns);
545                         else
546                                 WriteElementStringRaw (name, ns, value);
547                 }
548
549                 protected void WriteNullableStringLiteralRaw (string name, string ns, string value)
550                 {
551                         if (value == null)
552                                 WriteNullTagLiteral (name, ns);
553                         else
554                                 WriteElementStringRaw (name, ns, value);
555                 }
556
557                 protected void WriteNullTagEncoded (string name)
558                 {
559                         WriteNullTagEncoded (name, String.Empty);
560                 }
561
562                 protected void WriteNullTagEncoded (string name, string ns)
563                 {
564                         Writer.WriteStartElement (name, ns);
565 #if NET_1_1
566                         Writer.WriteAttributeString ("nil", XmlSchema.InstanceNamespace, "true");
567 #else
568                         Writer.WriteAttributeString ("null", XmlSchema.InstanceNamespace, "1");
569 #endif
570                         Writer.WriteEndElement ();
571                 }
572
573                 protected void WriteNullTagLiteral (string name)
574                 {
575                         WriteNullTagLiteral (name, String.Empty);
576                 }
577
578                 protected void WriteNullTagLiteral (string name, string ns)
579                 {
580                         WriteStartElement (name, ns);
581                         Writer.WriteAttributeString ("nil", XmlSchema.InstanceNamespace, "true");
582                         WriteEndElement ();
583                 }
584
585                 protected void WritePotentiallyReferencingElement (string n, string ns, object o)
586                 {
587                         WritePotentiallyReferencingElement (n, ns, o, null, false, false);
588                 }
589
590                 protected void WritePotentiallyReferencingElement (string n, string ns, object o, Type ambientType)
591                 {
592                         WritePotentiallyReferencingElement (n, ns, o, ambientType, false, false);
593                 }
594
595                 protected void WritePotentiallyReferencingElement (string n, string ns, object o, Type ambientType, bool suppressReference)
596                 {
597                         WritePotentiallyReferencingElement (n, ns, o, ambientType, suppressReference, false);
598                 }
599
600                 protected void WritePotentiallyReferencingElement (string n, string ns, object o, Type ambientType, bool suppressReference, bool isNullable)
601                 {
602                         if (o == null) 
603                         {
604                                 if (isNullable) WriteNullTagEncoded (n, ns);
605                                 return;
606                         }
607
608                         WriteStartElement (n, ns, true);
609
610                         CheckReferenceQueue ();
611
612                         if (callbacks.ContainsKey (o.GetType ()))
613                         {
614                                 WriteCallbackInfo info = (WriteCallbackInfo) callbacks[o.GetType()];
615                                 if (o.GetType ().IsEnum) {
616                                         info.Callback (o);
617                                 }
618                                 else if (suppressReference) {
619                                         Writer.WriteAttributeString ("id", GetId (o, false));
620                                         if (ambientType != o.GetType ()) WriteXsiType(info.TypeName, info.TypeNs);
621                                         info.Callback (o);
622                                 }
623                                 else {
624                                         if (!AlreadyQueued (o)) referencedElements.Enqueue (o);
625                                         Writer.WriteAttributeString ("href", "#" + GetId (o, true));
626                                 }
627                         }
628                         else
629                         {
630                                 // Must be a primitive type or array of primitives
631                                 TypeData td = TypeTranslator.GetTypeData (o.GetType ());
632                                 if (td.SchemaType == SchemaTypes.Primitive) {
633                                         WriteXsiType (td.XmlType, XmlSchema.Namespace);
634                                         Writer.WriteString (XmlCustomFormatter.ToXmlString (td, o));
635                                 } else if (IsPrimitiveArray (td)) {
636                                         if (!AlreadyQueued (o)) referencedElements.Enqueue (o);
637                                         Writer.WriteAttributeString ("href", "#" + GetId (o, true));
638                                 } else
639                                         throw new InvalidOperationException ("Invalid type: " + o.GetType().FullName);
640                         }
641
642                         WriteEndElement ();
643                 }
644
645                 protected void WriteReferencedElements ()
646                 {
647                         if (referencedElements == null) return;
648                         if (callbacks == null) return;
649
650                         while (referencedElements.Count > 0)
651                         {
652                                 object o = referencedElements.Dequeue ();
653                                 TypeData td = TypeTranslator.GetTypeData (o.GetType ());
654                                 WriteCallbackInfo info = (WriteCallbackInfo) callbacks[o.GetType()];
655                                 
656                                 if (info != null) {
657                                         WriteStartElement (info.TypeName, info.TypeNs, true);
658                                         Writer.WriteAttributeString ("id", GetId (o, false));
659
660                                         if (td.SchemaType != SchemaTypes.Array) // Array use its own "arrayType" attribute
661                                                 WriteXsiType(info.TypeName, info.TypeNs);
662
663                                         info.Callback (o);
664                                         WriteEndElement ();
665                                 } else if (IsPrimitiveArray (td)) {
666                                         WriteArray (o, td);
667                                 }
668                         }
669                 }
670                 
671                 bool IsPrimitiveArray (TypeData td)
672                 {
673                         if (td.SchemaType == SchemaTypes.Array) {
674                                 if (td.ListItemTypeData.SchemaType == SchemaTypes.Primitive || td.ListItemType == typeof(object))
675                                         return true;
676                                 return IsPrimitiveArray (td.ListItemTypeData);
677                         } else
678                                 return false;
679                 }
680
681                 void WriteArray (object o, TypeData td)
682                 {
683                         TypeData itemTypeData = td;
684                         string xmlType;
685                         int nDims = -1;
686
687                         do {
688                                 itemTypeData = itemTypeData.ListItemTypeData;
689                                 xmlType = itemTypeData.XmlType;
690                                 nDims++;
691                         }
692                         while (itemTypeData.SchemaType == SchemaTypes.Array );
693
694                         while (nDims-- > 0)
695                                 xmlType += "[]";
696
697                         WriteStartElement("Array", XmlSerializer.EncodingNamespace, true);
698                         Writer.WriteAttributeString("id", GetId(o, false));
699                         if (td.SchemaType == SchemaTypes.Array) {
700                                 Array a = (Array)o;
701                                 int len = a.Length;
702                                 Writer.WriteAttributeString("arrayType", XmlSerializer.EncodingNamespace, GetQualifiedName(xmlType, XmlSchema.Namespace) + "[" + len.ToString() + "]");
703                                 for (int i = 0; i < len; i++) {
704                                         WritePotentiallyReferencingElement("Item", "", a.GetValue(i), td.ListItemType, false, true);
705                                 }
706                         }
707                         WriteEndElement();
708                 }
709
710
711                 protected void WriteReferencingElement (string n, string ns, object o)
712                 {
713                         WriteReferencingElement (n, ns, o, false);
714                 }
715
716                 protected void WriteReferencingElement (string n, string ns, object o, bool isNullable)
717                 {
718                         if (o == null) 
719                         {
720                                 if (isNullable) WriteNullTagEncoded (n, ns);
721                                 return;
722                         }
723                         else
724                         {
725                                 CheckReferenceQueue ();
726                                 if (!AlreadyQueued (o)) referencedElements.Enqueue (o);
727
728                                 Writer.WriteStartElement (n, ns);
729                                 Writer.WriteAttributeString ("href", "#" + GetId (o, true));
730                                 Writer.WriteEndElement ();
731                         }
732                 }
733
734                 void CheckReferenceQueue ()
735                 {
736                         if (referencedElements == null)  
737                         {
738                                 referencedElements = new Queue ();
739                                 InitCallbacks ();
740                         }
741                 }
742
743                 [MonoTODO]
744                 protected void WriteRpcResult (string name, string ns)
745                 {
746                         throw new NotImplementedException ();
747                 }
748
749                 protected void WriteSerializable (IXmlSerializable serializable, string name, string ns, bool isNullable)
750                 {
751                         if (serializable == null)
752                         {
753                                 if (isNullable) WriteNullTagLiteral (name, ns);
754                                 return;
755                         }
756                         else
757                         {
758                                 Writer.WriteStartElement (name, ns);
759                                 serializable.WriteXml (Writer);
760                                 Writer.WriteEndElement ();
761                         }
762                 }
763
764                 protected void WriteStartDocument ()
765                 {
766                         if (Writer.WriteState == WriteState.Start)
767                                 Writer.WriteStartDocument ();
768                 }
769
770                 protected void WriteStartElement (string name)
771                 {
772                         WriteStartElement (name, String.Empty, null, false);
773                 }
774
775                 protected void WriteStartElement (string name, string ns)
776                 {
777                         WriteStartElement (name, ns, null, false);
778                 }
779
780                 protected void WriteStartElement (string name, string ns, bool writePrefixed)
781                 {
782                         WriteStartElement (name, ns, null, writePrefixed);
783                 }
784
785                 protected void WriteStartElement (string name, string ns, object o)
786                 {
787                         WriteStartElement (name, ns, o, false);
788                 }
789
790                 protected void WriteStartElement (string name, string ns, object o, bool writePrefixed)
791                 {
792                         if (o != null)
793                         {
794                                 if (serializedObjects.Contains (o))
795                                         throw new InvalidOperationException ("A circular reference was detected while serializing an object of type " + o.GetType().Name);
796                                 else
797                                         serializedObjects [o] = o;
798                         }
799                         
800                         string prefix = null;
801                         
802                         if (topLevelElement && ns != null && ns.Length != 0)
803                         {
804                                 foreach (XmlQualifiedName qn in namespaces)
805                                         if (qn.Namespace == ns) {
806                                                 prefix = qn.Name;
807                                                 writePrefixed = true;
808                                                 break;
809                                         }
810                         }
811
812                         if (writePrefixed && ns != string.Empty)
813                         {
814                                 name = XmlCustomFormatter.FromXmlName (name);
815                                 
816                                 if (prefix == null)
817                                         prefix = Writer.LookupPrefix (ns);
818                                 if (prefix == null || prefix.Length == 0)
819                                         prefix = "q" + (++qnameCount);
820                                 Writer.WriteStartElement (prefix, name, ns);
821                         } else
822                                 Writer.WriteStartElement (name, ns);
823
824                         if (topLevelElement) 
825                         {
826                                 if (namespaces != null) {
827                                         foreach (XmlQualifiedName qn in namespaces)
828                                         {
829                                                 string currentPrefix = Writer.LookupPrefix (qn.Namespace);
830                                                 if (currentPrefix != null && currentPrefix.Length != 0) continue;
831                                                 
832                                                 WriteAttribute ("xmlns",qn.Name,xmlNamespace,qn.Namespace);
833                                         }
834                                 }
835                                 topLevelElement = false;
836                         }
837                 }
838
839                 protected void WriteTypedPrimitive (string name, string ns, object o, bool xsiType)
840                 {
841                         string value;
842                         TypeData td = TypeTranslator.GetTypeData (o.GetType ());
843
844                         name = XmlCustomFormatter.FromXmlName (name);
845                         Writer.WriteStartElement (name, ns);
846
847                         if (o is XmlNode[]) {
848                                 foreach (XmlNode node in (XmlNode[])o)
849                                         node.WriteTo (Writer);
850                         }
851                         else {
852                                 if (o is XmlQualifiedName)
853                                         value = FromXmlQualifiedName ((XmlQualifiedName) o);
854                                 else
855                                         value = XmlCustomFormatter.ToXmlString (td, o);
856
857                                 if (xsiType)
858                                 {
859                                         if (td.SchemaType != SchemaTypes.Primitive)
860                                                 throw new InvalidOperationException (string.Format (unexpectedTypeError, o.GetType().FullName));
861                                         WriteXsiType (td.XmlType, XmlSchema.Namespace);
862                                 }
863
864                                 WriteValue (value);
865                         }
866                         Writer.WriteEndElement ();
867                 }
868
869                 protected void WriteValue (byte[] value)
870                 {
871                         Writer.WriteBase64 (value, 0, value.Length);
872                 }
873
874                 protected void WriteValue (string value)
875                 {
876                         if (value != null)
877                                 Writer.WriteString (value);
878                 }
879
880                 protected void WriteXmlAttribute (XmlNode node)
881                 {
882                         WriteXmlAttribute (node, null);
883                 }
884
885                 protected void WriteXmlAttribute (XmlNode node, object container)
886                 {
887                         XmlAttribute attr = node as XmlAttribute;
888                         if (attr == null)
889                                 throw new InvalidOperationException ("The node must be either type XmlAttribute or a derived type.");
890                         
891                         if (attr.NamespaceURI == XmlSerializer.WsdlNamespace)
892                         {
893                                 // The wsdl arrayType attribute needs special handling
894                                 if (attr.LocalName == "arrayType") {
895                                         string ns, type, dimensions;
896                                         TypeTranslator.ParseArrayType (attr.Value, out type, out ns, out dimensions);
897                                         string value = GetQualifiedName (type + dimensions, ns);
898                                         WriteAttribute (attr.Prefix, attr.LocalName, attr.NamespaceURI, value);
899                                         return;
900                                 }
901                         }
902                         
903                         WriteAttribute (attr.Prefix, attr.LocalName, attr.NamespaceURI, attr.Value);
904                 }
905
906                 protected void WriteXsiType (string name, string ns)
907                 {
908                         if (ns != null && ns != string.Empty)
909                                 WriteAttribute ("type", XmlSchema.InstanceNamespace, GetQualifiedName (name, ns));
910                         else
911                                 WriteAttribute ("type", XmlSchema.InstanceNamespace, name);
912                 }
913                 
914 #if NET_2_0
915
916                 [MonoTODO]
917                 protected Exception CreateInvalidAnyTypeException (object o)
918                 {
919                         throw new NotImplementedException ();
920                 }
921                 
922                 [MonoTODO]
923                 protected Exception CreateInvalidAnyTypeException (Type t)
924                 {
925                         throw new NotImplementedException ();
926                 }
927
928                 protected Exception CreateInvalidEnumValueException (object value, string typeName)
929                 {
930                         return new InvalidOperationException (string.Format(CultureInfo.CurrentCulture,
931                                 "'{0}' is not a valid value for {1}.", value, typeName));
932                 }
933
934                 protected static string FromEnum (long value, string[] values, long[] ids, string typeName)
935                 {
936                         return XmlCustomFormatter.FromEnum (value, values, ids, typeName);
937                 }
938
939                 [MonoTODO]
940                 protected string FromXmlQualifiedName (XmlQualifiedName xmlQualifiedName, bool ignoreEmpty)
941                 {
942                         throw new NotImplementedException ();
943                 }
944                 
945                 [MonoTODO]
946                 protected static Assembly ResolveDynamicAssembly (string assemblyFullName)
947                 {
948                         throw new NotImplementedException ();
949                 }
950                 
951                 [MonoTODO]
952                 protected void WriteSerializable (IXmlSerializable serializable, string name, string ns, bool isNullable, bool any)
953                 {
954                         throw new NotImplementedException ();
955                 }
956                 
957                 [MonoTODO]
958                 protected bool EscapeName
959                 {
960                         get { throw new NotImplementedException(); }
961                         set { throw new NotImplementedException(); }
962                 }
963 #endif
964
965                 #endregion
966
967                 class WriteCallbackInfo
968                 {
969                         public Type Type;
970                         public string TypeName;
971                         public string TypeNs;
972                         public XmlSerializationWriteCallback Callback;
973                 }
974         }
975 }