ServiceModelExtensionCollectionElement.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Configuration
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Configuration;
  9. using System.Diagnostics;
  10. using System.Runtime;
  11. using System.Runtime.Diagnostics;
  12. using System.Security;
  13. using System.ServiceModel;
  14. using System.ServiceModel.Diagnostics;
  15. using System.Xml;
  16. public abstract class ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> : ConfigurationElement, ICollection<TServiceModelExtensionElement>, IConfigurationContextProviderInternal
  17. where TServiceModelExtensionElement : ServiceModelExtensionElement
  18. {
  19. [Fx.Tag.SecurityNote(Critical = "Stores information used in a security decision.")]
  20. [SecurityCritical]
  21. EvaluationContextHelper contextHelper;
  22. string extensionCollectionName = null;
  23. bool modified = false;
  24. List<TServiceModelExtensionElement> items = null;
  25. ConfigurationPropertyCollection properties = null;
  26. internal ServiceModelExtensionCollectionElement(string extensionCollectionName)
  27. {
  28. this.extensionCollectionName = extensionCollectionName;
  29. }
  30. public TServiceModelExtensionElement this[int index]
  31. {
  32. get { return this.Items[index]; }
  33. }
  34. public TServiceModelExtensionElement this[Type extensionType]
  35. {
  36. get
  37. {
  38. if (extensionType == null)
  39. {
  40. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("extensionType");
  41. }
  42. if (!this.CollectionElementBaseType.IsAssignableFrom(extensionType))
  43. {
  44. #pragma warning disable 56506 //[....]; Variable 'extensionType' checked for null previously
  45. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("extensionType",
  46. SR.GetString(SR.ConfigInvalidExtensionType,
  47. extensionType.ToString(),
  48. this.CollectionElementBaseType.FullName,
  49. this.extensionCollectionName));
  50. #pragma warning restore
  51. }
  52. TServiceModelExtensionElement retval = null;
  53. foreach (TServiceModelExtensionElement collectionElement in this)
  54. {
  55. if (null != collectionElement)
  56. {
  57. if (collectionElement.GetType() == extensionType)
  58. {
  59. retval = collectionElement;
  60. }
  61. }
  62. }
  63. return retval;
  64. }
  65. }
  66. public int Count
  67. {
  68. get { return this.Items.Count; }
  69. }
  70. bool ICollection<TServiceModelExtensionElement>.IsReadOnly
  71. {
  72. get { return this.IsReadOnly(); }
  73. }
  74. internal List<TServiceModelExtensionElement> Items
  75. {
  76. get
  77. {
  78. if (this.items == null)
  79. {
  80. this.items = new List<TServiceModelExtensionElement>();
  81. }
  82. return this.items;
  83. }
  84. }
  85. protected override ConfigurationPropertyCollection Properties
  86. {
  87. get
  88. {
  89. if (this.properties == null)
  90. {
  91. this.properties = new ConfigurationPropertyCollection();
  92. }
  93. return this.properties;
  94. }
  95. }
  96. public virtual void Add(TServiceModelExtensionElement element)
  97. {
  98. if (this.IsReadOnly())
  99. {
  100. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
  101. }
  102. if (element == null)
  103. {
  104. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
  105. }
  106. element.ExtensionCollectionName = this.extensionCollectionName;
  107. if (this.Contains(element))
  108. {
  109. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("element", SR.GetString(SR.ConfigDuplicateKey, element.ConfigurationElementName));
  110. }
  111. else if (!this.CanAdd(element))
  112. {
  113. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("element",
  114. SR.GetString(SR.ConfigElementTypeNotAllowed,
  115. element.ConfigurationElementName,
  116. this.extensionCollectionName));
  117. }
  118. else
  119. {
  120. element.ContainingEvaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
  121. ConfigurationProperty configProperty = new ConfigurationProperty(element.ConfigurationElementName, element.GetType(), null);
  122. this.Properties.Add(configProperty);
  123. this[configProperty] = element;
  124. this.Items.Add(element);
  125. this.modified = true;
  126. }
  127. }
  128. internal void AddItem(TServiceModelExtensionElement element)
  129. {
  130. if (this.IsReadOnly())
  131. {
  132. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
  133. }
  134. element.ExtensionCollectionName = this.extensionCollectionName;
  135. element.ContainingEvaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
  136. this.Items.Add(element);
  137. this.modified = true;
  138. }
  139. public virtual bool CanAdd(TServiceModelExtensionElement element)
  140. {
  141. if (null == element)
  142. {
  143. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
  144. }
  145. bool retval = false;
  146. Type elementType = element.GetType();
  147. if (!this.IsReadOnly())
  148. {
  149. if (!this.ContainsKey(elementType))
  150. {
  151. retval = element.CanAdd(this.extensionCollectionName, ConfigurationHelpers.GetEvaluationContext(this));
  152. }
  153. else if (DiagnosticUtility.ShouldTraceWarning)
  154. {
  155. TraceUtility.TraceEvent(TraceEventType.Warning,
  156. TraceCode.ExtensionElementAlreadyExistsInCollection,
  157. SR.GetString(SR.TraceCodeExtensionElementAlreadyExistsInCollection),
  158. this.CreateCanAddRecord(this[elementType]), this, null);
  159. }
  160. }
  161. else if (DiagnosticUtility.ShouldTraceWarning)
  162. {
  163. TraceUtility.TraceEvent(TraceEventType.Warning,
  164. TraceCode.ConfigurationIsReadOnly,
  165. SR.GetString(SR.TraceCodeConfigurationIsReadOnly),
  166. null, this, null);
  167. }
  168. return retval;
  169. }
  170. DictionaryTraceRecord CreateCanAddRecord(TServiceModelExtensionElement element)
  171. {
  172. return this.CreateCanAddRecord(element, new Dictionary<string, string>(3));
  173. }
  174. DictionaryTraceRecord CreateCanAddRecord(TServiceModelExtensionElement element, Dictionary<string, string> values)
  175. {
  176. values["ElementType"] = System.Runtime.Diagnostics.DiagnosticTraceBase.XmlEncode(typeof(TServiceModelExtensionElement).AssemblyQualifiedName);
  177. values["ConfiguredSectionName"] = element.ConfigurationElementName;
  178. values["CollectionName"] = ConfigurationStrings.ExtensionsSectionPath + "/" + this.extensionCollectionName;
  179. return new DictionaryTraceRecord(values);
  180. }
  181. public void Clear()
  182. {
  183. if (this.IsReadOnly())
  184. {
  185. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
  186. }
  187. if (this.Properties.Count > 0)
  188. {
  189. this.modified = true;
  190. }
  191. List<string> propertiesToRemove = new List<string>(this.Items.Count);
  192. foreach (TServiceModelExtensionElement item in this.Items)
  193. {
  194. propertiesToRemove.Add(item.ConfigurationElementName);
  195. }
  196. this.Items.Clear();
  197. foreach (string name in propertiesToRemove)
  198. {
  199. this.Properties.Remove(name);
  200. }
  201. }
  202. internal Type CollectionElementBaseType
  203. {
  204. get { return typeof(TServiceModelExtensionElement); }
  205. }
  206. public bool Contains(TServiceModelExtensionElement element)
  207. {
  208. if (element == null)
  209. {
  210. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
  211. }
  212. return this.ContainsKey(element.GetType());
  213. }
  214. public bool ContainsKey(Type elementType)
  215. {
  216. if (elementType == null)
  217. {
  218. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementType");
  219. }
  220. return (this[elementType] != null);
  221. }
  222. public bool ContainsKey(string elementName)
  223. {
  224. if (string.IsNullOrEmpty(elementName))
  225. {
  226. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementName");
  227. }
  228. bool retval = false;
  229. foreach (TServiceModelExtensionElement element in this)
  230. {
  231. if (null != element)
  232. {
  233. string configuredSectionName = element.ConfigurationElementName;
  234. if (configuredSectionName.Equals(elementName, StringComparison.Ordinal))
  235. {
  236. retval = true;
  237. break;
  238. }
  239. }
  240. }
  241. return retval;
  242. }
  243. public void CopyTo(TServiceModelExtensionElement[] elements, int start)
  244. {
  245. if (elements == null)
  246. {
  247. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elements");
  248. }
  249. if (start < 0 || start >= elements.Length)
  250. {
  251. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("start",
  252. SR.GetString(SR.ConfigInvalidStartValue,
  253. elements.Length - 1,
  254. start));
  255. }
  256. foreach (TServiceModelExtensionElement element in this)
  257. {
  258. if (null != element)
  259. {
  260. string configuredSectionName = element.ConfigurationElementName;
  261. TServiceModelExtensionElement copiedElement = this.CreateNewSection(configuredSectionName);
  262. if ((copiedElement != null) && (start < elements.Length))
  263. {
  264. copiedElement.CopyFrom(element);
  265. elements[start] = copiedElement;
  266. ++start;
  267. }
  268. }
  269. }
  270. }
  271. /// <summary>
  272. /// Returns the extension element, or null if the type cannot be loaded in certain situations (see the code for details).
  273. /// </summary>
  274. TServiceModelExtensionElement CreateNewSection(string name)
  275. {
  276. if (this.ContainsKey(name) && !(name == ConfigurationStrings.Clear || name == ConfigurationStrings.Remove))
  277. {
  278. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigDuplicateItem,
  279. name,
  280. this.GetType().Name),
  281. this.ElementInformation.Source,
  282. this.ElementInformation.LineNumber));
  283. }
  284. TServiceModelExtensionElement retval = null;
  285. Type elementType;
  286. ContextInformation evaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
  287. try
  288. {
  289. elementType = GetExtensionType(evaluationContext, name);
  290. }
  291. catch (ConfigurationErrorsException e)
  292. {
  293. // Work-around for bug 219506@CSDMain: if the extension type cannot be loaded, we'll ignore
  294. // the exception when running in win8 app container and reading from machine.config.
  295. if (System.ServiceModel.Channels.AppContainerInfo.IsRunningInAppContainer && evaluationContext.IsMachineLevel)
  296. {
  297. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  298. return null;
  299. }
  300. else
  301. {
  302. throw;
  303. }
  304. }
  305. if (null != elementType)
  306. {
  307. if (this.CollectionElementBaseType.IsAssignableFrom(elementType))
  308. {
  309. retval = (TServiceModelExtensionElement)Activator.CreateInstance(elementType);
  310. retval.ExtensionCollectionName = this.extensionCollectionName;
  311. retval.ConfigurationElementName = name;
  312. retval.InternalInitializeDefault();
  313. }
  314. else
  315. {
  316. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidExtensionElement,
  317. name,
  318. this.CollectionElementBaseType.FullName),
  319. this.ElementInformation.Source,
  320. this.ElementInformation.LineNumber));
  321. }
  322. }
  323. else
  324. {
  325. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidExtensionElementName,
  326. name,
  327. this.extensionCollectionName),
  328. this.ElementInformation.Source,
  329. this.ElementInformation.LineNumber));
  330. }
  331. return retval;
  332. }
  333. [Fx.Tag.SecurityNote(Critical = "Calls SecurityCritical method UnsafeLookupCollection which elevates in order to load config.",
  334. Safe = "Does not leak any config objects.")]
  335. [SecuritySafeCritical]
  336. Type GetExtensionType(ContextInformation evaluationContext, string name)
  337. {
  338. ExtensionElementCollection collection = ExtensionsSection.UnsafeLookupCollection(this.extensionCollectionName, evaluationContext);
  339. if (collection.ContainsKey(name))
  340. {
  341. ExtensionElement element = collection[name];
  342. Type elementType = Type.GetType(element.Type, false);
  343. if (null == elementType)
  344. {
  345. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidType, element.Type, element.Name),
  346. this.ElementInformation.Source,
  347. this.ElementInformation.LineNumber));
  348. }
  349. return elementType;
  350. }
  351. return null;
  352. }
  353. internal void MergeWith(List<TServiceModelExtensionElement> parentExtensionElements)
  354. {
  355. ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>.Merge(parentExtensionElements, this);
  356. this.Clear();
  357. foreach (TServiceModelExtensionElement parentExtensionElement in parentExtensionElements)
  358. {
  359. this.Add(parentExtensionElement);
  360. }
  361. }
  362. static void Merge(List<TServiceModelExtensionElement> parentExtensionElements, IEnumerable<TServiceModelExtensionElement> childExtensionElements)
  363. {
  364. foreach (TServiceModelExtensionElement childExtensionElement in childExtensionElements)
  365. {
  366. if (childExtensionElement is ClearBehaviorElement)
  367. {
  368. parentExtensionElements.Clear();
  369. }
  370. else if (childExtensionElement is RemoveBehaviorElement)
  371. {
  372. string childExtensionElementName = (childExtensionElement as RemoveBehaviorElement).Name;
  373. if (!string.IsNullOrEmpty(childExtensionElementName))
  374. {
  375. parentExtensionElements.RemoveAll(element => element != null && element.ConfigurationElementName == childExtensionElementName);
  376. }
  377. }
  378. else
  379. {
  380. Type childExtensionElementType = childExtensionElement.GetType();
  381. parentExtensionElements.RemoveAll(element => element != null && element.GetType() == childExtensionElementType);
  382. parentExtensionElements.Add(childExtensionElement);
  383. }
  384. }
  385. }
  386. [Fx.Tag.SecurityNote(Critical = "Uses the critical helper SetIsPresent.",
  387. Safe = "Controls how/when SetIsPresent is used, not arbitrarily callable from PT (method is protected and class is sealed).")]
  388. [SecuritySafeCritical]
  389. protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
  390. {
  391. SetIsPresent();
  392. DeserializeElementCore(reader);
  393. }
  394. private void DeserializeElementCore(XmlReader reader)
  395. {
  396. if (reader.HasAttributes && 0 < reader.AttributeCount)
  397. {
  398. while (reader.MoveToNextAttribute())
  399. {
  400. if (this.Properties.Contains(reader.Name))
  401. {
  402. this[reader.Name] = this.Properties[reader.Name].Converter.ConvertFromString(reader.Value);
  403. }
  404. else
  405. {
  406. this.OnDeserializeUnrecognizedAttribute(reader.Name, reader.Value);
  407. }
  408. }
  409. }
  410. if (XmlNodeType.Element != reader.NodeType)
  411. {
  412. reader.MoveToElement();
  413. }
  414. XmlReader subTree = reader.ReadSubtree();
  415. if (subTree.Read())
  416. {
  417. while (subTree.Read())
  418. {
  419. if (XmlNodeType.Element == subTree.NodeType)
  420. {
  421. // Create new child element and add it to the property collection to
  422. // associate the element with an EvaluationContext. Then deserialize
  423. // XML further to set actual values.
  424. TServiceModelExtensionElement collectionElement = this.CreateNewSection(subTree.Name);
  425. if (collectionElement != null)
  426. {
  427. this.Add(collectionElement);
  428. collectionElement.DeserializeInternal(subTree, false);
  429. }
  430. }
  431. }
  432. }
  433. }
  434. [Fx.Tag.SecurityNote(Critical = "Calls ConfigurationHelpers.SetIsPresent which elevates in order to set a property.")]
  435. [SecurityCritical]
  436. void SetIsPresent()
  437. {
  438. ConfigurationHelpers.SetIsPresent(this);
  439. }
  440. public System.Collections.Generic.IEnumerator<TServiceModelExtensionElement> GetEnumerator()
  441. {
  442. for (int index = 0; index < this.Items.Count; ++index)
  443. {
  444. TServiceModelExtensionElement currentValue = items[index];
  445. yield return currentValue;
  446. }
  447. }
  448. protected override bool IsModified()
  449. {
  450. bool retval = this.modified;
  451. if (!retval)
  452. {
  453. for (int i = 0; i < this.Items.Count; i++)
  454. {
  455. TServiceModelExtensionElement element = this.Items[i];
  456. if (element.IsModifiedInternal())
  457. {
  458. retval = true;
  459. break;
  460. }
  461. }
  462. }
  463. return retval;
  464. }
  465. protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
  466. {
  467. // When this is used as a DefaultCollection (i.e. CommonBehaviors)
  468. // the element names are unrecognized by the parent tag, which delegates
  469. // to the collection's OnDeserializeUnrecognizedElement. In this case,
  470. // an unrecognized element may be expected, simply try to deserialize the
  471. // element and let DeserializeElement() throw the appropriate exception if
  472. // an error is hit.
  473. this.DeserializeElement(reader, false);
  474. return true;
  475. }
  476. public bool Remove(TServiceModelExtensionElement element)
  477. {
  478. if (element == null)
  479. {
  480. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
  481. }
  482. bool retval = false;
  483. if (this.Contains(element))
  484. {
  485. string configuredSectionName = element.ConfigurationElementName;
  486. TServiceModelExtensionElement existingElement = (TServiceModelExtensionElement)this[element.GetType()];
  487. this.Items.Remove(existingElement);
  488. this.Properties.Remove(configuredSectionName);
  489. this.modified = true;
  490. retval = true;
  491. }
  492. return retval;
  493. }
  494. [Fx.Tag.SecurityNote(Critical = "Accesses critical field contextHelper.")]
  495. [SecurityCritical]
  496. protected override void Reset(ConfigurationElement parentElement)
  497. {
  498. ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> collection =
  499. (ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>)parentElement;
  500. foreach (TServiceModelExtensionElement collectionElement in collection.Items)
  501. {
  502. this.Items.Add(collectionElement);
  503. }
  504. // Update my properties
  505. this.UpdateProperties(collection);
  506. this.contextHelper.OnReset(parentElement);
  507. base.Reset(parentElement);
  508. }
  509. protected override void ResetModified()
  510. {
  511. for (int i = 0; i < this.Items.Count; i++)
  512. {
  513. TServiceModelExtensionElement collectionElement = this.Items[i];
  514. collectionElement.ResetModifiedInternal();
  515. }
  516. this.modified = false;
  517. }
  518. protected void SetIsModified()
  519. {
  520. this.modified = true;
  521. }
  522. protected override void SetReadOnly()
  523. {
  524. base.SetReadOnly();
  525. for (int i = 0; i < this.Items.Count; i++)
  526. {
  527. TServiceModelExtensionElement element = this.Items[i];
  528. element.SetReadOnlyInternal();
  529. }
  530. }
  531. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  532. {
  533. return this.GetEnumerator();
  534. }
  535. protected override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
  536. {
  537. if (sourceElement == null)
  538. {
  539. return;
  540. }
  541. ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> sourceCollectionElement = (ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>)sourceElement;
  542. this.UpdateProperties(sourceCollectionElement);
  543. base.Unmerge(sourceElement, parentElement, saveMode);
  544. }
  545. void UpdateProperties(ServiceModelExtensionCollectionElement<TServiceModelExtensionElement> sourceElement)
  546. {
  547. foreach (ConfigurationProperty property in sourceElement.Properties)
  548. {
  549. if (!this.Properties.Contains(property.Name))
  550. {
  551. this.Properties.Add(property);
  552. }
  553. }
  554. foreach (TServiceModelExtensionElement extension in this.Items)
  555. {
  556. if (extension is ClearBehaviorElement || extension is RemoveBehaviorElement)
  557. continue;
  558. string configuredSectionName = extension.ConfigurationElementName;
  559. if (!this.Properties.Contains(configuredSectionName))
  560. {
  561. ConfigurationProperty configProperty = new ConfigurationProperty(configuredSectionName, extension.GetType(), null);
  562. this.Properties.Add(configProperty);
  563. }
  564. }
  565. }
  566. ContextInformation IConfigurationContextProviderInternal.GetEvaluationContext()
  567. {
  568. return this.EvaluationContext;
  569. }
  570. [Fx.Tag.SecurityNote(Critical = "Accesses critical field contextHelper.",
  571. Miscellaneous = "RequiresReview -- the return value will be used for a security decision -- see comment in interface definition.")]
  572. [SecurityCritical]
  573. ContextInformation IConfigurationContextProviderInternal.GetOriginalEvaluationContext()
  574. {
  575. return this.contextHelper.GetOriginalContext(this);
  576. }
  577. }
  578. }