Add missing files to get the XML tests running
[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 !TARGET_JVM
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 IXmlSerializerImplementation 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 TARGET_JVM
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                         
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                 }
165
166 #region Constructors
167
168                 protected XmlSerializer ()
169                 {
170                         customSerializer = true;
171                 }
172
173                 public XmlSerializer (Type type)
174                         : this (type, null, null, null, null)
175                 {
176                 }
177
178                 public XmlSerializer (XmlTypeMapping xmlTypeMapping)
179                 {
180                         typeMapping = xmlTypeMapping;
181                 }
182
183                 internal XmlSerializer (XmlMapping mapping, SerializerData data)
184                 {
185                         typeMapping = mapping;
186                         serializerData = data;
187                 }
188
189                 public XmlSerializer (Type type, string defaultNamespace)
190                         : this (type, null, null, null, defaultNamespace)
191                 {
192                 }
193
194                 public XmlSerializer (Type type, Type[] extraTypes)
195                         : this (type, null, extraTypes, null, null)
196                 {
197                 }
198
199                 public XmlSerializer (Type type, XmlAttributeOverrides overrides)
200                         : this (type, overrides, null, null, null)
201                 {
202                 }
203
204                 public XmlSerializer (Type type, XmlRootAttribute root)
205                         : this (type, null, null, root, null)
206                 {
207                 }
208
209                 public XmlSerializer (Type type,
210                         XmlAttributeOverrides overrides,
211                         Type [] extraTypes,
212                         XmlRootAttribute root,
213                         string defaultNamespace)
214                 {
215                         if (type == null)
216                                 throw new ArgumentNullException ("type");
217
218                         XmlReflectionImporter importer = new XmlReflectionImporter (overrides, defaultNamespace);
219
220                         if (extraTypes != null) 
221                         {
222                                 foreach (Type intype in extraTypes)
223                                         importer.IncludeType (intype);
224                         }
225
226                         typeMapping = importer.ImportTypeMapping (type, root, defaultNamespace);
227                 }
228                 
229                 internal XmlMapping Mapping
230                 {
231                         get { return typeMapping; }
232                 }
233
234 #if NET_2_0
235
236                 [MonoTODO]
237                 public XmlSerializer (Type type,
238                         XmlAttributeOverrides overrides,
239                         Type [] extraTypes,
240                         XmlRootAttribute root,
241                         string defaultNamespace,
242                         string location,
243                         Evidence evidence)
244                 {
245                 }
246 #endif
247
248 #endregion // Constructors
249
250 #region Events
251
252                 private XmlAttributeEventHandler onUnknownAttribute;
253                 private XmlElementEventHandler onUnknownElement;
254                 private XmlNodeEventHandler onUnknownNode;
255                 private UnreferencedObjectEventHandler onUnreferencedObject;
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                 public event UnreferencedObjectEventHandler UnreferencedObject 
273                 {
274                         add { onUnreferencedObject += value; } remove { onUnreferencedObject -= value; }
275                 }
276
277
278                 internal virtual void OnUnknownAttribute (XmlAttributeEventArgs e) 
279                 {
280                         if (onUnknownAttribute != null) onUnknownAttribute(this, e);
281                 }
282
283                 internal virtual void OnUnknownElement (XmlElementEventArgs e) 
284                 {
285                         if (onUnknownElement != null) onUnknownElement(this, e);
286                 }
287
288                 internal virtual void OnUnknownNode (XmlNodeEventArgs e) 
289                 {
290                         if (onUnknownNode != null) onUnknownNode(this, e);
291                 }
292
293                 internal virtual void OnUnreferencedObject (UnreferencedObjectEventArgs e) 
294                 {
295                         if (onUnreferencedObject != null) onUnreferencedObject(this, e);
296                 }
297
298
299 #endregion // Events
300
301 #region Methods
302
303                 public virtual bool CanDeserialize (XmlReader xmlReader)
304                 {
305                         xmlReader.MoveToContent ();
306                         if (typeMapping is XmlMembersMapping) 
307                                 return true;
308                         else
309                                 return ((XmlTypeMapping)typeMapping).ElementName == xmlReader.LocalName;
310                 }
311
312                 protected virtual XmlSerializationReader CreateReader ()
313                 {
314                         // Must be implemented in derived class
315                         throw new NotImplementedException ();
316                 }
317
318                 protected virtual XmlSerializationWriter CreateWriter ()
319                 {
320                         // Must be implemented in derived class
321                         throw new NotImplementedException ();
322                 }
323
324                 public object Deserialize (Stream stream)
325                 {
326                         XmlTextReader xmlReader = new XmlTextReader(stream);
327                         xmlReader.Normalization = true;
328                         return Deserialize(xmlReader);
329                 }
330
331                 public object Deserialize (TextReader textReader)
332                 {
333                         XmlTextReader xmlReader = new XmlTextReader(textReader);
334                         xmlReader.Normalization = true;
335                         return Deserialize(xmlReader);
336                 }
337
338                 public object Deserialize (XmlReader xmlReader)
339                 {
340                         XmlSerializationReader xsReader;
341                         if (customSerializer)
342                                 xsReader = CreateReader ();
343                         else
344                                 xsReader = CreateReader (typeMapping);
345                                 
346                         xsReader.Initialize (xmlReader, this);
347                         return Deserialize (xsReader);
348                 }
349
350                 protected virtual object Deserialize (XmlSerializationReader reader)
351                 {
352                         if (customSerializer)
353                                 // Must be implemented in derived class
354                                 throw new NotImplementedException ();
355                         
356                         try {
357                                 if (reader is XmlSerializationReaderInterpreter)
358                                         return ((XmlSerializationReaderInterpreter) reader).ReadRoot ();
359                                 else
360                                         return serializerData.ReaderMethod.Invoke (reader, null);
361                         } catch (Exception ex) {
362                                 if (ex is InvalidOperationException || ex is InvalidCastException)
363                                         throw new InvalidOperationException ("There was an error generating" +
364                                                 " the XML document.", ex);
365                                 throw;
366                         }
367                 }
368
369                 public static XmlSerializer [] FromMappings (XmlMapping [] mappings)
370                 {
371                         XmlSerializer[] sers = new XmlSerializer [mappings.Length];
372                         SerializerData[] datas = new SerializerData [mappings.Length];
373                         GenerationBatch batch = new GenerationBatch ();
374                         batch.Maps = mappings;
375                         batch.Datas = datas;
376                         
377                         for (int n=0; n<mappings.Length; n++)
378                         {
379                                 if (mappings[n] != null)
380                                 {
381                                         SerializerData data = new SerializerData ();
382                                         data.Batch = batch;
383                                         sers[n] = new XmlSerializer (mappings[n], data);
384                                         datas[n] = data;
385                                 }
386                         }
387                         
388                         return sers;
389                 }
390
391                 public static XmlSerializer [] FromTypes (Type [] mappings)
392                 {
393                         XmlSerializer [] sers = new XmlSerializer [mappings.Length];
394                         for (int n=0; n<mappings.Length; n++)
395                                 sers[n] = new XmlSerializer (mappings[n]);
396                         return sers;
397                 }
398
399                 protected virtual void Serialize (object o, XmlSerializationWriter writer)
400                 {
401                         if (customSerializer)
402                                 // Must be implemented in derived class
403                                 throw new NotImplementedException ();
404                                 
405                         if (writer is XmlSerializationWriterInterpreter)
406                                 ((XmlSerializationWriterInterpreter)writer).WriteRoot (o);
407                         else
408                                 serializerData.WriterMethod.Invoke (writer, new object[] {o});
409                 }
410
411                 public void Serialize (Stream stream, object o)
412                 {
413                         XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
414                         xmlWriter.Formatting = Formatting.Indented;
415                         Serialize (xmlWriter, o, null);
416                 }
417
418                 public void Serialize (TextWriter textWriter, object o)
419                 {
420                         XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
421                         xmlWriter.Formatting = Formatting.Indented;
422                         Serialize (xmlWriter, o, null);
423                 }
424
425                 public void Serialize (XmlWriter xmlWriter, object o)
426                 {
427                         Serialize (xmlWriter, o, null);
428                 }
429
430                 public void Serialize (Stream stream, object o, XmlSerializerNamespaces namespaces)
431                 {
432                         XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
433                         xmlWriter.Formatting = Formatting.Indented;
434                         Serialize (xmlWriter, o, namespaces);
435                 }
436
437                 public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
438                 {
439                         XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
440                         xmlWriter.Formatting = Formatting.Indented;
441                         Serialize (xmlWriter, o, namespaces);
442                         xmlWriter.Flush();
443                 }
444
445                 public void Serialize (XmlWriter writer, object o, XmlSerializerNamespaces namespaces)
446                 {
447                         XmlSerializationWriter xsWriter;
448
449                         try {
450                                 if (customSerializer)
451                                         xsWriter = CreateWriter ();
452                                 else
453                                         xsWriter = CreateWriter (typeMapping);
454
455                                 if (namespaces == null || namespaces.Count == 0) {
456                                         namespaces = new XmlSerializerNamespaces ();
457                                         namespaces.Add ("xsd", XmlSchema.Namespace);
458                                         namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
459                                 }
460
461                                 xsWriter.Initialize (writer, namespaces);
462                                 Serialize (o, xsWriter);
463                                 writer.Flush ();
464                         } catch (Exception ex) {
465                                 if (ex is TargetInvocationException)
466                                         ex = ex.InnerException;
467
468                                 if (ex is InvalidOperationException || ex is InvalidCastException)
469                                         throw new InvalidOperationException ("There was an error generating" +
470                                                 " the XML document.", ex);
471
472                                 throw;
473                         }
474                 }
475                 
476 #if NET_2_0
477                 
478                 [MonoTODO]
479                 public object Deserialize (XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
480                 {
481                         throw new NotImplementedException ();
482                 }
483
484                 [MonoTODO]
485                 public object Deserialize (XmlReader xmlReader, string encodingStyle)
486                 {
487                         throw new NotImplementedException ();
488                 }
489
490                 [MonoTODO]
491                 public object Deserialize (XmlReader xmlReader, XmlDeserializationEvents events)
492                 {
493                         throw new NotImplementedException ();
494                 }
495                 
496                 [MonoTODO]
497                 public static XmlSerializer[] FromMappings (XmlMapping[] mappings, Evidence evidence)
498                 {
499                         throw new NotImplementedException ();
500                 }
501
502                 [MonoTODO]
503                 public static XmlSerializer[] FromMappings (XmlMapping[] mappings, Type type)
504                 {
505                         throw new NotImplementedException ();
506                 }
507
508                 public static Assembly GenerateSerializer (Type[] types, XmlMapping[] mappings)
509                 {
510                         return GenerateSerializer (types, mappings, null);
511                 }
512                 
513                 [MonoTODO]
514                 public static Assembly GenerateSerializer (Type[] types, XmlMapping[] mappings, CompilerParameters parameters)
515                 {
516                         GenerationBatch batch = new GenerationBatch ();
517                         batch.Maps = mappings;
518                         batch.Datas = new SerializerData [mappings.Length];
519                         
520                         for (int n=0; n<mappings.Length; n++) {
521                                 SerializerData data = new SerializerData ();
522                                 data.Batch = batch;
523                                 batch.Datas [n] = data;
524                         }
525                         
526                         return GenerateSerializers (batch, parameters);
527                 }
528                 
529                 [MonoTODO]
530                 [Obsolete]
531                 public static Assembly GenerateSerializer (Type[] types, 
532                         XmlMapping[] mappings, 
533                         string codePath, 
534                         bool debug, 
535                         bool keepFiles)
536                 {
537                         throw new NotImplementedException ();
538                 }
539                 
540                 [MonoTODO]
541                 [Obsolete]
542                 public static Assembly GenerateSerializer (Type[] types, 
543                         XmlMapping[] mappings, 
544                         string codePath, 
545                         bool debug, 
546                         bool keepFiles, 
547                         string compilerOptions)
548                 {
549                         throw new NotImplementedException ();
550                 }
551
552                 public static string GetXmlSerializerAssemblyName (Type type)
553                 {
554                         return type.Assembly.GetName().Name + ".XmlSerializers";
555                 }
556
557                 public static string GetXmlSerializerAssemblyName (Type type, string defaultNamespace)
558                 {
559                         return GetXmlSerializerAssemblyName (type) + "." + defaultNamespace.GetHashCode ();
560                 }
561                 
562                 [MonoTODO]
563                 public void Serialize (XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
564                 {
565                         throw new NotImplementedException ();
566                 }
567
568 #endif
569                 
570                 XmlSerializationWriter CreateWriter (XmlMapping typeMapping)
571                 {
572                         XmlSerializationWriter writer;
573                         
574                         lock (this) {
575                                 if (serializerData != null) {
576                                         lock (serializerData) {
577                                                 writer = serializerData.CreateWriter ();
578                                         }
579                                         if (writer != null) return writer;
580                                 }
581                         }
582                         
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                         return new XmlSerializationWriterInterpreter (typeMapping);
598                 }
599                 
600                 XmlSerializationReader CreateReader (XmlMapping typeMapping)
601                 {
602                         XmlSerializationReader reader;
603                         
604                         lock (this) {
605                                 if (serializerData != null) {
606                                         lock (serializerData) {
607                                                 reader = serializerData.CreateReader ();
608                                         }
609                                         if (reader != null) return reader;
610                                 }
611                         }
612                         
613                         if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
614                                 return new XmlSerializationReaderInterpreter (typeMapping);
615
616                         CheckGeneratedTypes (typeMapping);
617                         
618                         lock (this) {
619                                 lock (serializerData) {
620                                         reader = serializerData.CreateReader ();
621                                 }
622                                 if (reader != null) return reader;
623                                 if (!generatorFallback)
624                                         throw new InvalidOperationException ("Error while generating serializer");
625                         }
626                         
627                         return new XmlSerializationReaderInterpreter (typeMapping);
628                 }
629                 
630 #if TARGET_JVM
631                 void CheckGeneratedTypes (XmlMapping typeMapping)
632                 {
633                         throw new NotImplementedException();
634                 }
635                 void GenerateSerializersAsync (GenerationBatch batch)
636                 {
637                         throw new NotImplementedException();
638                 }
639                 void RunSerializerGeneration (object obj)
640                 {
641                         throw new NotImplementedException();
642                 }
643 #else
644                 void CheckGeneratedTypes (XmlMapping typeMapping)
645                 {
646                         lock (this)
647                         {
648                                 if (serializerData == null) 
649                                 {
650                                         lock (serializerTypes)
651                                         {
652                                                 serializerData = (SerializerData) serializerTypes [typeMapping.Source];
653                                                 if (serializerData == null) {
654                                                         serializerData = new SerializerData();
655                                                         serializerTypes [typeMapping.Source] = serializerData;
656                                                 }
657                                         }
658                                 }
659                         }
660                         
661                         bool generate = false;
662                         lock (serializerData)
663                         {
664                                 generate = (++serializerData.UsageCount == generationThreshold);
665                         }
666                         
667                         if (generate)
668                         {
669                                 if (serializerData.Batch != null)
670                                         GenerateSerializersAsync (serializerData.Batch);
671                                 else
672                                 {
673                                         GenerationBatch batch = new GenerationBatch ();
674                                         batch.Maps = new XmlMapping[] {typeMapping};
675                                         batch.Datas = new SerializerData[] {serializerData};
676                                         GenerateSerializersAsync (batch);
677                                 }
678                         }
679                 }
680                 
681                 void GenerateSerializersAsync (GenerationBatch batch)
682                 {
683                         if (batch.Maps.Length != batch.Datas.Length)
684                                 throw new ArgumentException ("batch");
685
686                         lock (batch)
687                         {
688                                 if (batch.Done) return;
689                                 batch.Done = true;
690                         }
691                         
692                         if (backgroundGeneration)
693                                 ThreadPool.QueueUserWorkItem (new WaitCallback (RunSerializerGeneration), batch);
694                         else
695                                 RunSerializerGeneration (batch);
696                 }
697                 
698                 void RunSerializerGeneration (object obj)
699                 {
700                         try
701                         {
702                                 GenerationBatch batch = (GenerationBatch) obj;
703                                 batch = LoadFromSatelliteAssembly (batch);
704                                 
705                                 if (batch != null)
706                                         GenerateSerializers (batch, null);
707                         }
708                         catch (Exception ex)
709                         {
710                                 Console.WriteLine (ex);
711                         }
712                 }
713                 
714                 static Assembly GenerateSerializers (GenerationBatch batch, CompilerParameters cp)
715                 {
716                         DateTime tim = DateTime.Now;
717                         
718                         XmlMapping[] maps = batch.Maps;
719                         
720                         if (cp == null) {
721                                 cp = new CompilerParameters();
722                                 cp.IncludeDebugInformation = false;
723                                 cp.GenerateInMemory = true;
724                                 cp.TempFiles.KeepFiles = !deleteTempFiles;
725                         }
726                         
727                         string file = cp.TempFiles.AddExtension ("cs");
728                         StreamWriter sw = new StreamWriter (file);
729                         
730                         if (!deleteTempFiles)
731                                 Console.WriteLine ("Generating " + file);
732                         
733                         SerializationCodeGenerator gen = new SerializationCodeGenerator (maps);
734                         
735                         try
736                         {
737                                 gen.GenerateSerializers (sw);
738                         }
739                         catch (Exception ex)
740                         {
741                                 Console.WriteLine ("Serializer could not be generated");
742                                 Console.WriteLine (ex);
743                                 cp.TempFiles.Delete ();
744                                 return null;
745                         }
746                         sw.Close ();
747                         
748                         CSharpCodeProvider provider = new CSharpCodeProvider();
749                         ICodeCompiler comp = provider.CreateCompiler ();
750                         
751                         cp.GenerateExecutable = false;
752                         
753                         foreach (Type rtype in gen.ReferencedTypes)
754                         {
755                                 if (!cp.ReferencedAssemblies.Contains (rtype.Assembly.Location))
756                                         cp.ReferencedAssemblies.Add (rtype.Assembly.Location);
757                         }
758                                 
759                         if (!cp.ReferencedAssemblies.Contains ("System.dll"))
760                                 cp.ReferencedAssemblies.Add ("System.dll");
761                         if (!cp.ReferencedAssemblies.Contains ("System.Xml"))
762                                 cp.ReferencedAssemblies.Add ("System.Xml");
763                         if (!cp.ReferencedAssemblies.Contains ("System.Data"))
764                                 cp.ReferencedAssemblies.Add ("System.Data");
765                         
766                         CompilerResults res = comp.CompileAssemblyFromFile (cp, file);
767                         if (res.Errors.HasErrors || res.CompiledAssembly == null) {
768                                 Console.WriteLine ("Error while compiling generated serializer");
769                                 foreach (CompilerError error in res.Errors)
770                                         Console.WriteLine (error);
771                                         
772                                 cp.TempFiles.Delete ();
773                                 return null;
774                         }
775                         
776                         GenerationResult[] results = gen.GenerationResults;
777                         for (int n=0; n<results.Length; n++)
778                         {
779                                 GenerationResult gres = results[n];
780                                 SerializerData sd = batch.Datas [n];
781                                 lock (sd)
782                                 {
783                                         sd.WriterType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.WriterClassName);
784                                         sd.ReaderType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.ReaderClassName);
785                                         sd.WriterMethod = sd.WriterType.GetMethod (gres.WriteMethodName);
786                                         sd.ReaderMethod = sd.ReaderType.GetMethod (gres.ReadMethodName);
787                                         sd.Batch = null;
788                                 }
789                         }
790                         
791                         cp.TempFiles.Delete ();
792
793                         if (!deleteTempFiles)
794                                 Console.WriteLine ("Generation finished - " + (DateTime.Now - tim).TotalMilliseconds + " ms");
795                                 
796                         return res.CompiledAssembly;
797                 }
798 #endif
799                 
800 #if NET_2_0
801                 GenerationBatch LoadFromSatelliteAssembly (GenerationBatch batch)
802                 {
803                         return batch;
804                 }
805 #else
806                 GenerationBatch LoadFromSatelliteAssembly (GenerationBatch batch)
807                 {
808                         return batch;
809                 }
810 #endif
811                 
812 #endregion // Methods
813         }
814 }