5 // Lluis Sanchez Gual (lluis@ximian.com)
7 // (C) 2002, 2003 Ximian, Inc. http://www.ximian.com
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
32 using System.Threading;
33 using System.Collections;
34 using System.Globalization;
36 using System.Reflection;
38 using System.Xml.Schema;
42 using System.CodeDom.Compiler;
43 using Microsoft.CSharp;
45 using System.Configuration;
46 using System.Security.Policy;
48 namespace System.Xml.Serialization
51 public class XmlSerializer
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;
61 bool customSerializer;
62 XmlMapping typeMapping;
64 SerializerData serializerData;
66 static Hashtable serializerTypes = new Hashtable ();
68 internal class SerializerData
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;
78 public XmlSerializationReader CreateReader () {
79 if (ReaderType != null)
80 return (XmlSerializationReader) Activator.CreateInstance (ReaderType);
81 else if (Implementation != null)
82 return Implementation.Reader;
87 public XmlSerializationWriter CreateWriter () {
88 if (WriterType != null)
89 return (XmlSerializationWriter) Activator.CreateInstance (WriterType);
90 else if (Implementation != null)
91 return Implementation.Writer;
97 internal class GenerationBatch
100 public XmlMapping[] Maps;
101 public SerializerData[] Datas;
104 static XmlSerializer ()
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
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.
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
126 generationThreshold = -1;
127 backgroundGeneration = false;
129 string db = Environment.GetEnvironmentVariable ("MONO_XMLSERIALIZER_DEBUG");
130 string th = Environment.GetEnvironmentVariable ("MONO_XMLSERIALIZER_THS");
133 generationThreshold = 50;
134 backgroundGeneration = true;
136 int i = th.IndexOf (',');
138 if (th.Substring (i+1) == "nofallback")
139 generatorFallback = false;
140 th = th.Substring (0, i);
143 if (th.ToLower(CultureInfo.InvariantCulture) == "no")
144 generationThreshold = -1;
146 generationThreshold = int.Parse (th, CultureInfo.InvariantCulture);
147 backgroundGeneration = (generationThreshold != 0);
148 if (generationThreshold < 1) generationThreshold = 1;
152 deleteTempFiles = (db == null || db == "no");
154 IDictionary table = (IDictionary) ConfigurationSettings.GetConfig("system.diagnostics");
157 table = (IDictionary) table["switches"];
160 string val = (string) table ["XmlSerialization.Compilation"];
161 if (val == "1") deleteTempFiles = false;
168 protected XmlSerializer ()
170 customSerializer = true;
173 public XmlSerializer (Type type)
174 : this (type, null, null, null, null)
178 public XmlSerializer (XmlTypeMapping xmlTypeMapping)
180 typeMapping = xmlTypeMapping;
183 internal XmlSerializer (XmlMapping mapping, SerializerData data)
185 typeMapping = mapping;
186 serializerData = data;
189 public XmlSerializer (Type type, string defaultNamespace)
190 : this (type, null, null, null, defaultNamespace)
194 public XmlSerializer (Type type, Type[] extraTypes)
195 : this (type, null, extraTypes, null, null)
199 public XmlSerializer (Type type, XmlAttributeOverrides overrides)
200 : this (type, overrides, null, null, null)
204 public XmlSerializer (Type type, XmlRootAttribute root)
205 : this (type, null, null, root, null)
209 public XmlSerializer (Type type,
210 XmlAttributeOverrides overrides,
212 XmlRootAttribute root,
213 string defaultNamespace)
216 throw new ArgumentNullException ("type");
218 XmlReflectionImporter importer = new XmlReflectionImporter (overrides, defaultNamespace);
220 if (extraTypes != null)
222 foreach (Type intype in extraTypes)
223 importer.IncludeType (intype);
226 typeMapping = importer.ImportTypeMapping (type, root, defaultNamespace);
229 internal XmlMapping Mapping
231 get { return typeMapping; }
237 public XmlSerializer (Type type,
238 XmlAttributeOverrides overrides,
240 XmlRootAttribute root,
241 string defaultNamespace,
248 #endregion // Constructors
252 private XmlAttributeEventHandler onUnknownAttribute;
253 private XmlElementEventHandler onUnknownElement;
254 private XmlNodeEventHandler onUnknownNode;
255 private UnreferencedObjectEventHandler onUnreferencedObject;
257 public event XmlAttributeEventHandler UnknownAttribute
259 add { onUnknownAttribute += value; } remove { onUnknownAttribute -= value; }
262 public event XmlElementEventHandler UnknownElement
264 add { onUnknownElement += value; } remove { onUnknownElement -= value; }
267 public event XmlNodeEventHandler UnknownNode
269 add { onUnknownNode += value; } remove { onUnknownNode -= value; }
272 public event UnreferencedObjectEventHandler UnreferencedObject
274 add { onUnreferencedObject += value; } remove { onUnreferencedObject -= value; }
278 internal virtual void OnUnknownAttribute (XmlAttributeEventArgs e)
280 if (onUnknownAttribute != null) onUnknownAttribute(this, e);
283 internal virtual void OnUnknownElement (XmlElementEventArgs e)
285 if (onUnknownElement != null) onUnknownElement(this, e);
288 internal virtual void OnUnknownNode (XmlNodeEventArgs e)
290 if (onUnknownNode != null) onUnknownNode(this, e);
293 internal virtual void OnUnreferencedObject (UnreferencedObjectEventArgs e)
295 if (onUnreferencedObject != null) onUnreferencedObject(this, e);
303 public virtual bool CanDeserialize (XmlReader xmlReader)
305 xmlReader.MoveToContent ();
306 if (typeMapping is XmlMembersMapping)
309 return ((XmlTypeMapping)typeMapping).ElementName == xmlReader.LocalName;
312 protected virtual XmlSerializationReader CreateReader ()
314 // Must be implemented in derived class
315 throw new NotImplementedException ();
318 protected virtual XmlSerializationWriter CreateWriter ()
320 // Must be implemented in derived class
321 throw new NotImplementedException ();
324 public object Deserialize (Stream stream)
326 XmlTextReader xmlReader = new XmlTextReader(stream);
327 xmlReader.Normalization = true;
328 return Deserialize(xmlReader);
331 public object Deserialize (TextReader textReader)
333 XmlTextReader xmlReader = new XmlTextReader(textReader);
334 xmlReader.Normalization = true;
335 return Deserialize(xmlReader);
338 public object Deserialize (XmlReader xmlReader)
340 XmlSerializationReader xsReader;
341 if (customSerializer)
342 xsReader = CreateReader ();
344 xsReader = CreateReader (typeMapping);
346 xsReader.Initialize (xmlReader, this);
347 return Deserialize (xsReader);
350 protected virtual object Deserialize (XmlSerializationReader reader)
352 if (customSerializer)
353 // Must be implemented in derived class
354 throw new NotImplementedException ();
357 if (reader is XmlSerializationReaderInterpreter)
358 return ((XmlSerializationReaderInterpreter) reader).ReadRoot ();
360 return serializerData.ReaderMethod.Invoke (reader, null);
361 } catch (Exception ex) {
362 if (ex is InvalidOperationException || ex is InvalidCastException)
363 throw new InvalidOperationException ("There is an error in"
364 + " XML document.", ex);
369 public static XmlSerializer [] FromMappings (XmlMapping [] mappings)
371 XmlSerializer[] sers = new XmlSerializer [mappings.Length];
372 SerializerData[] datas = new SerializerData [mappings.Length];
373 GenerationBatch batch = new GenerationBatch ();
374 batch.Maps = mappings;
377 for (int n=0; n<mappings.Length; n++)
379 if (mappings[n] != null)
381 SerializerData data = new SerializerData ();
383 sers[n] = new XmlSerializer (mappings[n], data);
391 public static XmlSerializer [] FromTypes (Type [] mappings)
393 XmlSerializer [] sers = new XmlSerializer [mappings.Length];
394 for (int n=0; n<mappings.Length; n++)
395 sers[n] = new XmlSerializer (mappings[n]);
399 protected virtual void Serialize (object o, XmlSerializationWriter writer)
401 if (customSerializer)
402 // Must be implemented in derived class
403 throw new NotImplementedException ();
405 if (writer is XmlSerializationWriterInterpreter)
406 ((XmlSerializationWriterInterpreter)writer).WriteRoot (o);
408 serializerData.WriterMethod.Invoke (writer, new object[] {o});
411 public void Serialize (Stream stream, object o)
413 XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
414 xmlWriter.Formatting = Formatting.Indented;
415 Serialize (xmlWriter, o, null);
418 public void Serialize (TextWriter textWriter, object o)
420 XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
421 xmlWriter.Formatting = Formatting.Indented;
422 Serialize (xmlWriter, o, null);
425 public void Serialize (XmlWriter xmlWriter, object o)
427 Serialize (xmlWriter, o, null);
430 public void Serialize (Stream stream, object o, XmlSerializerNamespaces namespaces)
432 XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
433 xmlWriter.Formatting = Formatting.Indented;
434 Serialize (xmlWriter, o, namespaces);
437 public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
439 XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
440 xmlWriter.Formatting = Formatting.Indented;
441 Serialize (xmlWriter, o, namespaces);
445 public void Serialize (XmlWriter writer, object o, XmlSerializerNamespaces namespaces)
447 XmlSerializationWriter xsWriter;
450 if (customSerializer)
451 xsWriter = CreateWriter ();
453 xsWriter = CreateWriter (typeMapping);
455 if (namespaces == null || namespaces.Count == 0) {
456 namespaces = new XmlSerializerNamespaces ();
458 namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
459 namespaces.Add ("xsd", XmlSchema.Namespace);
461 namespaces.Add ("xsd", XmlSchema.Namespace);
462 namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
466 xsWriter.Initialize (writer, namespaces);
467 Serialize (o, xsWriter);
469 } catch (Exception ex) {
470 if (ex is TargetInvocationException)
471 ex = ex.InnerException;
473 if (ex is InvalidOperationException || ex is InvalidCastException)
474 throw new InvalidOperationException ("There was an error generating" +
475 " the XML document.", ex);
484 public object Deserialize (XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
486 throw new NotImplementedException ();
490 public object Deserialize (XmlReader xmlReader, string encodingStyle)
492 throw new NotImplementedException ();
496 public object Deserialize (XmlReader xmlReader, XmlDeserializationEvents events)
498 throw new NotImplementedException ();
502 public static XmlSerializer[] FromMappings (XmlMapping[] mappings, Evidence evidence)
504 throw new NotImplementedException ();
508 public static XmlSerializer[] FromMappings (XmlMapping[] mappings, Type type)
510 throw new NotImplementedException ();
514 public static Assembly GenerateSerializer (Type[] types, XmlMapping[] mappings)
516 return GenerateSerializer (types, mappings, null);
520 public static Assembly GenerateSerializer (Type[] types, XmlMapping[] mappings, CompilerParameters parameters)
522 GenerationBatch batch = new GenerationBatch ();
523 batch.Maps = mappings;
524 batch.Datas = new SerializerData [mappings.Length];
526 for (int n=0; n<mappings.Length; n++) {
527 SerializerData data = new SerializerData ();
529 batch.Datas [n] = data;
532 return GenerateSerializers (batch, parameters);
536 public static string GetXmlSerializerAssemblyName (Type type)
538 return type.Assembly.GetName().Name + ".XmlSerializers";
541 public static string GetXmlSerializerAssemblyName (Type type, string defaultNamespace)
543 return GetXmlSerializerAssemblyName (type) + "." + defaultNamespace.GetHashCode ();
547 public void Serialize (XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
549 throw new NotImplementedException ();
554 XmlSerializationWriter CreateWriter (XmlMapping typeMapping)
556 XmlSerializationWriter writer;
559 if (serializerData != null) {
560 lock (serializerData) {
561 writer = serializerData.CreateWriter ();
563 if (writer != null) return writer;
567 if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
568 return new XmlSerializationWriterInterpreter (typeMapping);
570 CheckGeneratedTypes (typeMapping);
573 lock (serializerData) {
574 writer = serializerData.CreateWriter ();
576 if (writer != null) return writer;
577 if (!generatorFallback)
578 throw new InvalidOperationException ("Error while generating serializer");
581 return new XmlSerializationWriterInterpreter (typeMapping);
584 XmlSerializationReader CreateReader (XmlMapping typeMapping)
586 XmlSerializationReader reader;
589 if (serializerData != null) {
590 lock (serializerData) {
591 reader = serializerData.CreateReader ();
593 if (reader != null) return reader;
597 if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
598 return new XmlSerializationReaderInterpreter (typeMapping);
600 CheckGeneratedTypes (typeMapping);
603 lock (serializerData) {
604 reader = serializerData.CreateReader ();
606 if (reader != null) return reader;
607 if (!generatorFallback)
608 throw new InvalidOperationException ("Error while generating serializer");
611 return new XmlSerializationReaderInterpreter (typeMapping);
615 void CheckGeneratedTypes (XmlMapping typeMapping)
617 throw new NotImplementedException();
619 void GenerateSerializersAsync (GenerationBatch batch)
621 throw new NotImplementedException();
623 void RunSerializerGeneration (object obj)
625 throw new NotImplementedException();
628 void CheckGeneratedTypes (XmlMapping typeMapping)
632 if (serializerData == null)
634 lock (serializerTypes)
636 serializerData = (SerializerData) serializerTypes [typeMapping.Source];
637 if (serializerData == null) {
638 serializerData = new SerializerData();
639 serializerTypes [typeMapping.Source] = serializerData;
645 bool generate = false;
646 lock (serializerData)
648 generate = (++serializerData.UsageCount == generationThreshold);
653 if (serializerData.Batch != null)
654 GenerateSerializersAsync (serializerData.Batch);
657 GenerationBatch batch = new GenerationBatch ();
658 batch.Maps = new XmlMapping[] {typeMapping};
659 batch.Datas = new SerializerData[] {serializerData};
660 GenerateSerializersAsync (batch);
665 void GenerateSerializersAsync (GenerationBatch batch)
667 if (batch.Maps.Length != batch.Datas.Length)
668 throw new ArgumentException ("batch");
672 if (batch.Done) return;
676 if (backgroundGeneration)
677 ThreadPool.QueueUserWorkItem (new WaitCallback (RunSerializerGeneration), batch);
679 RunSerializerGeneration (batch);
682 void RunSerializerGeneration (object obj)
686 GenerationBatch batch = (GenerationBatch) obj;
687 batch = LoadFromSatelliteAssembly (batch);
690 GenerateSerializers (batch, null);
694 Console.WriteLine (ex);
698 static Assembly GenerateSerializers (GenerationBatch batch, CompilerParameters cp)
700 DateTime tim = DateTime.Now;
702 XmlMapping[] maps = batch.Maps;
705 cp = new CompilerParameters();
706 cp.IncludeDebugInformation = false;
707 cp.GenerateInMemory = true;
708 cp.TempFiles.KeepFiles = !deleteTempFiles;
711 string file = cp.TempFiles.AddExtension ("cs");
712 StreamWriter sw = new StreamWriter (file);
714 if (!deleteTempFiles)
715 Console.WriteLine ("Generating " + file);
717 SerializationCodeGenerator gen = new SerializationCodeGenerator (maps);
721 gen.GenerateSerializers (sw);
725 Console.WriteLine ("Serializer could not be generated");
726 Console.WriteLine (ex);
727 cp.TempFiles.Delete ();
732 CSharpCodeProvider provider = new CSharpCodeProvider();
733 ICodeCompiler comp = provider.CreateCompiler ();
735 cp.GenerateExecutable = false;
737 foreach (Type rtype in gen.ReferencedTypes)
739 if (!cp.ReferencedAssemblies.Contains (rtype.Assembly.Location))
740 cp.ReferencedAssemblies.Add (rtype.Assembly.Location);
743 if (!cp.ReferencedAssemblies.Contains ("System.dll"))
744 cp.ReferencedAssemblies.Add ("System.dll");
745 if (!cp.ReferencedAssemblies.Contains ("System.Xml"))
746 cp.ReferencedAssemblies.Add ("System.Xml");
747 if (!cp.ReferencedAssemblies.Contains ("System.Data"))
748 cp.ReferencedAssemblies.Add ("System.Data");
750 CompilerResults res = comp.CompileAssemblyFromFile (cp, file);
751 if (res.Errors.HasErrors || res.CompiledAssembly == null) {
752 Console.WriteLine ("Error while compiling generated serializer");
753 foreach (CompilerError error in res.Errors)
754 Console.WriteLine (error);
756 cp.TempFiles.Delete ();
760 GenerationResult[] results = gen.GenerationResults;
761 for (int n=0; n<results.Length; n++)
763 GenerationResult gres = results[n];
764 SerializerData sd = batch.Datas [n];
767 sd.WriterType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.WriterClassName);
768 sd.ReaderType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.ReaderClassName);
769 sd.WriterMethod = sd.WriterType.GetMethod (gres.WriteMethodName);
770 sd.ReaderMethod = sd.ReaderType.GetMethod (gres.ReadMethodName);
775 cp.TempFiles.Delete ();
777 if (!deleteTempFiles)
778 Console.WriteLine ("Generation finished - " + (DateTime.Now - tim).TotalMilliseconds + " ms");
780 return res.CompiledAssembly;
785 GenerationBatch LoadFromSatelliteAssembly (GenerationBatch batch)
790 GenerationBatch LoadFromSatelliteAssembly (GenerationBatch batch)
796 #endregion // Methods