ConfigurationElement.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. //
  2. // System.Configuration.ConfigurationElement.cs
  3. //
  4. // Authors:
  5. // Duncan Mak ([email protected])
  6. // Lluis Sanchez Gual ([email protected])
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining
  9. // a copy of this software and associated documentation files (the
  10. // "Software"), to deal in the Software without restriction, including
  11. // without limitation the rights to use, copy, modify, merge, publish,
  12. // distribute, sublicense, and/or sell copies of the Software, and to
  13. // permit persons to whom the Software is furnished to do so, subject to
  14. // the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be
  17. // included in all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. //
  27. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  28. //
  29. #if NET_2_0
  30. using System.Collections;
  31. using System.Xml;
  32. using System.Reflection;
  33. using System.IO;
  34. using System.ComponentModel;
  35. namespace System.Configuration
  36. {
  37. public abstract class ConfigurationElement
  38. {
  39. string rawXml;
  40. bool modified;
  41. ElementMap map;
  42. ConfigurationPropertyCollection keyProps;
  43. ConfigurationElementCollection defaultCollection;
  44. bool readOnly;
  45. ElementInformation elementInfo;
  46. ConfigurationElementProperty elementProperty;
  47. protected ConfigurationElement ()
  48. {
  49. }
  50. internal virtual void InitFromProperty (PropertyInformation propertyInfo)
  51. {
  52. elementInfo = new ElementInformation (this, propertyInfo);
  53. Init ();
  54. }
  55. public ElementInformation ElementInformation {
  56. get {
  57. if (elementInfo == null)
  58. elementInfo = new ElementInformation (this, null);
  59. return elementInfo;
  60. }
  61. }
  62. internal string RawXml {
  63. get { return rawXml; }
  64. set {
  65. // FIXME: this hack is nasty. We should make
  66. // some refactory on the entire assembly.
  67. if (rawXml == null || value != null)
  68. rawXml = value;
  69. }
  70. }
  71. protected internal virtual void Init ()
  72. {
  73. }
  74. protected internal virtual ConfigurationElementProperty ElementProperty {
  75. get {
  76. if (elementProperty == null)
  77. elementProperty = new ConfigurationElementProperty (ElementInformation.Validator);
  78. return elementProperty;
  79. }
  80. }
  81. [MonoTODO]
  82. protected ContextInformation EvaluationContext {
  83. get {
  84. throw new NotImplementedException ();
  85. }
  86. }
  87. ConfigurationLockCollection lockAllAttributesExcept;
  88. public ConfigurationLockCollection LockAllAttributesExcept {
  89. get {
  90. if (lockAllAttributesExcept == null) {
  91. lockAllAttributesExcept = new ConfigurationLockCollection (this, ConfigurationLockType.Attribute | ConfigurationLockType.Exclude);
  92. }
  93. return lockAllAttributesExcept;
  94. }
  95. }
  96. ConfigurationLockCollection lockAllElementsExcept;
  97. public ConfigurationLockCollection LockAllElementsExcept {
  98. get {
  99. if (lockAllElementsExcept == null) {
  100. lockAllElementsExcept = new ConfigurationLockCollection (this, ConfigurationLockType.Element | ConfigurationLockType.Exclude);
  101. }
  102. return lockAllElementsExcept;
  103. }
  104. }
  105. ConfigurationLockCollection lockAttributes;
  106. public ConfigurationLockCollection LockAttributes {
  107. get {
  108. if (lockAttributes == null) {
  109. lockAttributes = new ConfigurationLockCollection (this, ConfigurationLockType.Attribute);
  110. }
  111. return lockAttributes;
  112. }
  113. }
  114. ConfigurationLockCollection lockElements;
  115. public ConfigurationLockCollection LockElements {
  116. get {
  117. if (lockElements == null) {
  118. lockElements = new ConfigurationLockCollection (this, ConfigurationLockType.Element);
  119. }
  120. return lockElements;
  121. }
  122. }
  123. bool lockItem;
  124. public bool LockItem {
  125. get { return lockItem; }
  126. set { lockItem = value; }
  127. }
  128. [MonoTODO]
  129. protected virtual void ListErrors (IList list)
  130. {
  131. throw new NotImplementedException ();
  132. }
  133. [MonoTODO]
  134. protected void SetPropertyValue (ConfigurationProperty prop, object value, bool ignoreLocks)
  135. {
  136. try {
  137. /* XXX all i know for certain is that Validation happens here */
  138. prop.Validate (value);
  139. /* XXX presumably the actual setting of the
  140. * property happens here instead of in the
  141. * set_Item code below, but that would mean
  142. * the Value needs to be stuffed in the
  143. * property, not the propertyinfo (or else the
  144. * property needs a ref to the property info
  145. * to correctly set the value). */
  146. }
  147. catch (Exception e) {
  148. throw new ConfigurationErrorsException (String.Format ("The value for the property '{0}' is not valid. The error is: {1}", prop.Name, e.Message), e);
  149. }
  150. }
  151. internal ConfigurationPropertyCollection GetKeyProperties ()
  152. {
  153. if (keyProps != null) return keyProps;
  154. if (map != null && map.Properties == Properties)
  155. keyProps = map.KeyProperties;
  156. else {
  157. keyProps = new ConfigurationPropertyCollection ();
  158. foreach (ConfigurationProperty prop in Properties) {
  159. if (prop.IsKey)
  160. keyProps.Add (prop);
  161. }
  162. }
  163. return keyProps;
  164. }
  165. internal ConfigurationElementCollection GetDefaultCollection ()
  166. {
  167. if (defaultCollection != null) return defaultCollection;
  168. ConfigurationProperty defaultCollectionProp = null;
  169. if (map != null && map.Properties == Properties) {
  170. defaultCollectionProp = map.DefaultCollectionProperty;
  171. }
  172. else {
  173. foreach (ConfigurationProperty prop in Properties) {
  174. if (prop.IsDefaultCollection) {
  175. defaultCollectionProp = prop;
  176. break;
  177. }
  178. }
  179. }
  180. if (defaultCollectionProp != null) {
  181. defaultCollection = this [defaultCollectionProp] as ConfigurationElementCollection;
  182. }
  183. return defaultCollection;
  184. }
  185. protected internal object this [ConfigurationProperty property] {
  186. get { return this [property.Name]; }
  187. set { this [property.Name] = value; }
  188. }
  189. protected internal object this [string property_name] {
  190. get {
  191. PropertyInformation pi = ElementInformation.Properties [property_name];
  192. if (pi == null)
  193. throw new InvalidOperationException ("Property '" + property_name + "' not found in configuration element");
  194. return pi.Value;
  195. }
  196. set {
  197. PropertyInformation pi = ElementInformation.Properties [property_name];
  198. if (pi == null)
  199. throw new InvalidOperationException ("Property '" + property_name + "' not found in configuration element");
  200. SetPropertyValue (pi.Property, value, false);
  201. pi.Value = value;
  202. modified = true;
  203. }
  204. }
  205. protected internal virtual ConfigurationPropertyCollection Properties {
  206. get {
  207. if (map == null)
  208. map = ElementMap.GetMap (GetType());
  209. return map.Properties;
  210. }
  211. }
  212. public override bool Equals (object compareTo)
  213. {
  214. ConfigurationElement other = compareTo as ConfigurationElement;
  215. if (other == null) return false;
  216. if (GetType() != other.GetType()) return false;
  217. foreach (ConfigurationProperty prop in Properties) {
  218. if (!object.Equals (this [prop], other [prop]))
  219. return false;
  220. }
  221. return true;
  222. }
  223. public override int GetHashCode ()
  224. {
  225. int code = 0;
  226. foreach (ConfigurationProperty prop in Properties)
  227. code += this [prop].GetHashCode ();
  228. return code;
  229. }
  230. internal virtual bool HasValues ()
  231. {
  232. foreach (PropertyInformation pi in ElementInformation.Properties)
  233. if (pi.ValueOrigin != PropertyValueOrigin.Default)
  234. return true;
  235. return false;
  236. }
  237. protected internal virtual void DeserializeElement (XmlReader reader, bool serializeCollectionKey)
  238. {
  239. Hashtable readProps = new Hashtable ();
  240. reader.MoveToContent ();
  241. while (reader.MoveToNextAttribute ())
  242. {
  243. PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
  244. if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
  245. /* handle the built in ConfigurationElement attributes here */
  246. if (reader.LocalName == "lockAllAttributesExcept") {
  247. LockAllAttributesExcept.SetFromList (reader.Value);
  248. }
  249. else if (reader.LocalName == "lockAllElementsExcept") {
  250. LockAllElementsExcept.SetFromList (reader.Value);
  251. }
  252. else if (reader.LocalName == "lockAttributes") {
  253. LockAttributes.SetFromList (reader.Value);
  254. }
  255. else if (reader.LocalName == "lockElements") {
  256. LockElements.SetFromList (reader.Value);
  257. }
  258. else if (reader.LocalName == "lockItem") {
  259. LockItem = (reader.Value.ToLowerInvariant () == "true");
  260. }
  261. else if (reader.LocalName == "xmlns") {
  262. /* ignore */
  263. }
  264. else if (!OnDeserializeUnrecognizedAttribute (reader.LocalName, reader.Value))
  265. throw new ConfigurationException ("Unrecognized attribute '" + reader.LocalName + "'.");
  266. continue;
  267. }
  268. if (readProps.ContainsKey (prop))
  269. throw new ConfigurationException ("The attribute '" + prop.Name + "' may only appear once in this element.");
  270. string value = null;
  271. try {
  272. value = reader.Value;
  273. ValidateValue (prop.Property, value);
  274. prop.SetStringValue (value);
  275. } catch (ConfigurationErrorsException) {
  276. throw;
  277. } catch (ConfigurationException) {
  278. throw;
  279. } catch (Exception ex) {
  280. string msg = String.Format ("The value of the property '{0}' cannot be parsed.", prop.Name);
  281. throw new ConfigurationErrorsException (msg, reader);
  282. }
  283. readProps [prop] = prop.Name;
  284. }
  285. reader.MoveToElement ();
  286. if (reader.IsEmptyElement) {
  287. reader.Skip ();
  288. } else {
  289. int depth = reader.Depth;
  290. reader.ReadStartElement ();
  291. reader.MoveToContent ();
  292. do {
  293. if (reader.NodeType != XmlNodeType.Element) {
  294. reader.Skip ();
  295. continue;
  296. }
  297. PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
  298. if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
  299. if (!OnDeserializeUnrecognizedElement (reader.LocalName, reader)) {
  300. if (prop == null) {
  301. ConfigurationElementCollection c = GetDefaultCollection ();
  302. if (c != null && c.OnDeserializeUnrecognizedElement (reader.LocalName, reader))
  303. continue;
  304. }
  305. throw new ConfigurationException ("Unrecognized element '" + reader.LocalName + "'.");
  306. }
  307. continue;
  308. }
  309. if (!prop.IsElement)
  310. throw new ConfigurationException ("Property '" + prop.Name + "' is not a ConfigurationElement.");
  311. if (readProps.Contains (prop))
  312. throw new ConfigurationException ("The element <" + prop.Name + "> may only appear once in this section.");
  313. ConfigurationElement val = (ConfigurationElement) prop.Value;
  314. val.DeserializeElement (reader, serializeCollectionKey);
  315. readProps [prop] = prop.Name;
  316. reader.Read();
  317. } while (depth < reader.Depth);
  318. if (reader.NodeType == XmlNodeType.EndElement)
  319. reader.Read ();
  320. }
  321. modified = false;
  322. foreach (PropertyInformation prop in ElementInformation.Properties)
  323. if (!String.IsNullOrEmpty(prop.Name) && prop.IsRequired && !readProps.ContainsKey (prop)) {
  324. object val = OnRequiredPropertyNotFound (prop.Name);
  325. if (!object.Equals (val, prop.DefaultValue)) {
  326. prop.Value = val;
  327. prop.IsModified = false;
  328. }
  329. }
  330. PostDeserialize ();
  331. }
  332. protected virtual bool OnDeserializeUnrecognizedAttribute (string name, string value)
  333. {
  334. return false;
  335. }
  336. protected virtual bool OnDeserializeUnrecognizedElement (string element, XmlReader reader)
  337. {
  338. return false;
  339. }
  340. protected virtual object OnRequiredPropertyNotFound (string name)
  341. {
  342. throw new ConfigurationErrorsException ("Required attribute '" + name + "' not found.");
  343. }
  344. protected virtual void PreSerialize (XmlWriter writer)
  345. {
  346. }
  347. protected virtual void PostDeserialize ()
  348. {
  349. }
  350. protected internal virtual void InitializeDefault ()
  351. {
  352. }
  353. protected internal virtual bool IsModified ()
  354. {
  355. return modified;
  356. }
  357. protected internal virtual void SetReadOnly ()
  358. {
  359. readOnly = true;
  360. }
  361. public virtual bool IsReadOnly ()
  362. {
  363. return readOnly;
  364. }
  365. protected internal virtual void Reset (ConfigurationElement parentElement)
  366. {
  367. if (parentElement != null)
  368. ElementInformation.Reset (parentElement.ElementInformation);
  369. else
  370. InitializeDefault ();
  371. }
  372. protected internal virtual void ResetModified ()
  373. {
  374. modified = false;
  375. foreach (PropertyInformation p in ElementInformation.Properties)
  376. p.IsModified = false;
  377. }
  378. protected internal virtual bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
  379. {
  380. PreSerialize (writer);
  381. if (serializeCollectionKey) {
  382. ConfigurationPropertyCollection props = GetKeyProperties ();
  383. foreach (ConfigurationProperty prop in props)
  384. writer.WriteAttributeString (prop.Name, prop.ConvertToString (this[prop.Name]));
  385. return props.Count > 0;
  386. }
  387. bool wroteData = false;
  388. foreach (PropertyInformation prop in ElementInformation.Properties)
  389. {
  390. if (prop.IsElement || prop.ValueOrigin == PropertyValueOrigin.Default)
  391. continue;
  392. if (!object.Equals (prop.Value, prop.DefaultValue)) {
  393. writer.WriteAttributeString (prop.Name, prop.GetStringValue ());
  394. wroteData = true;
  395. }
  396. }
  397. foreach (PropertyInformation prop in ElementInformation.Properties)
  398. {
  399. if (!prop.IsElement)
  400. continue;
  401. ConfigurationElement val = (ConfigurationElement) prop.Value;
  402. if (val != null && val.HasValues ()) {
  403. wroteData = val.SerializeToXmlElement (writer, prop.Name) || wroteData;
  404. }
  405. }
  406. return wroteData;
  407. }
  408. protected internal virtual bool SerializeToXmlElement (
  409. XmlWriter writer, string elementName)
  410. {
  411. if (elementName != null && elementName != "")
  412. writer.WriteStartElement (elementName);
  413. bool res = SerializeElement (writer, false);
  414. if (elementName != null && elementName != "")
  415. writer.WriteEndElement ();
  416. return res;
  417. }
  418. protected internal virtual void Unmerge (
  419. ConfigurationElement source, ConfigurationElement parent,
  420. ConfigurationSaveMode updateMode)
  421. {
  422. if (parent != null && source.GetType() != parent.GetType())
  423. throw new ConfigurationException ("Can't unmerge two elements of different type");
  424. foreach (PropertyInformation prop in source.ElementInformation.Properties)
  425. {
  426. if (prop.ValueOrigin == PropertyValueOrigin.Default)
  427. continue;
  428. PropertyInformation unmergedProp = ElementInformation.Properties [prop.Name];
  429. object sourceValue = prop.Value;
  430. if (parent == null || !parent.HasValue (prop.Name)) {
  431. unmergedProp.Value = sourceValue;
  432. continue;
  433. }
  434. else if (sourceValue != null) {
  435. object parentValue = parent [prop.Name];
  436. if (prop.IsElement) {
  437. if (parentValue != null) {
  438. ConfigurationElement copy = (ConfigurationElement) unmergedProp.Value;
  439. copy.Unmerge ((ConfigurationElement) sourceValue, (ConfigurationElement) parentValue, updateMode);
  440. }
  441. else
  442. unmergedProp.Value = sourceValue;
  443. }
  444. else {
  445. if (!object.Equals (sourceValue, parentValue) ||
  446. (updateMode == ConfigurationSaveMode.Full) ||
  447. (updateMode == ConfigurationSaveMode.Modified && prop.ValueOrigin == PropertyValueOrigin.SetHere))
  448. unmergedProp.Value = sourceValue;
  449. }
  450. }
  451. }
  452. }
  453. internal bool HasValue (string propName)
  454. {
  455. PropertyInformation info = ElementInformation.Properties [propName];
  456. return info != null && info.ValueOrigin != PropertyValueOrigin.Default;
  457. }
  458. internal bool IsReadFromConfig (string propName)
  459. {
  460. PropertyInformation info = ElementInformation.Properties [propName];
  461. return info != null && info.ValueOrigin == PropertyValueOrigin.SetHere;
  462. }
  463. void ValidateValue (ConfigurationProperty p, string value)
  464. {
  465. ConfigurationValidatorBase validator;
  466. if (p == null || (validator = p.Validator) == null)
  467. return;
  468. if (!validator.CanValidate (p.Type))
  469. throw new ConfigurationException (
  470. String.Format ("Validator does not support type {0}", p.Type));
  471. validator.Validate (p.ConvertFromString (value));
  472. }
  473. }
  474. internal class ElementMap
  475. {
  476. static Hashtable elementMaps = new Hashtable ();
  477. ConfigurationPropertyCollection properties;
  478. ConfigurationPropertyCollection keyProperties;
  479. ConfigurationProperty defaultCollectionProperty;
  480. ConfigurationCollectionAttribute collectionAttribute;
  481. public static ElementMap GetMap (Type t)
  482. {
  483. lock (elementMaps) {
  484. ElementMap map = elementMaps [t] as ElementMap;
  485. if (map != null) return map;
  486. map = new ElementMap (t);
  487. elementMaps [t] = map;
  488. return map;
  489. }
  490. }
  491. public ElementMap (Type t)
  492. {
  493. ReflectProperties (t);
  494. }
  495. protected void ReflectProperties (Type t)
  496. {
  497. collectionAttribute = Attribute.GetCustomAttribute (t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
  498. PropertyInfo[] props = t.GetProperties ();
  499. foreach (PropertyInfo prop in props)
  500. {
  501. ConfigurationPropertyAttribute at = Attribute.GetCustomAttribute (prop, typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute;
  502. if (at == null) continue;
  503. string name = at.Name != null ? at.Name : prop.Name;
  504. ConfigurationValidatorAttribute validatorAttr = Attribute.GetCustomAttribute (t, typeof(ConfigurationValidatorAttribute)) as ConfigurationValidatorAttribute;
  505. ConfigurationValidatorBase validator = validatorAttr != null ? validatorAttr.ValidatorInstance : null;
  506. TypeConverterAttribute convertAttr = (TypeConverterAttribute) Attribute.GetCustomAttribute (t, typeof (TypeConverterAttribute));
  507. TypeConverter converter = convertAttr != null ? (TypeConverter) Activator.CreateInstance (Type.GetType (convertAttr.ConverterTypeName)) : null;
  508. ConfigurationProperty cp = new ConfigurationProperty (name, prop.PropertyType, at.DefaultValue, converter, validator, at.Options);
  509. cp.CollectionAttribute = Attribute.GetCustomAttribute (prop, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
  510. if (properties == null) properties = new ConfigurationPropertyCollection ();
  511. properties.Add (cp);
  512. }
  513. }
  514. public bool HasProperties
  515. {
  516. get { return properties != null && properties.Count > 0; }
  517. }
  518. public ConfigurationPropertyCollection Properties
  519. {
  520. get {
  521. if (properties == null) properties = new ConfigurationPropertyCollection ();
  522. return properties;
  523. }
  524. }
  525. public ConfigurationPropertyCollection KeyProperties {
  526. get {
  527. if (keyProperties == null) {
  528. keyProperties = new ConfigurationPropertyCollection ();
  529. if (properties != null)
  530. foreach (ConfigurationProperty p in properties)
  531. if (p.IsKey) keyProperties.Add (p);
  532. }
  533. return keyProperties;
  534. }
  535. }
  536. public ConfigurationCollectionAttribute CollectionAttribute {
  537. get { return collectionAttribute; }
  538. }
  539. public ConfigurationProperty DefaultCollectionProperty {
  540. get {
  541. if (defaultCollectionProperty == null) {
  542. if (properties != null)
  543. foreach (ConfigurationProperty p in properties) {
  544. if (p.IsDefaultCollection) {
  545. defaultCollectionProperty = p;
  546. break;
  547. }
  548. }
  549. }
  550. return defaultCollectionProperty;
  551. }
  552. }
  553. }
  554. }
  555. #endif