Welcome to mirror list, hosted at ThFree Co, Russian Federation.

XmlSerializer.cs « System.Xml.Serialization « System.XML « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: aa57189fb341f571fa0f3943f42919a104b98795 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//
// XmlSerializer.cs: 
//
// Author:
//   Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) 2002, 2003 Ximian, Inc.  http://www.ximian.com
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Configuration;

namespace System.Xml.Serialization
{

	public class XmlSerializer
	{
		internal const string WsdlNamespace = "http://schemas.xmlsoap.org/wsdl/";
		internal const string EncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/";
		static int generationThreshold;
		static bool backgroundGeneration = true;
		static bool deleteTempFiles = true;

		bool customSerializer;
		XmlMapping typeMapping;
		
		SerializerData serializerData;
		Type writerType;
		Type readerType;
		
		static Hashtable serializerTypes = new Hashtable ();
		
		internal class SerializerData
		{
			public int UsageCount;
			public Type ReaderType;
			public MethodInfo ReaderMethod;
			public Type WriterType;
			public MethodInfo WriterMethod;
			public GenerationBatch Batch;
		}
		
		internal class GenerationBatch
		{
			public bool Done;
			public XmlMapping[] Maps;
			public SerializerData[] Datas;
		}
		
		static XmlSerializer ()
		{
			string db = Environment.GetEnvironmentVariable ("MONO_XMLSERIALIZER_DEBUG");
			deleteTempFiles = (db == null || db == "no");
			
			IDictionary table = (IDictionary) ConfigurationSettings.GetConfig("system.diagnostics");
			if (table != null) {
				table = (IDictionary) table["switches"];
				if (table != null) {
					string val = (string) table ["XmlSerialization.Compilation"];
					if (val == "1") deleteTempFiles = false;
				}
			}
			
			string th = Environment.GetEnvironmentVariable ("MONO_XMLSERIALIZER_THS");
			
			if (th == null) {
				generationThreshold = 50;
				backgroundGeneration = true;
			}
			else if (th.ToLower(CultureInfo.InvariantCulture) == "no") 
				generationThreshold = -1;
			else {
				generationThreshold = int.Parse (th, CultureInfo.InvariantCulture);
				backgroundGeneration = (generationThreshold != 0);
				if (generationThreshold < 1) generationThreshold = 1;
			}
		}

#region Constructors

		protected XmlSerializer ()
		{
			customSerializer = true;
		}

		public XmlSerializer (Type type)
			: this (type, null, null, null, null)
		{
		}

		public XmlSerializer (XmlTypeMapping xmlTypeMapping)
		{
			typeMapping = xmlTypeMapping;
		}

		internal XmlSerializer (XmlMapping mapping, SerializerData data)
		{
			typeMapping = mapping;
			serializerData = data;
		}

		public XmlSerializer (Type type, string defaultNamespace)
			: this (type, null, null, null, defaultNamespace)
		{
		}

		public XmlSerializer (Type type, Type[] extraTypes)
			: this (type, null, extraTypes, null, null)
		{
		}

		public XmlSerializer (Type type, XmlAttributeOverrides overrides)
			: this (type, overrides, null, null, null)
		{
		}

		public XmlSerializer (Type type, XmlRootAttribute root)
			: this (type, null, null, root, null)
		{
		}

		public XmlSerializer (Type type,
			XmlAttributeOverrides overrides,
			Type [] extraTypes,
			XmlRootAttribute root,
			string defaultNamespace)
		{
			if (type == null)
				throw new ArgumentNullException ("type");

			XmlReflectionImporter importer = new XmlReflectionImporter (overrides, defaultNamespace);

			if (extraTypes != null) 
			{
				foreach (Type intype in extraTypes)
					importer.IncludeType (intype);
			}

			typeMapping = importer.ImportTypeMapping (type, root, defaultNamespace);
		}


#endregion // Constructors

#region Events

		private XmlAttributeEventHandler onUnknownAttribute;
		private XmlElementEventHandler onUnknownElement;
		private XmlNodeEventHandler onUnknownNode;
		private UnreferencedObjectEventHandler onUnreferencedObject;

		public event XmlAttributeEventHandler UnknownAttribute 
		{
			add { onUnknownAttribute += value; } remove { onUnknownAttribute -= value; }
		}

		public event XmlElementEventHandler UnknownElement 
		{
			add { onUnknownElement += value; } remove { onUnknownElement -= value; }
		}

		public event XmlNodeEventHandler UnknownNode 
		{
			add { onUnknownNode += value; } remove { onUnknownNode -= value; }
		}

		public event UnreferencedObjectEventHandler UnreferencedObject 
		{
			add { onUnreferencedObject += value; } remove { onUnreferencedObject -= value; }
		}


		internal virtual void OnUnknownAttribute (XmlAttributeEventArgs e) 
		{
			if (onUnknownAttribute != null) onUnknownAttribute(this, e);
		}

		internal virtual void OnUnknownElement (XmlElementEventArgs e) 
		{
			if (onUnknownElement != null) onUnknownElement(this, e);
		}

		internal virtual void OnUnknownNode (XmlNodeEventArgs e) 
		{
			if (onUnknownNode != null) onUnknownNode(this, e);
		}

		internal virtual void OnUnreferencedObject (UnreferencedObjectEventArgs e) 
		{
			if (onUnreferencedObject != null) onUnreferencedObject(this, e);
		}


#endregion // Events

#region Methods

		public virtual bool CanDeserialize (XmlReader xmlReader)
		{
			xmlReader.MoveToContent	();
			if (typeMapping is XmlMembersMapping) 
				return true;
			else
				return ((XmlTypeMapping)typeMapping).ElementName == xmlReader.LocalName;
		}

		protected virtual XmlSerializationReader CreateReader ()
		{
			// Must be implemented in derived class
			throw new NotImplementedException ();
		}

		protected virtual XmlSerializationWriter CreateWriter ()
		{
			// Must be implemented in derived class
			throw new NotImplementedException ();
		}

		public object Deserialize (Stream stream)
		{
			XmlTextReader xmlReader = new XmlTextReader(stream);
			xmlReader.Normalization = true;
			return Deserialize(xmlReader);
		}

		public object Deserialize (TextReader textReader)
		{
			XmlTextReader xmlReader = new XmlTextReader(textReader);
			xmlReader.Normalization = true;
			return Deserialize(xmlReader);
		}

		public object Deserialize (XmlReader xmlReader)
		{
			XmlSerializationReader xsReader;
			if (customSerializer)
				xsReader = CreateReader ();
			else
				xsReader = CreateReader (typeMapping);
				
			xsReader.Initialize (xmlReader, this);
			return Deserialize (xsReader);
		}

		protected virtual object Deserialize (XmlSerializationReader reader)
		{
			if (customSerializer)
				// Must be implemented in derived class
				throw new NotImplementedException ();
			
			if (reader is XmlSerializationReaderInterpreter)
				return ((XmlSerializationReaderInterpreter)reader).ReadRoot ();
			else
				return serializerData.ReaderMethod.Invoke (reader, null);
		}

		public static XmlSerializer [] FromMappings (XmlMapping	[] mappings)
		{
			XmlSerializer[] sers = new XmlSerializer [mappings.Length];
			SerializerData[] datas = new SerializerData [mappings.Length];
			GenerationBatch batch = new GenerationBatch ();
			batch.Maps = mappings;
			batch.Datas = datas;
			
			for (int n=0; n<mappings.Length; n++)
			{
				if (mappings[n] != null)
				{
					SerializerData data = new SerializerData ();
					data.Batch = batch;
					sers[n] = new XmlSerializer (mappings[n], data);
					datas[n] = data;
				}
			}
			
			return sers;
		}

		public static XmlSerializer [] FromTypes (Type [] mappings)
		{
			XmlSerializer [] sers = new XmlSerializer [mappings.Length];
			for (int n=0; n<mappings.Length; n++)
				sers[n] = new XmlSerializer (mappings[n]);
			return sers;
		}

		protected virtual void Serialize (object o, XmlSerializationWriter writer)
		{
			if (customSerializer)
				// Must be implemented in derived class
				throw new NotImplementedException ();
				
			if (writer is XmlSerializationWriterInterpreter)
				((XmlSerializationWriterInterpreter)writer).WriteRoot (o);
			else
				serializerData.WriterMethod.Invoke (writer, new object[] {o});
		}

		public void Serialize (Stream stream, object o)
		{
			XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
			xmlWriter.Formatting = Formatting.Indented;
			Serialize (xmlWriter, o, null);
		}

		public void Serialize (TextWriter textWriter, object o)
		{
			XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
			xmlWriter.Formatting = Formatting.Indented;
			Serialize (xmlWriter, o, null);
		}

		public void Serialize (XmlWriter xmlWriter, object o)
		{
			Serialize (xmlWriter, o, null);
		}

		public void Serialize (Stream stream, object o, XmlSerializerNamespaces	namespaces)
		{
			XmlTextWriter xmlWriter	= new XmlTextWriter (stream, System.Text.Encoding.Default);
			xmlWriter.Formatting = Formatting.Indented;
			Serialize (xmlWriter, o, namespaces);
		}

		public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces	namespaces)
		{
			XmlTextWriter xmlWriter	= new XmlTextWriter (textWriter);
			xmlWriter.Formatting = Formatting.Indented;
			Serialize (xmlWriter, o, namespaces);
			xmlWriter.Flush();
		}

		public void Serialize (XmlWriter writer, object o, XmlSerializerNamespaces namespaces)
		{
			XmlSerializationWriter xsWriter;
			
			if (customSerializer)
				xsWriter = CreateWriter ();
			else
				xsWriter = CreateWriter (typeMapping);
				
			if (namespaces == null || namespaces.Count == 0)
			{
				namespaces = new XmlSerializerNamespaces ();
				namespaces.Add ("xsd", XmlSchema.Namespace);
				namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
			}
			
			xsWriter.Initialize (writer, namespaces);
			Serialize (o, xsWriter);
			writer.Flush ();
		}
		
		XmlSerializationWriter CreateWriter (XmlMapping typeMapping)
		{
			lock (this) {
				if (serializerData != null && serializerData.WriterType != null)
					return (XmlSerializationWriter) Activator.CreateInstance (serializerData.WriterType);
			}
			
			if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
				return new XmlSerializationWriterInterpreter (typeMapping);

			CheckGeneratedTypes (typeMapping);
			
			lock (this) {
				if (serializerData.WriterType != null)
					return (XmlSerializationWriter) Activator.CreateInstance (serializerData.WriterType);
			}
			
			return new XmlSerializationWriterInterpreter (typeMapping);
		}
		
		XmlSerializationReader CreateReader (XmlMapping typeMapping)
		{
			lock (this) {
				if (serializerData != null && serializerData.ReaderType != null)
					return (XmlSerializationReader) Activator.CreateInstance (serializerData.ReaderType);
			}
			
			if (!typeMapping.Source.CanBeGenerated || generationThreshold == -1)
				return new XmlSerializationReaderInterpreter (typeMapping);

			CheckGeneratedTypes (typeMapping);
			
			lock (this) {
				if (serializerData.ReaderType != null)
					return (XmlSerializationReader) Activator.CreateInstance (serializerData.ReaderType);
			}
			
			return new XmlSerializationReaderInterpreter (typeMapping);
		}
		
		void CheckGeneratedTypes (XmlMapping typeMapping)
		{
			lock (this)
			{
				if (serializerData == null) 
				{
					lock (serializerTypes)
					{
						serializerData = (SerializerData) serializerTypes [typeMapping.Source];
						if (serializerData == null) {
							serializerData = new SerializerData();
							serializerTypes [typeMapping.Source] = serializerData;
						}
					}
				}
			}
			
			bool generate = false;
			lock (serializerData)
			{
				generate = (++serializerData.UsageCount == generationThreshold);
			}
			
			if (generate)
			{
				if (serializerData.Batch != null)
					GenerateSerializers (serializerData.Batch);
				else
				{
					GenerationBatch batch = new GenerationBatch ();
					batch.Maps = new XmlMapping[] {typeMapping};
					batch.Datas = new SerializerData[] {serializerData};
					GenerateSerializers (batch);
				}
			}
		}
		
		void GenerateSerializers (GenerationBatch batch)
		{
			if (batch.Maps.Length != batch.Datas.Length)
				throw new ArgumentException ("batch");

			lock (batch)
			{
				if (batch.Done) return;
				batch.Done = true;
			}
			
			if (backgroundGeneration)
				ThreadPool.QueueUserWorkItem (new WaitCallback (RunSerializerGeneration), batch);
			else
				RunSerializerGeneration (batch);
		}
		
		void RunSerializerGeneration (object obj)
		{
			try
			{
				RunSerializerGenerationAux (obj);
			}
			catch (Exception ex)
			{
				Console.WriteLine (ex);
			}
		}
		
		void RunSerializerGenerationAux (object obj)
		{
			DateTime tim = DateTime.Now;
			
			GenerationBatch batch = (GenerationBatch) obj;
			XmlMapping[] maps = batch.Maps;
			
			string file = Path.GetTempFileName ();
			StreamWriter sw = new StreamWriter (file);
			
			if (!deleteTempFiles)
				Console.WriteLine ("Generating " + file);
			
			SerializationCodeGenerator gen = new SerializationCodeGenerator (maps);
			
			try
			{
				gen.GenerateSerializers (sw);
			}
			catch (Exception ex)
			{
				Console.WriteLine ("Serializer could not be generated");
				Console.WriteLine (ex);
				
				if (deleteTempFiles)
					File.Delete (file);
				return;
			}
			sw.Close ();
			
			CSharpCodeProvider provider = new CSharpCodeProvider();
			ICodeCompiler comp = provider.CreateCompiler ();
			
			CompilerParameters cp = new CompilerParameters();
		    cp.GenerateExecutable = false;
			cp.IncludeDebugInformation = false;
		    cp.GenerateInMemory = true;
		    cp.ReferencedAssemblies.Add ("System.dll");
			cp.ReferencedAssemblies.Add ("System.Xml");
			cp.ReferencedAssemblies.Add ("System.Data");
			
			foreach (Type rtype in gen.ReferencedTypes)
			{
				if (!cp.ReferencedAssemblies.Contains (rtype.Assembly.Location))
					cp.ReferencedAssemblies.Add (rtype.Assembly.Location);
			}

			CompilerResults res = comp.CompileAssemblyFromFile (cp, file);
			if (res.Errors.Count > 0)
			{
				Console.WriteLine ("Error while compiling generated serializer");
				foreach (CompilerError error in res.Errors)
					Console.WriteLine (error);
					
				if (deleteTempFiles)
					File.Delete (file);
				return;
			}
			
			GenerationResult[] results = gen.GenerationResults;
			for (int n=0; n<results.Length; n++)
			{
				GenerationResult gres = results[n];
				SerializerData sd = batch.Datas [n];
				lock (sd)
				{
					sd.WriterType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.WriterClassName);
					sd.ReaderType = res.CompiledAssembly.GetType (gres.Namespace + "." + gres.ReaderClassName);
					sd.WriterMethod = sd.WriterType.GetMethod (gres.WriteMethodName);
					sd.ReaderMethod = sd.ReaderType.GetMethod (gres.ReadMethodName);
					sd.Batch = null;
				}
			}
			
			if (deleteTempFiles)
				File.Delete (file);

			if (!deleteTempFiles)
				Console.WriteLine ("Generation finished - " + (DateTime.Now - tim).TotalMilliseconds + " ms");
		}
		
#endregion // Methods
	}
}