2
0

XmlSerializer.cs 22 KB

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