[Cleanup] Removed TARGET_JVM
[mono.git] / mcs / class / System.XML / System.Xml.Serialization / XmlSerializer.cs
1 //
2 // XmlSerializer.cs: 
3 //
4 // Author:
5 //   Lluis Sanchez Gual (lluis@ximian.com)
6 //
7 // (C) 2002, 2003 Ximian, Inc.  http://www.ximian.com
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Threading;
33 using System.Collections;
34 using System.Globalization;
35 using System.IO;
36 using System.Reflection;
37 using System.Xml;
38 using System.Xml.Schema;
39 using System.Text;
40 #if !NET_2_1
41 using System.CodeDom;
42 using System.CodeDom.Compiler;
43 using Microsoft.CSharp;
44 #endif
45 using System.Configuration;
46 using System.Security.Policy;
47
48 namespace System.Xml.Serialization
49 {
50
51         public class XmlSerializer
52         {
53                 internal const string WsdlNamespace = "http://schemas.xmlsoap.org/wsdl/";
54                 internal const string EncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/";
55                 internal const string WsdlTypesNamespace = "http://microsoft.com/wsdl/types/";
56                 static int generationThreshold;
57                 static bool backgroundGeneration = true;
58                 static bool deleteTempFiles = true;
59                 static bool generatorFallback = true;
60
61                 bool customSerializer;
62                 XmlMapping typeMapping;
63                 
64                 SerializerData serializerData;
65                 
66                 static Hashtable serializerTypes = new Hashtable ();
67                 
68                 internal class SerializerData
69                 {
70                         public int UsageCount;
71                         public Type ReaderType;
72                         public MethodInfo ReaderMethod;
73                         public Type WriterType;
74                         public MethodInfo WriterMethod;
75                         public GenerationBatch Batch;
76                         public XmlSerializerImplementation Implementation = null;
77                         
78                         public XmlSerializationReader CreateReader () {
79                                 if (ReaderType != null)
80                                         return (XmlSerializationReader) Activator.CreateInstance (ReaderType);
81                                 else if (Implementation != null)
82                                         return Implementation.Reader;
83                                 else
84                                         return null;
85                         }
86                         
87                         public XmlSerializationWriter CreateWriter () {
88                                 if (WriterType != null)
89                                         return (XmlSerializationWriter) Activator.CreateInstance (WriterType);
90                                 else if (Implementation != null)
91                                         return Implementation.Writer;
92                                 else
93                                         return null;
94                         }
95                 }
96                 
97                 internal class GenerationBatch
98                 {
99                         public bool Done;
100                         public XmlMapping[] Maps;
101                         public SerializerData[] Datas;
102                 }
103                 
104                 static XmlSerializer ()
105                 {
106                         // The following options are available:
107                         // MONO_XMLSERIALIZER_DEBUG: when set to something != "no", it will
108                         //       it will print the name of the generated file, and it won't
109                         //       be deleted.
110                         // MONO_XMLSERIALIZER_THS: The code generator threshold. It can be:
111                         //       no: does not use the generator, always the interpreter.
112                         //       0: always use the generator, wait until the generation is done.
113                         //       any number: use the interpreted serializer until the specified
114                         //       number of serializations is reached. At this point the generation
115                         //       of the serializer will start in the background. The interpreter
116                         //       will be used while the serializer is being generated.
117                         //
118                         //       XmlSerializer will fall back to the interpreted serializer if
119                         //       the code generation somehow fails. This can be avoided for
120                         //       debugging pourposes by adding the "nofallback" option.
121                         //       For example: MONO_XMLSERIALIZER_THS=0,nofallback
122                         
123 #if NET_2_1
124                         string db = null;
125                         string th = null;
126                         generationThreshold = -1;
127                         backgroundGeneration = false;
128 #else
129                         string db = Environment.GetEnvironmentVariable ("MONO_XMLSERIALIZER_DEBUG");
130                         string th = Environment.GetEnvironmentVariable ("MONO_XMLSERIALIZER_THS");
131                         
132                         if (th == null) {
133                                 generationThreshold = 50;
134                                 backgroundGeneration = true;
135                         } else {
136                                 int i = th.IndexOf (',');
137                                 if (i != -1) {
138                                         if (th.Substring (i+1) == "nofallback")
139                                                 generatorFallback = false;
140                                         th = th.Substring (0, i);
141                                 }
142                                 
143                                 if (th.ToLower(CultureInfo.InvariantCulture) == "no") 
144                                         generationThreshold = -1;
145                                 else {
146                                         generationThreshold = int.Parse (th, CultureInfo.InvariantCulture);
147                                         backgroundGeneration = (generationThreshold != 0);
148                                         if (generationThreshold < 1) generationThreshold = 1;
149                                 }
150                         }
151 #endif
152                         deleteTempFiles = (db == null || db == "no");
153 #if !NET_2_1
154                         IDictionary table = (IDictionary) ConfigurationSettings.GetConfig("system.diagnostics");
155                         if (table != null) 
156                         {
157                                 table = (IDictionary) table["switches"];
158                                 if (table != null) 
159                                 {
160                                         string val = (string) table ["XmlSerialization.Compilation"];
161                                         if (val == "1") deleteTempFiles = false;
162                                 }
163                         }
164 #endif
165                 }
166
167 #region Constructors
168
169                 protected XmlSerializer ()
170                 {
171                         customSerializer = true;
172                 }
173
174                 public XmlSerializer (Type type)
175                         : this (type, null, null, null, null)
176                 {
177                 }
178
179                 public XmlSerializer (XmlTypeMapping xmlTypeMapping)
180                 {
181                         typeMapping = xmlTypeMapping;
182                 }
183
184                 internal XmlSerializer (XmlMapping mapping, SerializerData data)
185                 {
186                         typeMapping = mapping;
187                         serializerData = data;
188                 }
189
190                 public XmlSerializer (Type type, string defaultNamespace)
191                         : this (type, null, null, null, defaultNamespace)
192                 {
193                 }
194
195                 public XmlSerializer (Type type, Type[] extraTypes)
196                         : this (type, null, extraTypes, null, null)
197                 {
198                 }
199
200                 public XmlSerializer (Type type, XmlAttributeOverrides overrides)
201                         : this (type, overrides, null, null, null)
202                 {
203                 }
204
205                 public XmlSerializer (Type type, XmlRootAttribute root)
206                         : this (type, null, null, root, null)
207                 {
208                 }
209
210                 public XmlSerializer (Type type,
211                         XmlAttributeOverrides overrides,
212                         Type [] extraTypes,
213                         XmlRootAttribute root,
214                         string defaultNamespace)
215                 {
216                         if (type == null)
217                                 throw new ArgumentNullException ("type");
218
219                         XmlReflectionImporter importer = new XmlReflectionImporter (overrides, defaultNamespace);
220
221                         if (extraTypes != null) 
222                         {
223                                 foreach (Type intype in extraTypes)
224                                         importer.IncludeType (intype);
225                         }
226
227                         typeMapping = importer.ImportTypeMapping (type, root, defaultNamespace);
228                 }
229                 
230                 internal XmlMapping Mapping
231                 {
232                         get { return typeMapping; }
233                 }
234
235 #if NET_2_0
236
237                 [MonoTODO]
238                 public XmlSerializer (Type type,
239                         XmlAttributeOverrides overrides,
240                         Type [] extraTypes,
241                         XmlRootAttribute root,
242                         string defaultNamespace,
243                         string location,
244                         Evidence evidence)
245                 {
246                 }
247 #endif
248
249 #endregion // Constructors
250
251 #region Events
252                 private UnreferencedObjectEventHandler onUnreferencedObject;
253                 private XmlAttributeEventHandler onUnknownAttribute;
254                 private XmlElementEventHandler onUnknownElement;
255                 private XmlNodeEventHandler onUnknownNode;
256
257                 public event XmlAttributeEventHandler UnknownAttribute 
258                 {
259                         add { onUnknownAttribute += value; } remove { onUnknownAttribute -= value; }
260                 }
261
262                 public event XmlElementEventHandler UnknownElement 
263                 {
264                         add { onUnknownElement += value; } remove { onUnknownElement -= value; }
265                 }
266
267                 public event XmlNodeEventHandler UnknownNode 
268                 {
269                         add { onUnknownNode += value; } remove { onUnknownNode -= value; }
270                 }
271
272
273                 internal virtual void OnUnknownAttribute (XmlAttributeEventArgs e) 
274                 {
275                         if (onUnknownAttribute != null) onUnknownAttribute(this, e);
276                 }
277
278                 internal virtual void OnUnknownElement (XmlElementEventArgs e) 
279                 {
280                         if (onUnknownElement != null) onUnknownElement(this, e);
281                 }
282
283                 internal virtual void OnUnknownNode (XmlNodeEventArgs e) 
284                 {
285                         if (onUnknownNode != null) onUnknownNode(this, e);
286                 }
287
288                 internal virtual void OnUnreferencedObject (UnreferencedObjectEventArgs e) 
289                 {
290                         if (onUnreferencedObject != null) onUnreferencedObject(this, e);
291                 }
292
293                 public event UnreferencedObjectEventHandler UnreferencedObject 
294                 {
295                         add { onUnreferencedObject += value; } remove { onUnreferencedObject -= value; }
296                 }
297
298 #endregion // Events
299
300 #region Methods
301
302                 public virtual bool CanDeserialize (XmlReader xmlReader)
303                 {
304                         xmlReader.MoveToContent ();
305                         if (typeMapping is XmlMembersMapping) 
306                                 return true;
307                         else
308                                 return ((XmlTypeMapping)typeMapping).ElementName == xmlReader.LocalName;
309                 }
310
311                 protected virtual XmlSerializationReader CreateReader ()
312                 {
313                         // Must be implemented in derived class
314                         throw new NotImplementedException ();
315                 }
316
317                 protected virtual XmlSerializationWriter CreateWriter ()
318                 {
319                         // Must be implemented in derived class
320                         throw new NotImplementedException ();
321                 }
322
323                 public object Deserialize (Stream stream)
324                 {
325                         XmlTextReader xmlReader = new XmlTextReader(stream);
326                         xmlReader.Normalization = true;
327                         xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
328                         return Deserialize(xmlReader);
329                 }
330
331                 public object Deserialize (TextReader textReader)
332                 {
333                         XmlTextReader xmlReader = new XmlTextReader(textReader);
334                         xmlReader.Normalization = true;
335                         xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
336                         return Deserialize(xmlReader);
337                 }
338
339                 public object Deserialize (XmlReader xmlReader)
340                 {
341                         XmlSerializationReader xsReader;
342                         if (customSerializer)
343                                 xsReader = CreateReader ();
344                         else
345                                 xsReader = CreateReader (typeMapping);
346                                 
347                         xsReader.Initialize (xmlReader, this);
348                         return Deserialize (xsReader);
349                 }
350
351                 protected virtual object Deserialize (XmlSerializationReader reader)
352                 {
353                         if (customSerializer)
354                                 // Must be implemented in derived class
355                                 throw new NotImplementedException ();
356                         
357                         try {
358                                 if (reader is XmlSerializationReaderInterpreter)
359                                         return ((XmlSerializationReaderInterpreter) reader).ReadRoot ();
360                                 else {
361                                         try {
362                                                 return serializerData.ReaderMethod.Invoke (reader, null);
363                                         } catch (TargetInvocationException ex) {
364                                                 throw ex.InnerException;
365                                         }
366                                 }
367                         } catch (Exception ex) {
368                                 if (ex is InvalidOperationException || ex is InvalidCastException)
369                                         throw new InvalidOperationException ("There is an error in"
370                                                 + " XML document.", ex);
371                                 throw;
372                         }
373                 }
374
375                 public static XmlSerializer [] FromMappings (XmlMapping [] mappings)
376                 {
377                         XmlSerializer[] sers = new XmlSerializer [mappings.Length];
378                         SerializerData[] datas = new SerializerData [mappings.Length];
379                         GenerationBatch batch = new GenerationBatch ();
380                         batch.Maps = mappings;
381                         batch.Datas = datas;
382                         
383                         for (int n=0; n<mappings.Length; n++)
384                         {
385                                 if (mappings[n] != null)
386                                 {
387                                         SerializerData data = new SerializerData ();
388                                         data.Batch = batch;
389                                         sers[n] = new XmlSerializer (mappings[n], data);
390                                         datas[n] = data;
391                                 }
392                         }
393                         
394                         return sers;
395                 }
396
397                 public static XmlSerializer [] FromTypes (Type [] types)
398                 {
399                         XmlSerializer [] sers = new XmlSerializer [types.Length];
400                         for (int n=0; n<types.Length; n++)
401                                 sers[n] = new XmlSerializer (types[n]);
402                         return sers;
403                 }
404
405                 protected virtual void Serialize (object o, XmlSerializationWriter writer)
406                 {
407                         if (customSerializer)
408                                 // Must be implemented in derived class
409                                 throw new NotImplementedException ();
410                                 
411                         if (writer is XmlSerializationWriterInterpreter)
412                                 ((XmlSerializationWriterInterpreter)writer).WriteRoot (o);
413                         else {
414                                 try {
415                                         serializerData.WriterMethod.Invoke (writer, new object[] {o});
416                                 } catch (TargetInvocationException ex) {
417                                         throw ex.InnerException;
418                                 }
419                         }
420                 }
421
422                 static Encoding DefaultEncoding = Encoding.Default;
423
424                 public void Serialize (Stream stream, object o)
425                 {
426                         XmlTextWriter xmlWriter = new XmlTextWriter (stream, DefaultEncoding);
427                         xmlWriter.Formatting = Formatting.Indented;
428                         Serialize (xmlWriter, o, null);
429                 }
430
431                 public void Serialize (TextWriter textWriter, object o)
432                 {
433                         XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
434                         xmlWriter.Formatting = Formatting.Indented;
435                         Serialize (xmlWriter, o, null);
436                 }
437
438                 public void Serialize (XmlWriter xmlWriter, object o)
439                 {
440                         Serialize (xmlWriter, o, null);
441                 }
442
443                 public void Serialize (Stream stream, object o, XmlSerializerNamespaces namespaces)
444                 {
445                         XmlTextWriter xmlWriter = new XmlTextWriter (stream, DefaultEncoding);
446                         xmlWriter.Formatting = Formatting.Indented;
447                         Serialize (xmlWriter, o, namespaces);
448                 }
449
450                 public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
451                 {
452                         XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
453                         xmlWriter.Formatting = Formatting.Indented;
454                         Serialize (xmlWriter, o, namespaces);
455                         xmlWriter.Flush();
456                 }
457
458                 public void Serialize (XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
459                 {
460                         XmlSerializationWriter xsWriter;
461
462                         try {
463                                 if (customSerializer)
464                                         xsWriter = CreateWriter ();
465                                 else
466                                         xsWriter = CreateWriter (typeMapping);
467
468                                 if (namespaces == null || namespaces.Count == 0) {
469                                         namespaces = new XmlSerializerNamespaces ();
470 #if NET_2_0
471                                         namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
472                                         namespaces.Add ("xsd", XmlSchema.Namespace);
473 #else
474                                         namespaces.Add ("xsd", XmlSchema.Namespace);
475                                         namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
476 #endif
477                                 }
478
479                                 xsWriter.Initialize (xmlWriter, namespaces);
480                                 Serialize (o, xsWriter);
481                                 xmlWriter.Flush ();
482                         } catch (Exception ex) {
483                                 if (ex is TargetInvocationException)
484                                         ex = ex.InnerException;
485
486                                 if (ex is InvalidOperationException || ex is InvalidCastException)
487                                         throw new InvalidOperationException ("There was an error generating" +
488                                                 " the XML document.", ex);
489
490                                 throw;
491                         }
492                 }
493                 
494                 [MonoTODO]
495                 public object Deserialize (XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
496                 {
497                         throw new NotImplementedException ();
498                 }
499
500                 [MonoTODO]
501                 public object Deserialize (XmlReader xmlReader, string encodingStyle)
502                 {
503                         throw new NotImplementedException ();
504                 }
505
506                 [MonoTODO]
507                 public object Deserialize (XmlReader xmlReader, XmlDeserializationEvents events)
508                 {
509                         throw new NotImplementedException ();
510                 }
511                 
512                 [MonoTODO]
513                 public static XmlSerializer[] FromMappings (XmlMapping[] mappings, Evidence evidence)
514                 {
515                         throw new NotImplementedException ();
516                 }
517
518                 [MonoTODO]
519                 public static XmlSerializer[] FromMappings (XmlMapping[] mappings, Type type)
520                 {
521                         throw new NotImplementedException ();
522                 }
523
524 #if !MOBILE
525                 public static Assembly GenerateSerializer (Type[] types, XmlMapping[] mappings)
526                 {
527                         return GenerateSerializer (types, mappings, null);
528                 }
529                 
530                 [MonoTODO]
531                 public static Assembly GenerateSerializer (Type[] types, XmlMapping[] mappings, CompilerParameters parameters)
532                 {
533                         GenerationBatch batch = new GenerationBatch ();
534                         batch.Maps = mappings;
535                         batch.Datas = new SerializerData [mappings.Length];
536                         
537                         for (int n=0; n<mappings.Length; n++) {
538                                 SerializerData data = new SerializerData ();
539                                 data.Batch = batch;
540                                 batch.Datas [n] = data;
541                         }
542                         
543                         return GenerateSerializers (batch, parameters);
544                 }
545 #endif
546
547                 public static string GetXmlSerializerAssemblyName (Type type)
548                 {
549                         return type.Assembly.GetName().Name + ".XmlSerializers";
550                 }
551
552                 public static string GetXmlSerializerAssemblyName (Type type, string defaultNamespace)
553                 {
554                         return GetXmlSerializerAssemblyName (type) + "." + defaultNamespace.GetHashCode ();
555                 }
556                 
557                 [MonoTODO]
558                 public void Serialize (XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
559                 {
560                         throw new NotImplementedException ();
561                 }
562
563                 [MonoNotSupported("")]
564                 public void Serialize (XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
565                 {
566                         throw new NotImplementedException ();
567                 }
568                 
569                 XmlSerializationWriter CreateWriter (XmlMapping typeMapping)
570                 {
571                         XmlSerializationWriter writer;
572                         
573                         lock (this) {
574                                 if (serializerData != null) {
575                                         lock (serializerData) {
576                                                 writer = serializerData.CreateWriter ();
577                                         }
578                                         if (writer != null) return writer;
579                                 }
580                         }
581                         
582 #if !NET_2_1
583                         if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
584                                 return new XmlSerializationWriterInterpreter (typeMapping);
585
586                         CheckGeneratedTypes (typeMapping);
587                         
588                         lock (this) {
589                                 lock (serializerData) {
590                                         writer = serializerData.CreateWriter ();
591                                 }
592                                 if (writer != null) return writer;
593                                 if (!generatorFallback)
594                                         throw new InvalidOperationException ("Error while generating serializer");
595                         }
596                         
597 #endif
598                         return new XmlSerializationWriterInterpreter (typeMapping);
599                 }
600                 
601                 XmlSerializationReader CreateReader (XmlMapping typeMapping)
602                 {
603 #if !NET_2_1
604                         XmlSerializationReader reader;
605                         
606                         lock (this) {
607                                 if (serializerData != null) {
608                                         lock (serializerData) {
609                                                 reader = serializerData.CreateReader ();
610                                         }
611                                         if (reader != null) return reader;
612                                 }
613                         }
614                         
615                         if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
616                                 return new XmlSerializationReaderInterpreter (typeMapping);
617
618                         CheckGeneratedTypes (typeMapping);
619                         
620                         lock (this) {
621                                 lock (serializerData) {
622                                         reader = serializerData.CreateReader ();
623                                 }
624                                 if (reader != null) return reader;
625                                 if (!generatorFallback)
626                                         throw new InvalidOperationException ("Error while generating serializer");
627                         }
628
629 #endif
630                         return new XmlSerializationReaderInterpreter (typeMapping);
631                 }
632                 
633 #if NET_2_1
634                 void CheckGeneratedTypes (XmlMapping typeMapping)
635                 {
636                         throw new NotImplementedException();
637                 }
638                 void GenerateSerializersAsync (GenerationBatch batch)
639                 {
640                         throw new NotImplementedException();
641                 }
642                 void RunSerializerGeneration (object obj)
643                 {
644                         throw new NotImplementedException();
645                 }
646 #else
647                 void CheckGeneratedTypes (XmlMapping typeMapping)
648                 {
649                         lock (this)
650                         {
651                                 if (serializerData == null) 
652                                 {
653                                         lock (serializerTypes)
654                                         {
655                                                 serializerData = (SerializerData) serializerTypes [typeMapping.Source];
656                                                 if (serializerData == null) {
657                                                         serializerData = new SerializerData();
658                                                         serializerTypes [typeMapping.Source] = serializerData;
659                                                 }
660                                         }
661                                 }
662                         }
663                         
664                         bool generate = false;
665                         lock (serializerData)
666                         {
667                                 generate = (++serializerData.UsageCount == generationThreshold);
668                         }
669                         
670                         if (generate)
671                         {
672                                 if (serializerData.Batch != null)
673                                         GenerateSerializersAsync (serializerData.Batch);
674                                 else
675                                 {
676                                         GenerationBatch batch = new GenerationBatch ();
677                                         batch.Maps = new XmlMapping[] {typeMapping};
678                                         batch.Datas = new SerializerData[] {serializerData};
679                                         GenerateSerializersAsync (batch);
680                                 }
681                         }
682                 }
683                 
684                 void GenerateSerializersAsync (GenerationBatch batch)
685                 {
686                         if (batch.Maps.Length != batch.Datas.Length)
687                                 throw new ArgumentException ("batch");
688
689                         lock (batch)
690                         {
691                                 if (batch.Done) return;
692                                 batch.Done = true;
693                         }
694                         
695                         if (backgroundGeneration)
696                                 ThreadPool.QueueUserWorkItem (new WaitCallback (RunSerializerGeneration), batch);
697                         else
698                                 RunSerializerGeneration (batch);
699                 }
700                 
701                 void RunSerializerGeneration (object obj)
702                 {
703                         try
704                         {
705                                 GenerationBatch batch = (GenerationBatch) obj;
706                                 batch = LoadFromSatelliteAssembly (batch);
707                                 
708                                 if (batch != null)
709                                         GenerateSerializers (batch, null);
710                         }
711                         catch (Exception ex)
712                         {
713                                 Console.WriteLine (ex);
714                         }
715                 }
716                 
717                 static Assembly GenerateSerializers (GenerationBatch batch, CompilerParameters cp)
718                 {
719                         DateTime tim = DateTime.Now;
720                         
721                         XmlMapping[] maps = batch.Maps;
722                         
723                         if (cp == null) {
724                                 cp = new CompilerParameters();
725                                 cp.IncludeDebugInformation = false;
726                                 cp.GenerateInMemory = true;
727                                 cp.TempFiles.KeepFiles = !deleteTempFiles;
728                         }
729                         
730                         string file = cp.TempFiles.AddExtension ("cs");
731                         StreamWriter sw = new StreamWriter (file);
732                         
733                         if (!deleteTempFiles)
734                                 Console.WriteLine ("Generating " + file);
735                         
736                         SerializationCodeGenerator gen = new SerializationCodeGenerator (maps);
737                         
738                         try
739                         {
740                                 gen.GenerateSerializers (sw);
741                         }
742                         catch (Exception ex)
743                         {
744                                 Console.WriteLine ("Serializer could not be generated");
745                                 Console.WriteLine (ex);
746                                 cp.TempFiles.Delete ();
747                                 return null;
748                         }
749                         sw.Close ();
750                         
751                         CSharpCodeProvider provider = new CSharpCodeProvider();
752                         ICodeCompiler comp = provider.CreateCompiler ();
753                         
754                         cp.GenerateExecutable = false;
755                         
756                         foreach (Type rtype in gen.ReferencedTypes)
757                         {
758                                 string path = new Uri (rtype.Assembly.CodeBase).LocalPath;
759                                 if (!cp.ReferencedAssemblies.Contains (path))
760                                         cp.ReferencedAssemblies.Add (path);
761                         }
762                                 
763                         if (!cp.ReferencedAssemblies.Contains ("System.dll"))
764                                 cp.ReferencedAssemblies.Add ("System.dll");
765                         if (!cp.ReferencedAssemblies.Contains ("System.Xml"))
766                                 cp.ReferencedAssemblies.Add ("System.Xml");
767                         if (!cp.ReferencedAssemblies.Contains ("System.Data"))
768                                 cp.ReferencedAssemblies.Add ("System.Data");
769                         
770                         CompilerResults res = comp.CompileAssemblyFromFile (cp, file);
771                         if (res.Errors.HasErrors || res.CompiledAssembly == null) {
772                                 Console.WriteLine ("Error while compiling generated serializer");
773                                 foreach (CompilerError error in res.Errors)
774                                         Console.WriteLine (error);
775                                         
776                                 cp.TempFiles.Delete ();
777                                 return null;
778                         }
779                         
780                         GenerationResult[] results = gen.GenerationResults;
781                         for (int n=0; n<results.Length; n++)
782                         {
783                                 GenerationResult gres = results[n];
784                                 SerializerData sd = batch.Datas [n];
785                                 lock (sd)
786                                 {
787                                         sd.WriterType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.WriterClassName);
788                                         sd.ReaderType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.ReaderClassName);
789                                         sd.WriterMethod = sd.WriterType.GetMethod (gres.WriteMethodName);
790                                         sd.ReaderMethod = sd.ReaderType.GetMethod (gres.ReadMethodName);
791                                         sd.Batch = null;
792                                 }
793                         }
794                         
795                         cp.TempFiles.Delete ();
796
797                         if (!deleteTempFiles)
798                                 Console.WriteLine ("Generation finished - " + (DateTime.Now - tim).TotalMilliseconds + " ms");
799                                 
800                         return res.CompiledAssembly;
801                 }
802 #endif
803                 
804 #if NET_2_0
805                 GenerationBatch LoadFromSatelliteAssembly (GenerationBatch batch)
806                 {
807                         return batch;
808                 }
809 #else
810                 GenerationBatch LoadFromSatelliteAssembly (GenerationBatch batch)
811                 {
812                         return batch;
813                 }
814 #endif
815                 
816 #endregion // Methods
817         }
818 }