File: ServiceModelExtensionCollectionElement.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3~deb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,284,488 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (645 lines) | stat: -rw-r--r-- 25,774 bytes parent folder | download | duplicates (8)
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
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace System.ServiceModel.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Diagnostics;
    using System.Runtime;
    using System.Runtime.Diagnostics;
    using System.Security;
    using System.ServiceModel;
    using System.ServiceModel.Diagnostics;
    using System.Xml;

    public abstract class ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> : ConfigurationElement, ICollection<TServiceModelExtensionElement>, IConfigurationContextProviderInternal
        where TServiceModelExtensionElement : ServiceModelExtensionElement
    {
        [Fx.Tag.SecurityNote(Critical = "Stores information used in a security decision.")]
        [SecurityCritical]
        EvaluationContextHelper contextHelper;

        string extensionCollectionName = null;
        bool modified = false;
        List<TServiceModelExtensionElement> items = null;
        ConfigurationPropertyCollection properties = null;

        internal ServiceModelExtensionCollectionElement(string extensionCollectionName)
        {
            this.extensionCollectionName = extensionCollectionName;
        }

        public TServiceModelExtensionElement this[int index]
        {
            get { return this.Items[index]; }
        }

        public TServiceModelExtensionElement this[Type extensionType]
        {
            get
            {
                if (extensionType == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("extensionType");
                }

                if (!this.CollectionElementBaseType.IsAssignableFrom(extensionType))
                {
#pragma warning disable 56506 //Microsoft; Variable 'extensionType' checked for null previously
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("extensionType",
                        SR.GetString(SR.ConfigInvalidExtensionType,
                        extensionType.ToString(),
                        this.CollectionElementBaseType.FullName,
                        this.extensionCollectionName));
#pragma warning restore
                }
                TServiceModelExtensionElement retval = null;

                foreach (TServiceModelExtensionElement collectionElement in this)
                {
                    if (null != collectionElement)
                    {
                        if (collectionElement.GetType() == extensionType)
                        {
                            retval = collectionElement;
                        }
                    }
                }

                return retval;
            }
        }

        public int Count
        {
            get { return this.Items.Count; }
        }

        bool ICollection<TServiceModelExtensionElement>.IsReadOnly
        {
            get { return this.IsReadOnly(); }
        }

        internal List<TServiceModelExtensionElement> Items
        {
            get
            {
                if (this.items == null)
                {
                    this.items = new List<TServiceModelExtensionElement>();
                }
                return this.items;
            }
        }

        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                if (this.properties == null)
                {
                    this.properties = new ConfigurationPropertyCollection();
                }
                return this.properties;
            }
        }

        public virtual void Add(TServiceModelExtensionElement element)
        {
            if (this.IsReadOnly())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
            }
            if (element == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
            }

            element.ExtensionCollectionName = this.extensionCollectionName;

            if (this.Contains(element))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("element", SR.GetString(SR.ConfigDuplicateKey, element.ConfigurationElementName));
            }
            else if (!this.CanAdd(element))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("element",
                    SR.GetString(SR.ConfigElementTypeNotAllowed,
                    element.ConfigurationElementName,
                    this.extensionCollectionName));
            }
            else
            {
                element.ContainingEvaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
                ConfigurationProperty configProperty = new ConfigurationProperty(element.ConfigurationElementName, element.GetType(), null);
                this.Properties.Add(configProperty);
                this[configProperty] = element;
                this.Items.Add(element);
                this.modified = true;
            }
        }

        internal void AddItem(TServiceModelExtensionElement element)
        {
            if (this.IsReadOnly())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
            }
            element.ExtensionCollectionName = this.extensionCollectionName;
            element.ContainingEvaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
            this.Items.Add(element);
            this.modified = true;
        }

        public virtual bool CanAdd(TServiceModelExtensionElement element)
        {
            if (null == element)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
            }

            bool retval = false;
            Type elementType = element.GetType();

            if (!this.IsReadOnly())
            {
                if (!this.ContainsKey(elementType))
                {
                    retval = element.CanAdd(this.extensionCollectionName, ConfigurationHelpers.GetEvaluationContext(this));
                }
                else if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning,
                        TraceCode.ExtensionElementAlreadyExistsInCollection,
                        SR.GetString(SR.TraceCodeExtensionElementAlreadyExistsInCollection),
                        this.CreateCanAddRecord(this[elementType]), this, null);
                }
            }
            else if (DiagnosticUtility.ShouldTraceWarning)
            {
                TraceUtility.TraceEvent(TraceEventType.Warning,
                    TraceCode.ConfigurationIsReadOnly,
                    SR.GetString(SR.TraceCodeConfigurationIsReadOnly),
                    null, this, null);
            }
            return retval;
        }

        DictionaryTraceRecord CreateCanAddRecord(TServiceModelExtensionElement element)
        {
            return this.CreateCanAddRecord(element, new Dictionary<string, string>(3));
        }

        DictionaryTraceRecord CreateCanAddRecord(TServiceModelExtensionElement element, Dictionary<string, string> values)
        {
            values["ElementType"] = System.Runtime.Diagnostics.DiagnosticTraceBase.XmlEncode(typeof(TServiceModelExtensionElement).AssemblyQualifiedName);
            values["ConfiguredSectionName"] = element.ConfigurationElementName;
            values["CollectionName"] = ConfigurationStrings.ExtensionsSectionPath + "/" + this.extensionCollectionName;
            return new DictionaryTraceRecord(values);
        }

        public void Clear()
        {
            if (this.IsReadOnly())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
            }
            if (this.Properties.Count > 0)
            {
                this.modified = true;
            }

            List<string> propertiesToRemove = new List<string>(this.Items.Count);
            foreach (TServiceModelExtensionElement item in this.Items)
            {
                propertiesToRemove.Add(item.ConfigurationElementName);
            }

            this.Items.Clear();

            foreach (string name in propertiesToRemove)
            {
                this.Properties.Remove(name);
            }
        }

        internal Type CollectionElementBaseType
        {
            get { return typeof(TServiceModelExtensionElement); }
        }

        public bool Contains(TServiceModelExtensionElement element)
        {
            if (element == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
            }
            return this.ContainsKey(element.GetType());
        }

        public bool ContainsKey(Type elementType)
        {
            if (elementType == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementType");
            }
            return (this[elementType] != null);
        }

        public bool ContainsKey(string elementName)
        {
            if (string.IsNullOrEmpty(elementName))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementName");
            }
            bool retval = false;
            foreach (TServiceModelExtensionElement element in this)
            {
                if (null != element)
                {
                    string configuredSectionName = element.ConfigurationElementName;
                    if (configuredSectionName.Equals(elementName, StringComparison.Ordinal))
                    {
                        retval = true;
                        break;
                    }
                }
            }
            return retval;
        }

        public void CopyTo(TServiceModelExtensionElement[] elements, int start)
        {
            if (elements == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elements");
            }
            if (start < 0 || start >= elements.Length)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("start",
                    SR.GetString(SR.ConfigInvalidStartValue,
                    elements.Length - 1,
                    start));
            }

            foreach (TServiceModelExtensionElement element in this)
            {
                if (null != element)
                {
                    string configuredSectionName = element.ConfigurationElementName;

                    TServiceModelExtensionElement copiedElement = this.CreateNewSection(configuredSectionName);
                    if ((copiedElement != null) && (start < elements.Length))
                    {
                        copiedElement.CopyFrom(element);
                        elements[start] = copiedElement;
                        ++start;
                    }
                }
            }
        }

        /// <summary>
        /// Returns the extension element, or null if the type cannot be loaded in certain situations (see the code for details).
        /// </summary>
        TServiceModelExtensionElement CreateNewSection(string name)
        {
            if (this.ContainsKey(name) && !(name == ConfigurationStrings.Clear || name == ConfigurationStrings.Remove))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigDuplicateItem,
                    name,
                    this.GetType().Name),
                    this.ElementInformation.Source,
                    this.ElementInformation.LineNumber));
            }

            TServiceModelExtensionElement retval = null;

            Type elementType;
            ContextInformation evaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
            try
            {
                elementType = GetExtensionType(evaluationContext, name);
            }
            catch (ConfigurationErrorsException e)
            {
                // Work-around for bug 219506@CSDMain: if the extension type cannot be loaded, we'll ignore 
                // the exception when running in win8 app container and reading from machine.config.
                if (System.ServiceModel.Channels.AppContainerInfo.IsRunningInAppContainer && evaluationContext.IsMachineLevel)
                {
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    return null;
                }
                else
                {
                    throw;
                }
            }

            if (null != elementType)
            {
                if (this.CollectionElementBaseType.IsAssignableFrom(elementType))
                {
                    retval = (TServiceModelExtensionElement)Activator.CreateInstance(elementType);
                    retval.ExtensionCollectionName = this.extensionCollectionName;
                    retval.ConfigurationElementName = name;
                    retval.InternalInitializeDefault();
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidExtensionElement,
                        name,
                        this.CollectionElementBaseType.FullName),
                        this.ElementInformation.Source,
                        this.ElementInformation.LineNumber));
                }
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidExtensionElementName,
                    name,
                    this.extensionCollectionName),
                    this.ElementInformation.Source,
                    this.ElementInformation.LineNumber));
            }

            return retval;
        }

        [Fx.Tag.SecurityNote(Critical = "Calls SecurityCritical method UnsafeLookupCollection which elevates in order to load config.",
            Safe = "Does not leak any config objects.")]
        [SecuritySafeCritical]
        Type GetExtensionType(ContextInformation evaluationContext, string name)
        {
            ExtensionElementCollection collection = ExtensionsSection.UnsafeLookupCollection(this.extensionCollectionName, evaluationContext);
            if (collection.ContainsKey(name))
            {
                ExtensionElement element = collection[name];
                Type elementType = Type.GetType(element.Type, false);
                if (null == elementType)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidType, element.Type, element.Name),
                        this.ElementInformation.Source,
                        this.ElementInformation.LineNumber));
                }
                return elementType;
            }
            return null;
        }

        internal void MergeWith(List<TServiceModelExtensionElement> parentExtensionElements)
        {
            ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>.Merge(parentExtensionElements, this);
            this.Clear();
            foreach (TServiceModelExtensionElement parentExtensionElement in parentExtensionElements)
            {
                this.Add(parentExtensionElement);
            }
        }

        static void Merge(List<TServiceModelExtensionElement> parentExtensionElements, IEnumerable<TServiceModelExtensionElement> childExtensionElements)
        {
            foreach (TServiceModelExtensionElement childExtensionElement in childExtensionElements)
            {
                if (childExtensionElement is ClearBehaviorElement)
                {
                    parentExtensionElements.Clear();
                }
                else if (childExtensionElement is RemoveBehaviorElement)
                {
                    string childExtensionElementName = (childExtensionElement as RemoveBehaviorElement).Name;
                    if (!string.IsNullOrEmpty(childExtensionElementName))
                    {
                        parentExtensionElements.RemoveAll(element => element != null && element.ConfigurationElementName == childExtensionElementName);
                    }
                }
                else
                {
                    Type childExtensionElementType = childExtensionElement.GetType();
                    parentExtensionElements.RemoveAll(element => element != null && element.GetType() == childExtensionElementType);
                    parentExtensionElements.Add(childExtensionElement);
                }
            }
        }

        [Fx.Tag.SecurityNote(Critical = "Uses the critical helper SetIsPresent.",
            Safe = "Controls how/when SetIsPresent is used, not arbitrarily callable from PT (method is protected and class is sealed).")]
        [SecuritySafeCritical]
        protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
        {
            SetIsPresent();
            DeserializeElementCore(reader);
        }

        private void DeserializeElementCore(XmlReader reader)
        {
            if (reader.HasAttributes && 0 < reader.AttributeCount)
            {
                while (reader.MoveToNextAttribute())
                {
                    if (this.Properties.Contains(reader.Name))
                    {
                        this[reader.Name] = this.Properties[reader.Name].Converter.ConvertFromString(reader.Value);
                    }
                    else
                    {
                        this.OnDeserializeUnrecognizedAttribute(reader.Name, reader.Value);
                    }
                }
            }

            if (XmlNodeType.Element != reader.NodeType)
            {
                reader.MoveToElement();
            }

            XmlReader subTree = reader.ReadSubtree();
            if (subTree.Read())
            {
                while (subTree.Read())
                {
                    if (XmlNodeType.Element == subTree.NodeType)
                    {
                        // Create new child element and add it to the property collection to
                        // associate the element with an EvaluationContext.  Then deserialize
                        // XML further to set actual values.
                        TServiceModelExtensionElement collectionElement = this.CreateNewSection(subTree.Name);
                        if (collectionElement != null)
                        {
                            this.Add(collectionElement);
                            collectionElement.DeserializeInternal(subTree, false);
                        }
                    }
                }
            }
        }

        [Fx.Tag.SecurityNote(Critical = "Calls ConfigurationHelpers.SetIsPresent which elevates in order to set a property.")]
        [SecurityCritical]
        void SetIsPresent()
        {
            ConfigurationHelpers.SetIsPresent(this);
        }

        public System.Collections.Generic.IEnumerator<TServiceModelExtensionElement> GetEnumerator()
        {
            for (int index = 0; index < this.Items.Count; ++index)
            {
                TServiceModelExtensionElement currentValue = items[index];
                yield return currentValue;
            }
        }

        protected override bool IsModified()
        {
            bool retval = this.modified;
            if (!retval)
            {
                for (int i = 0; i < this.Items.Count; i++)
                {
                    TServiceModelExtensionElement element = this.Items[i];
                    if (element.IsModifiedInternal())
                    {
                        retval = true;
                        break;
                    }
                }
            }
            return retval;
        }

        protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
        {
            // When this is used as a DefaultCollection (i.e. CommonBehaviors)
            // the element names are unrecognized by the parent tag, which delegates
            // to the collection's OnDeserializeUnrecognizedElement.  In this case,
            // an unrecognized element may be expected, simply try to deserialize the
            // element and let DeserializeElement() throw the appropriate exception if
            // an error is hit.
            this.DeserializeElement(reader, false);
            return true;
        }

        public bool Remove(TServiceModelExtensionElement element)
        {
            if (element == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
            }
            bool retval = false;
            if (this.Contains(element))
            {
                string configuredSectionName = element.ConfigurationElementName;

                TServiceModelExtensionElement existingElement = (TServiceModelExtensionElement)this[element.GetType()];
                this.Items.Remove(existingElement);
                this.Properties.Remove(configuredSectionName);
                this.modified = true;
                retval = true;
            }
            return retval;
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses critical field contextHelper.")]
        [SecurityCritical]
        protected override void Reset(ConfigurationElement parentElement)
        {
            ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> collection =
                (ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>)parentElement;
            foreach (TServiceModelExtensionElement collectionElement in collection.Items)
            {
                this.Items.Add(collectionElement);
            }
            // Update my properties
            this.UpdateProperties(collection);

            this.contextHelper.OnReset(parentElement);

            base.Reset(parentElement);
        }

        protected override void ResetModified()
        {
            for (int i = 0; i < this.Items.Count; i++)
            {
                TServiceModelExtensionElement collectionElement = this.Items[i];
                collectionElement.ResetModifiedInternal();
            }
            this.modified = false;
        }

        protected void SetIsModified()
        {
            this.modified = true;
        }

        protected override void SetReadOnly()
        {
            base.SetReadOnly();

            for (int i = 0; i < this.Items.Count; i++)
            {
                TServiceModelExtensionElement element = this.Items[i];
                element.SetReadOnlyInternal();
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        protected override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
        {
            if (sourceElement == null)
            {
                return;
            }

            ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> sourceCollectionElement = (ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>)sourceElement;

            this.UpdateProperties(sourceCollectionElement);
            base.Unmerge(sourceElement, parentElement, saveMode);
        }

        void UpdateProperties(ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> sourceElement)
        {
            foreach (ConfigurationProperty property in sourceElement.Properties)
            {
                if (!this.Properties.Contains(property.Name))
                {
                    this.Properties.Add(property);
                }
            }
            foreach (TServiceModelExtensionElement extension in this.Items)
            {
                if (extension is ClearBehaviorElement || extension is RemoveBehaviorElement)
                    continue;

                string configuredSectionName = extension.ConfigurationElementName;
                if (!this.Properties.Contains(configuredSectionName))
                {
                    ConfigurationProperty configProperty = new ConfigurationProperty(configuredSectionName, extension.GetType(), null);
                    this.Properties.Add(configProperty);
                }
            }
        }

        ContextInformation IConfigurationContextProviderInternal.GetEvaluationContext()
        {
            return this.EvaluationContext;
        }

        [Fx.Tag.SecurityNote(Critical = "Accesses critical field contextHelper.",
            Miscellaneous = "RequiresReview -- the return value will be used for a security decision -- see comment in interface definition.")]
        [SecurityCritical]
        ContextInformation IConfigurationContextProviderInternal.GetOriginalEvaluationContext()
        {
            return this.contextHelper.GetOriginalContext(this);
        }
    }
}