/
XmlSchemaSet.cs
1467 lines (1317 loc) · 57.5 KB
/
XmlSchemaSet.cs
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;
using System.Threading;
namespace System.Xml.Schema
{
/// <summary>
/// The XmlSchemaSet contains a set of namespace URI's.
/// Each namespace also have an associated private data cache
/// corresponding to the XML-Data Schema or W3C XML Schema.
/// The XmlSchemaSet will able to load only XSD schemas,
/// and compile them into an internal "cooked schema representation".
/// The Validate method then uses this internal representation for
/// efficient runtime validation of any given subtree.
/// </summary>
public class XmlSchemaSet
{
private readonly XmlNameTable _nameTable;
private SchemaNames? _schemaNames;
private readonly SortedList _schemas; // List of source schemas
//Event handling
private readonly ValidationEventHandler _internalEventHandler;
private ValidationEventHandler? _eventHandler;
private bool _isCompiled;
//Dictionary<Uri, XmlSchema> schemaLocations;
//Dictionary<ChameleonKey, XmlSchema> chameleonSchemas;
private readonly Hashtable _schemaLocations;
private readonly Hashtable _chameleonSchemas;
private readonly Hashtable _targetNamespaces;
private bool _compileAll;
//Cached Compiled Info
private SchemaInfo _cachedCompiledInfo;
//Reader settings to parse schema
private readonly XmlReaderSettings _readerSettings;
private XmlSchema? _schemaForSchema; //Only one schema for schema per set
//Schema compilation settings
private XmlSchemaCompilationSettings _compilationSettings;
internal XmlSchemaObjectTable? elements;
internal XmlSchemaObjectTable? attributes;
internal XmlSchemaObjectTable? schemaTypes;
internal XmlSchemaObjectTable? substitutionGroups;
private XmlSchemaObjectTable? _typeExtensions;
//Thread safety
private object? _internalSyncObject;
internal object InternalSyncObject
{
get
{
if (_internalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange<object?>(ref _internalSyncObject, o, null);
}
return _internalSyncObject;
}
}
//Constructors
/// <summary>
/// Construct a new empty schema schemas.
/// </summary>
public XmlSchemaSet() : this(new NameTable())
{
}
/// <summary>
/// Construct a new empty schema schemas with associated XmlNameTable.
/// The XmlNameTable is used when loading schemas.
/// </summary>
public XmlSchemaSet(XmlNameTable nameTable)
{
ArgumentNullException.ThrowIfNull(nameTable);
_nameTable = nameTable;
_schemas = new SortedList();
/*schemaLocations = new Dictionary<Uri, XmlSchema>();
chameleonSchemas = new Dictionary<ChameleonKey, XmlSchema>();*/
_schemaLocations = new Hashtable();
_chameleonSchemas = new Hashtable();
_targetNamespaces = new Hashtable();
_internalEventHandler = new ValidationEventHandler(InternalValidationCallback);
_eventHandler = _internalEventHandler;
_readerSettings = new XmlReaderSettings();
// we don't have to check XmlReaderSettings.EnableLegacyXmlSettings() here because the following
// code will return same result either we are running on v4.5 or later
if (_readerSettings.GetXmlResolver() == null)
{
// The created resolver will be used in the schema validation only
_readerSettings.XmlResolver = XmlReaderSettings.GetDefaultPermissiveResolver();
_readerSettings.IsXmlResolverSet = false;
}
_readerSettings.NameTable = nameTable;
_readerSettings.DtdProcessing = DtdProcessing.Prohibit;
_compilationSettings = new XmlSchemaCompilationSettings();
_cachedCompiledInfo = new SchemaInfo();
_compileAll = true;
}
//Public Properties
/// <summary>
/// The default XmlNameTable used by the XmlSchemaSet when loading new schemas.
/// </summary>
public XmlNameTable NameTable
{
get { return _nameTable; }
}
public event ValidationEventHandler ValidationEventHandler
{
add
{
_eventHandler -= _internalEventHandler;
_eventHandler += value;
_eventHandler ??= _internalEventHandler;
}
remove
{
_eventHandler -= value;
_eventHandler ??= _internalEventHandler;
}
}
/// <summary>
/// IsCompiled is true when the schema set is in compiled state.
/// </summary>
public bool IsCompiled
{
get
{
return _isCompiled;
}
}
public XmlResolver? XmlResolver
{
set
{
_readerSettings.XmlResolver = value;
}
}
public XmlSchemaCompilationSettings CompilationSettings
{
get
{
return _compilationSettings;
}
set
{
_compilationSettings = value;
}
}
/// <summary>
/// Returns the count of schemas in the set.
/// </summary>
public int Count
{
get
{
return _schemas.Count;
}
}
public XmlSchemaObjectTable GlobalElements => elements ??= new XmlSchemaObjectTable();
public XmlSchemaObjectTable GlobalAttributes => attributes ??= new XmlSchemaObjectTable();
public XmlSchemaObjectTable GlobalTypes => schemaTypes ??= new XmlSchemaObjectTable();
internal XmlSchemaObjectTable SubstitutionGroups => substitutionGroups ??= new XmlSchemaObjectTable();
/// <summary>
/// Table of all types extensions
/// </summary>
internal Hashtable SchemaLocations
{
get
{
return _schemaLocations;
}
}
/// <summary>
/// Table of all types extensions
/// </summary>
internal XmlSchemaObjectTable TypeExtensions => _typeExtensions ??= new XmlSchemaObjectTable();
//Public Methods
/// <summary>
/// Add the schema located by the given URL into the schema schemas.
/// If the given schema references other namespaces, the schemas for those other
/// namespaces are NOT automatically loaded.
/// </summary>
public XmlSchema? Add(string? targetNamespace, string schemaUri)
{
if (string.IsNullOrEmpty(schemaUri))
{
throw new ArgumentNullException(nameof(schemaUri));
}
if (targetNamespace != null)
{
targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace);
}
XmlSchema? schema = null;
lock (InternalSyncObject)
{
//Check if schema from url has already been added
XmlResolver tempResolver = _readerSettings.GetXmlResolver() ?? XmlReaderSettings.GetDefaultPermissiveResolver();
Uri tempSchemaUri = tempResolver.ResolveUri(null, schemaUri);
if (IsSchemaLoaded(tempSchemaUri, targetNamespace, out schema))
{
return schema;
}
else
{
//Url already not processed; Load SOM from url
XmlReader reader = XmlReader.Create(schemaUri, _readerSettings);
try
{
schema = Add(targetNamespace, ParseSchema(targetNamespace, reader));
while (reader.Read()) ; // wellformness check;
}
finally
{
reader.Close();
}
}
}
return schema;
}
/// <summary>
/// Add the given schema into the schema schemas.
/// If the given schema references other namespaces, the schemas for those
/// other namespaces are NOT automatically loaded.
/// </summary>
public XmlSchema? Add(string? targetNamespace, XmlReader schemaDocument)
{
ArgumentNullException.ThrowIfNull(schemaDocument);
if (targetNamespace != null)
{
targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace);
}
lock (InternalSyncObject)
{
XmlSchema? schema = null;
Uri schemaUri = new Uri(schemaDocument.BaseURI!, UriKind.RelativeOrAbsolute);
if (IsSchemaLoaded(schemaUri, targetNamespace, out schema))
{
return schema;
}
else
{
DtdProcessing dtdProcessing = _readerSettings.DtdProcessing;
SetDtdProcessing(schemaDocument);
schema = Add(targetNamespace, ParseSchema(targetNamespace, schemaDocument));
_readerSettings.DtdProcessing = dtdProcessing; //reset dtdProcessing setting
return schema;
}
}
}
/// <summary>
/// Adds all the namespaces defined in the given schemas
/// (including their associated schemas) to this schemas.
/// </summary>
public void Add(XmlSchemaSet schemas)
{
ArgumentNullException.ThrowIfNull(schemas);
if (this == schemas)
{
return;
}
bool thisLockObtained = false;
bool schemasLockObtained = false;
try
{
SpinWait spinner = default;
while (true)
{
Monitor.TryEnter(InternalSyncObject, ref thisLockObtained);
if (thisLockObtained)
{
Monitor.TryEnter(schemas.InternalSyncObject, ref schemasLockObtained);
if (schemasLockObtained)
{
break;
}
else
{
Monitor.Exit(InternalSyncObject); //Give up this lock and try both again
thisLockObtained = false;
spinner.SpinOnce(); //Let the thread that holds the lock run
continue;
}
}
}
XmlSchema? currentSchema;
if (schemas.IsCompiled)
{
CopyFromCompiledSet(schemas);
}
else
{
bool remove = false;
string? tns = null;
foreach (XmlSchema? schema in schemas.SortedSchemas.Values)
{
tns = schema!.TargetNamespace ?? string.Empty;
if (_schemas.ContainsKey(schema.SchemaId) || FindSchemaByNSAndUrl(schema.BaseUri, tns, null) != null)
{ //Do not already existing url
continue;
}
currentSchema = Add(schema.TargetNamespace, schema);
if (currentSchema == null)
{
remove = true;
break;
}
}
//Remove all from the set if even one schema in the passed in set is not preprocessed.
if (remove)
{
foreach (XmlSchema? schema in schemas.SortedSchemas.Values)
{ //Remove all previously added schemas from the set
_schemas.Remove(schema!.SchemaId); //Might remove schema that was already there and was not added thru this operation
_schemaLocations.Remove(schema.BaseUri!);
}
}
}
}
finally
{ //release locks on sets
if (thisLockObtained)
{
Monitor.Exit(InternalSyncObject);
}
if (schemasLockObtained)
{
Monitor.Exit(schemas.InternalSyncObject);
}
}
}
public XmlSchema? Add(XmlSchema schema)
{
ArgumentNullException.ThrowIfNull(schema);
lock (InternalSyncObject)
{
if (_schemas.ContainsKey(schema.SchemaId))
{
return schema;
}
return Add(schema.TargetNamespace, schema);
}
}
public XmlSchema? Remove(XmlSchema schema)
{
return Remove(schema, true);
}
public bool RemoveRecursive(XmlSchema schemaToRemove)
{
ArgumentNullException.ThrowIfNull(schemaToRemove);
if (!_schemas.ContainsKey(schemaToRemove.SchemaId))
{
return false;
}
lock (InternalSyncObject)
{ //Need to lock here so that remove cannot be called while the set is being compiled
if (_schemas.ContainsKey(schemaToRemove.SchemaId))
{ //Need to check again
//Build disallowedNamespaces list
Hashtable disallowedNamespaces = new Hashtable();
disallowedNamespaces.Add(GetTargetNamespace(schemaToRemove), schemaToRemove);
string importedNS;
for (int i = 0; i < schemaToRemove.ImportedNamespaces.Count; i++)
{
importedNS = (string)schemaToRemove.ImportedNamespaces[i]!;
if (disallowedNamespaces[importedNS] == null)
{
disallowedNamespaces.Add(importedNS, importedNS);
}
}
//Removal list is all schemas imported by this schema directly or indirectly
//Need to check if other schemas in the set import schemaToRemove / any of its imports
ArrayList needToCheckSchemaList = new ArrayList();
for (int i = 0; i < _schemas.Count; i++)
{
XmlSchema mainSchema = (XmlSchema)_schemas.GetByIndex(i)!;
if (mainSchema == schemaToRemove ||
schemaToRemove.ImportedSchemas.Contains(mainSchema))
{
continue;
}
needToCheckSchemaList.Add(mainSchema);
}
for (int i = 0; i < needToCheckSchemaList.Count; i++)
{ //Perf: Not using nested foreach here
XmlSchema mainSchema = (XmlSchema)needToCheckSchemaList[i]!;
if (mainSchema.ImportedNamespaces.Count > 0)
{
foreach (string? tns in disallowedNamespaces.Keys)
{
if (mainSchema.ImportedNamespaces.Contains(tns))
{
SendValidationEvent(new XmlSchemaException(SR.Sch_SchemaNotRemoved, string.Empty), XmlSeverityType.Warning);
return false;
}
}
}
}
Remove(schemaToRemove, true);
for (int i = 0; i < schemaToRemove.ImportedSchemas.Count; ++i)
{
XmlSchema impSchema = (XmlSchema)schemaToRemove.ImportedSchemas[i]!;
Remove(impSchema, true);
}
return true;
}
}
return false;
}
public bool Contains(string? targetNamespace)
{
targetNamespace ??= string.Empty;
return _targetNamespaces[targetNamespace] != null;
}
public bool Contains(XmlSchema schema)
{
ArgumentNullException.ThrowIfNull(schema);
return _schemas.ContainsValue(schema);
}
public void Compile()
{
if (_isCompiled)
{
return;
}
if (_schemas.Count == 0)
{
ClearTables(); //Clear any previously present compiled state left by calling just Remove() on the set
_cachedCompiledInfo = new SchemaInfo();
_isCompiled = true;
_compileAll = false;
return;
}
lock (InternalSyncObject)
{
if (!_isCompiled)
{ //Locking before checking isCompiled to avoid problems with double locking
Compiler compiler = new Compiler(_nameTable, _eventHandler, _schemaForSchema, _compilationSettings);
SchemaInfo newCompiledInfo = new SchemaInfo();
int schemaIndex = 0;
if (!_compileAll)
{ //if we are not compiling everything again, Move the pre-compiled schemas to the compiler's tables
compiler.ImportAllCompiledSchemas(this);
}
try
{ //First thing to do in the try block is to acquire locks since finally will try to release them.
//If we don't acquire the locks first, and an exception occurs in the code before the locking code, then Threading.SynchronizationLockException will be thrown
//when attempting to release it in the finally block
XmlSchema currentSchema;
XmlSchema xmlNSSchema = Preprocessor.GetBuildInSchema();
for (schemaIndex = 0; schemaIndex < _schemas.Count; schemaIndex++)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(schemaIndex)!;
//Lock schema to be compiled
Monitor.Enter(currentSchema);
if (!currentSchema.IsPreprocessed)
{
SendValidationEvent(new XmlSchemaException(SR.Sch_SchemaNotPreprocessed, string.Empty), XmlSeverityType.Error);
_isCompiled = false;
return;
}
if (currentSchema.IsCompiledBySet)
{
if (!_compileAll)
{
continue;
}
else if ((object)currentSchema == (object)xmlNSSchema)
{ // prepare for xml namespace schema without cleanup
compiler.Prepare(currentSchema, false);
continue;
}
}
compiler.Prepare(currentSchema, true);
}
_isCompiled = compiler.Execute(this, newCompiledInfo);
if (_isCompiled)
{
if (!_compileAll)
{
newCompiledInfo.Add(_cachedCompiledInfo, _eventHandler); //Add all the items from the old to the new compiled object
}
_compileAll = false;
_cachedCompiledInfo = newCompiledInfo; //Replace the compiled info in the set after successful compilation
}
}
finally
{
//Release locks on all schemas
XmlSchema currentSchema;
if (schemaIndex == _schemas.Count)
{
schemaIndex--;
}
for (int i = schemaIndex; i >= 0; i--)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(i)!;
if (currentSchema == Preprocessor.GetBuildInSchema())
{ //dont re-set compiled flags for xml namespace schema
Monitor.Exit(currentSchema);
continue;
}
currentSchema.IsCompiledBySet = _isCompiled;
Monitor.Exit(currentSchema);
}
}
}
}
return;
}
public XmlSchema Reprocess(XmlSchema schema)
{
ArgumentNullException.ThrowIfNull(schema);
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Remove, Add and AddSchemaToSet
// methods. If you change anything here *make sure* to update Remove/Add/AddSchemaToSet method(s) accordingly.
// The only difference is that we don't touch .schemas collection here to not break a code like this:
// foreach (XmlSchema s in schemaset.schemas) { schemaset.Reprocess(s); }
// This is by purpose.
if (!_schemas.ContainsKey(schema.SchemaId))
{
throw new ArgumentException(SR.Sch_SchemaDoesNotExist, nameof(schema));
}
XmlSchema originalSchema = schema;
lock (InternalSyncObject)
{ //Lock set so that set cannot be compiled in another thread
// This code is copied from method:
// Remove(XmlSchema schema, bool forceCompile)
// If you changed anything here go and change the same in Remove(XmlSchema schema, bool forceCompile) method
#region Copied from Remove(XmlSchema schema, bool forceCompile)
RemoveSchemaFromGlobalTables(schema);
RemoveSchemaFromCaches(schema);
if (schema.BaseUri != null)
{
_schemaLocations.Remove(schema.BaseUri);
}
string tns = GetTargetNamespace(schema);
if (Schemas(tns).Count == 0)
{ //This is the only schema for that namespace
_targetNamespaces.Remove(tns);
}
_isCompiled = false;
_compileAll = true; //Force compilation of the whole set; This is when the set is not completely thread-safe
#endregion //Copied from Remove(XmlSchema schema, bool forceCompile)
// This code is copied from method:
// Add(string targetNamespace, XmlSchema schema)
// If you changed anything here go and change the same in Add(string targetNamespace, XmlSchema schema) method
#region Copied from Add(string targetNamespace, XmlSchema schema)
if (schema.ErrorCount != 0)
{ //Schema with parsing errors cannot be loaded
return originalSchema;
}
if (PreprocessSchema(ref schema, schema.TargetNamespace))
{ //No perf opt for already compiled schemas
// This code is copied from method:
// AddSchemaToSet(XmlSchema schema)
// If you changed anything here go and change the same in AddSchemaToSet(XmlSchema schema) method
#region Copied from AddSchemaToSet(XmlSchema schema)
//Add to targetNamespaces table
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{ //Once preprocessed external schemas property is set
XmlSchema s = (XmlSchema)schema.ImportedSchemas[i]!;
if (!_schemas.ContainsKey(s.SchemaId))
{
_schemas.Add(s.SchemaId, s);
}
tns = GetTargetNamespace(s);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
}
#endregion //Copied from AddSchemaToSet(XmlSchema schema)
return schema;
}
#endregion // Copied from Add(string targetNamespace, XmlSchema schema)
return originalSchema;
}
}
public void CopyTo(XmlSchema[] schemas, int index)
{
ArgumentNullException.ThrowIfNull(schemas);
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfGreaterThan(index, schemas.Length - 1);
_schemas.Values.CopyTo(schemas, index);
}
public ICollection Schemas()
{
return _schemas.Values;
}
public ICollection Schemas(string? targetNamespace)
{
ArrayList tnsSchemas = new ArrayList();
XmlSchema currentSchema;
targetNamespace ??= string.Empty;
for (int i = 0; i < _schemas.Count; i++)
{
currentSchema = (XmlSchema)_schemas.GetByIndex(i)!;
if (GetTargetNamespace(currentSchema) == targetNamespace)
{
tnsSchemas.Add(currentSchema);
}
}
return tnsSchemas;
}
//Internal Methods
private XmlSchema? Add(string? targetNamespace, XmlSchema? schema)
{
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess
// method. If you change anything here *make sure* to update Reprocess method accordingly.
if (schema == null || schema.ErrorCount != 0)
{ //Schema with parsing errors cannot be loaded
return null;
}
// This code is copied to method:
// Reprocess(XmlSchema schema)
// If you changed anything here go and change the same in Reprocess(XmlSchema schema) method
if (PreprocessSchema(ref schema, targetNamespace))
{ //No perf opt for already compiled schemas
AddSchemaToSet(schema);
_isCompiled = false;
return schema;
}
return null;
}
#if TRUST_COMPILE_STATE
private void AddCompiledSchema(XmlSchema schema) {
if (schema.IsCompiledBySet ) { //trust compiled state always if it is not a chameleon schema
VerifyTables();
SchemaInfo newCompiledInfo = new SchemaInfo();
XmlSchemaObjectTable substitutionGroupsTable = null;
if (!AddToCompiledInfo(schema, newCompiledInfo, ref substitutionGroupsTable)) { //Error while adding main schema
return null;
}
foreach (XmlSchema impSchema in schema.ImportedSchemas) {
if (!AddToCompiledInfo(impSchema, newCompiledInfo, ref substitutionGroupsTable)) { //Error while adding imports
return null;
}
}
newCompiledInfo.Add(cachedCompiledInfo, eventHandler); //Add existing compiled info
cachedCompiledInfo = newCompiledInfo;
if (substitutionGroupsTable != null) {
ProcessNewSubstitutionGroups(substitutionGroupsTable, true);
}
if (schemas.Count == 0) { //If its the first compiled schema being added, then set doesnt need to be compiled
isCompiled = true;
compileAll = false;
}
AddSchemaToSet(schema);
return schema;
}
}
private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref XmlSchemaObjectTable substTable) {
//Add schema's compiled tables to the set
if (schema.BaseUri != null && schemaLocations[schema.BaseUri] == null) { //Update schemaLocations table
schemaLocations.Add(schema.BaseUri, schema);
}
foreach (XmlSchemaElement element in schema.Elements.Values) {
if (!AddToTable(elements, element.QualifiedName, element)) {
RemoveSchemaFromGlobalTables(schema);
return false;
}
XmlQualifiedName head = element.SubstitutionGroup;
if (!head.IsEmpty) {
substTable ??= new XmlSchemaObjectTable();
XmlSchemaSubstitutionGroup substitutionGroup = (XmlSchemaSubstitutionGroup)substTable[head];
if (substitutionGroup == null) {
substitutionGroup = new XmlSchemaSubstitutionGroup();
substitutionGroup.Examplar = head;
substTable.Add(head, substitutionGroup);
}
ArrayList members = substitutionGroup.Members;
if (!members.Contains(element)) { //Members might contain element if the same schema is included and imported through different paths. Imp, hence will be added to set directly
members.Add(element);
}
}
}
foreach (XmlSchemaAttribute attribute in schema.Attributes.Values) {
if (!AddToTable(attributes, attribute.QualifiedName, attribute)) {
RemoveSchemaFromGlobalTables(schema);
return false;
}
}
foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values) {
if (!AddToTable(schemaTypes, schemaType.QualifiedName, schemaType)) {
RemoveSchemaFromGlobalTables(schema);
return false;
}
}
schema.AddCompiledInfo(newCompiledInfo);
return true;
}
#endif
//For use by the validator when loading schemaLocations in the instance
internal void Add(string? targetNamespace, XmlReader reader, Hashtable validatedNamespaces)
{
ArgumentNullException.ThrowIfNull(reader);
targetNamespace ??= string.Empty;
if (validatedNamespaces[targetNamespace] != null)
{
if (FindSchemaByNSAndUrl(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, null) != null)
{
return;
}
else
{
throw new XmlSchemaException(SR.Sch_ComponentAlreadySeenForNS, targetNamespace);
}
}
//Not locking set as this will not be accessible outside the validator
XmlSchema? schema;
if (IsSchemaLoaded(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, out _))
{
return;
}
else
{ //top-level schema not present for same url
schema = ParseSchema(targetNamespace, reader);
//Store the previous locations
DictionaryEntry[] oldLocations = new DictionaryEntry[_schemaLocations.Count];
_schemaLocations.CopyTo(oldLocations, 0);
//Add to set
Add(targetNamespace, schema!);
if (schema!.ImportedSchemas.Count > 0)
{ //Check imports
string? tns;
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{
XmlSchema impSchema = (XmlSchema)schema.ImportedSchemas[i]!;
tns = impSchema.TargetNamespace ?? string.Empty;
if (validatedNamespaces[tns] != null && (FindSchemaByNSAndUrl(impSchema.BaseUri, tns, oldLocations) == null))
{
RemoveRecursive(schema);
throw new XmlSchemaException(SR.Sch_ComponentAlreadySeenForNS, tns);
}
}
}
}
}
internal XmlSchema? FindSchemaByNSAndUrl(Uri? schemaUri, string ns, DictionaryEntry[]? locationsTable)
{
if (schemaUri == null || schemaUri.OriginalString.Length == 0)
{
return null;
}
XmlSchema? schema = null;
if (locationsTable == null)
{
schema = (XmlSchema)_schemaLocations[schemaUri]!;
}
else
{
for (int i = 0; i < locationsTable.Length; i++)
{
if (schemaUri.Equals(locationsTable[i].Key))
{
schema = (XmlSchema)locationsTable[i].Value!;
break;
}
}
}
if (schema != null)
{
Debug.Assert(ns != null);
string tns = schema.TargetNamespace ?? string.Empty;
if (tns == ns)
{
return schema;
}
else if (tns.Length == 0)
{ //There could be a chameleon for same ns
// It is OK to pass in the schema we have found so far, since it must have the schemaUri we're looking for
// (we found it that way above) and it must be the original chameleon schema (the one without target ns)
// as we don't add the chameleon copies into the locations tables above.
Debug.Assert(schema.BaseUri!.Equals(schemaUri));
ChameleonKey cKey = new ChameleonKey(ns, schema);
schema = (XmlSchema)_chameleonSchemas[cKey]!; //Need not clone if a schema for that namespace already exists
}
else
{
schema = null;
}
}
return schema;
}
private void SetDtdProcessing(XmlReader reader)
{
if (reader.Settings != null)
{
_readerSettings.DtdProcessing = reader.Settings.DtdProcessing;
}
else
{
XmlTextReader? v1Reader = reader as XmlTextReader;
if (v1Reader != null)
{
_readerSettings.DtdProcessing = v1Reader.DtdProcessing;
}
}
}
private void AddSchemaToSet(XmlSchema schema)
{
// Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess
// method. If you change anything here *make sure* to update Reprocess method accordingly.
_schemas.Add(schema.SchemaId, schema);
//Add to targetNamespaces table
// This code is copied to method:
// Reprocess(XmlSchema schema)
// If you changed anything here go and change the same in Reprocess(XmlSchema schema) method
#region This code is copied to Reprocess(XmlSchema schema) method
string tns = GetTargetNamespace(schema);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
for (int i = 0; i < schema.ImportedSchemas.Count; ++i)
{ //Once preprocessed external schemas property is set
XmlSchema s = (XmlSchema)schema.ImportedSchemas[i]!;
if (!_schemas.ContainsKey(s.SchemaId))
{
_schemas.Add(s.SchemaId, s);
}
tns = GetTargetNamespace(s);
if (_targetNamespaces[tns] == null)
{
_targetNamespaces.Add(tns, tns);
}
if (_schemaForSchema == null && tns == XmlReservedNs.NsXs && schema.SchemaTypes[DatatypeImplementation.QnAnyType] != null)
{ //it has xs:anyType
_schemaForSchema = schema;
}
}
#endregion // This code is copied to Reprocess(XmlSchema schema) method
}
private void ProcessNewSubstitutionGroups(XmlSchemaObjectTable substitutionGroupsTable, bool resolve)
{
foreach (XmlSchemaSubstitutionGroup? substGroup in substitutionGroupsTable.Values)
{
if (resolve)
{ //Resolve substitutionGroups within this schema
ResolveSubstitutionGroup(substGroup!, substitutionGroupsTable);
}
//Add or Merge new substitutionGroups with those that already exist in the set
XmlQualifiedName head = substGroup!.Examplar;
XmlSchemaSubstitutionGroup? oldSubstGroup = (XmlSchemaSubstitutionGroup?)substitutionGroups![head];
if (oldSubstGroup != null)
{
for (int i = 0; i < substGroup.Members.Count; ++i)
{
if (!oldSubstGroup.Members.Contains(substGroup.Members[i]))
{
oldSubstGroup.Members.Add(substGroup.Members[i]);
}
}
}
else
{
AddToTable(substitutionGroups, head, substGroup);
}
}
}
private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGroup, XmlSchemaObjectTable substTable)
{
List<XmlSchemaElement>? newMembers = null;
XmlSchemaElement headElement = (XmlSchemaElement)elements![substitutionGroup.Examplar]!;
if (substitutionGroup.Members.Contains(headElement))
{// already checked
return;
}
for (int i = 0; i < substitutionGroup.Members.Count; ++i)
{
XmlSchemaElement element = (XmlSchemaElement)substitutionGroup.Members[i]!;
//Chain to other head's that are members of this head's substGroup
XmlSchemaSubstitutionGroup? g = (XmlSchemaSubstitutionGroup?)substTable[element.QualifiedName];
if (g != null)
{
ResolveSubstitutionGroup(g, substTable);
for (int j = 0; j < g.Members.Count; ++j)
{
XmlSchemaElement element1 = (XmlSchemaElement)g.Members[j]!;