ConfigurationElement.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 { rawXml = value; }
  65. }
  66. protected internal virtual void Init ()
  67. {
  68. }
  69. protected internal virtual ConfigurationElementProperty ElementProperty {
  70. get {
  71. if (elementProperty == null)
  72. elementProperty = new ConfigurationElementProperty (ElementInformation.Validator);
  73. return elementProperty;
  74. }
  75. }
  76. [MonoTODO]
  77. protected ContextInformation EvaluationContext {
  78. get {
  79. throw new NotImplementedException ();
  80. }
  81. }
  82. ConfigurationLockCollection lockAllAttributesExcept;
  83. public ConfigurationLockCollection LockAllAttributesExcept {
  84. get {
  85. if (lockAllAttributesExcept == null) {
  86. lockAllAttributesExcept = new ConfigurationLockCollection (this, ConfigurationLockType.Attribute | ConfigurationLockType.Exclude);
  87. }
  88. return lockAllAttributesExcept;
  89. }
  90. }
  91. ConfigurationLockCollection lockAllElementsExcept;
  92. public ConfigurationLockCollection LockAllElementsExcept {
  93. get {
  94. if (lockAllElementsExcept == null) {
  95. lockAllElementsExcept = new ConfigurationLockCollection (this, ConfigurationLockType.Element | ConfigurationLockType.Exclude);
  96. }
  97. return lockAllElementsExcept;
  98. }
  99. }
  100. ConfigurationLockCollection lockAttributes;
  101. public ConfigurationLockCollection LockAttributes {
  102. get {
  103. if (lockAttributes == null) {
  104. lockAttributes = new ConfigurationLockCollection (this, ConfigurationLockType.Attribute);
  105. }
  106. return lockAttributes;
  107. }
  108. }
  109. ConfigurationLockCollection lockElements;
  110. public ConfigurationLockCollection LockElements {
  111. get {
  112. if (lockElements == null) {
  113. lockElements = new ConfigurationLockCollection (this, ConfigurationLockType.Element);
  114. }
  115. return lockElements;
  116. }
  117. }
  118. bool lockItem;
  119. public bool LockItem {
  120. get { return lockItem; }
  121. set { lockItem = value; }
  122. }
  123. [MonoTODO]
  124. protected void ListErrors (IList list)
  125. {
  126. throw new NotImplementedException ();
  127. }
  128. [MonoTODO]
  129. protected void SetPropertyValue (ConfigurationProperty prop, object value, bool ignoreLocks)
  130. {
  131. try {
  132. /* XXX all i know for certain is that Validation happens here */
  133. prop.Validate (value);
  134. /* XXX presumably the actual setting of the
  135. * property happens here instead of in the
  136. * set_Item code below, but that would mean
  137. * the Value needs to be stuffed in the
  138. * property, not the propertyinfo (or else the
  139. * property needs a ref to the property info
  140. * to correctly set the value). */
  141. }
  142. catch (Exception e) {
  143. throw new ConfigurationErrorsException (String.Format ("The value for the property '{0}' is not valid. The error is: {1}", prop.Name, e.Message), e);
  144. }
  145. }
  146. internal ConfigurationPropertyCollection GetKeyProperties ()
  147. {
  148. if (keyProps != null) return keyProps;
  149. if (map != null && map.Properties == Properties)
  150. keyProps = map.KeyProperties;
  151. else {
  152. keyProps = new ConfigurationPropertyCollection ();
  153. foreach (ConfigurationProperty prop in Properties) {
  154. if (prop.IsKey)
  155. keyProps.Add (prop);
  156. }
  157. }
  158. return keyProps;
  159. }
  160. internal ConfigurationElementCollection GetDefaultCollection ()
  161. {
  162. if (defaultCollection != null) return defaultCollection;
  163. ConfigurationProperty defaultCollectionProp = null;
  164. if (map != null && map.Properties == Properties) {
  165. defaultCollectionProp = map.DefaultCollectionProperty;
  166. }
  167. else {
  168. foreach (ConfigurationProperty prop in Properties) {
  169. if (prop.IsDefaultCollection) {
  170. defaultCollectionProp = prop;
  171. break;
  172. }
  173. }
  174. }
  175. if (defaultCollectionProp != null) {
  176. defaultCollection = this [defaultCollectionProp] as ConfigurationElementCollection;
  177. }
  178. return defaultCollection;
  179. }
  180. protected internal object this [ConfigurationProperty property] {
  181. get { return this [property.Name]; }
  182. set { this [property.Name] = value; }
  183. }
  184. protected internal object this [string property_name] {
  185. get {
  186. PropertyInformation pi = ElementInformation.Properties [property_name];
  187. if (pi == null)
  188. throw new InvalidOperationException ("Property '" + property_name + "' not found in configuration element");
  189. return pi.Value;
  190. }
  191. set {
  192. PropertyInformation pi = ElementInformation.Properties [property_name];
  193. if (pi == null)
  194. throw new InvalidOperationException ("Property '" + property_name + "' not found in configuration element");
  195. SetPropertyValue (pi.Property, value, false);
  196. pi.Value = value;
  197. modified = true;
  198. }
  199. }
  200. protected internal virtual ConfigurationPropertyCollection Properties {
  201. get {
  202. if (map == null)
  203. map = ElementMap.GetMap (GetType());
  204. return map.Properties;
  205. }
  206. }
  207. public override bool Equals (object compareTo)
  208. {
  209. ConfigurationElement other = compareTo as ConfigurationElement;
  210. if (other == null) return false;
  211. if (GetType() != other.GetType()) return false;
  212. foreach (ConfigurationProperty prop in Properties) {
  213. if (!object.Equals (this [prop], other [prop]))
  214. return false;
  215. }
  216. return true;
  217. }
  218. public override int GetHashCode ()
  219. {
  220. int code = 0;
  221. foreach (ConfigurationProperty prop in Properties)
  222. code += this [prop].GetHashCode ();
  223. return code;
  224. }
  225. internal virtual bool HasValues ()
  226. {
  227. foreach (PropertyInformation pi in ElementInformation.Properties)
  228. if (pi.ValueOrigin != PropertyValueOrigin.Default)
  229. return true;
  230. return false;
  231. }
  232. protected internal virtual void DeserializeElement (XmlReader reader, bool serializeCollectionKey)
  233. {
  234. Hashtable readProps = new Hashtable ();
  235. reader.MoveToContent ();
  236. while (reader.MoveToNextAttribute ())
  237. {
  238. PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
  239. if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
  240. /* handle the built in ConfigurationElement attributes here */
  241. if (reader.LocalName == "lockAllAttributesExcept") {
  242. LockAllAttributesExcept.SetFromList (reader.Value);
  243. }
  244. else if (reader.LocalName == "lockAllElementsExcept") {
  245. LockAllElementsExcept.SetFromList (reader.Value);
  246. }
  247. else if (reader.LocalName == "lockAttributes") {
  248. LockAttributes.SetFromList (reader.Value);
  249. }
  250. else if (reader.LocalName == "lockElements") {
  251. LockElements.SetFromList (reader.Value);
  252. }
  253. else if (reader.LocalName == "lockItem") {
  254. LockItem = (reader.Value.ToLower() == "true");
  255. }
  256. else if (reader.LocalName == "xmlns") {
  257. /* ignore */
  258. }
  259. else if (!OnDeserializeUnrecognizedAttribute (reader.LocalName, reader.Value))
  260. throw new ConfigurationException ("Unrecognized attribute '" + reader.LocalName + "'.");
  261. continue;
  262. }
  263. if (readProps.ContainsKey (prop))
  264. throw new ConfigurationException ("The attribute '" + prop.Name + "' may only appear once in this element.");
  265. prop.SetStringValue (reader.Value);
  266. readProps [prop] = prop.Name;
  267. }
  268. reader.MoveToElement ();
  269. if (reader.IsEmptyElement) {
  270. reader.Skip ();
  271. }
  272. else {
  273. int depth = reader.Depth;
  274. reader.ReadStartElement ();
  275. reader.MoveToContent ();
  276. do {
  277. if (reader.NodeType != XmlNodeType.Element) {
  278. reader.Skip ();
  279. continue;
  280. }
  281. PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
  282. if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
  283. if (prop == null) {
  284. ConfigurationElementCollection c = GetDefaultCollection ();
  285. if (c != null && c.OnDeserializeUnrecognizedElement (reader.LocalName, reader))
  286. continue;
  287. }
  288. if (!OnDeserializeUnrecognizedElement (reader.LocalName, reader)) {
  289. throw new ConfigurationException ("Unrecognized element '" + reader.LocalName + "'.");
  290. }
  291. continue;
  292. }
  293. if (!prop.IsElement)
  294. throw new ConfigurationException ("Property '" + prop.Name + "' is not a ConfigurationElement.");
  295. if (readProps.Contains (prop))
  296. throw new ConfigurationException ("The element <" + prop.Name + "> may only appear once in this section.");
  297. ConfigurationElement val = (ConfigurationElement) prop.Value;
  298. val.DeserializeElement (reader, serializeCollectionKey);
  299. readProps [prop] = prop.Name;
  300. reader.Read();
  301. } while (depth < reader.Depth);
  302. if (reader.NodeType == XmlNodeType.EndElement)
  303. reader.Read ();
  304. }
  305. modified = false;
  306. foreach (PropertyInformation prop in ElementInformation.Properties)
  307. if (prop.IsRequired && !readProps.ContainsKey (prop)) {
  308. object val = OnRequiredPropertyNotFound (prop.Name);
  309. if (!object.Equals (val, prop.DefaultValue)) {
  310. prop.Value = val;
  311. prop.IsModified = false;
  312. }
  313. }
  314. PostDeserialize ();
  315. }
  316. protected virtual bool OnDeserializeUnrecognizedAttribute (string name, string value)
  317. {
  318. return false;
  319. }
  320. protected virtual bool OnDeserializeUnrecognizedElement (string element, XmlReader reader)
  321. {
  322. return false;
  323. }
  324. protected virtual object OnRequiredPropertyNotFound (string name)
  325. {
  326. throw new ConfigurationErrorsException ("Required attribute '" + name + "' not found.");
  327. }
  328. protected virtual void PreSerialize (XmlWriter writer)
  329. {
  330. }
  331. protected virtual void PostDeserialize ()
  332. {
  333. }
  334. protected internal virtual void InitializeDefault ()
  335. {
  336. }
  337. protected internal virtual bool IsModified ()
  338. {
  339. return modified;
  340. }
  341. protected internal virtual void SetReadOnly ()
  342. {
  343. readOnly = true;
  344. }
  345. public virtual bool IsReadOnly ()
  346. {
  347. return readOnly;
  348. }
  349. protected internal virtual void Reset (ConfigurationElement parentElement)
  350. {
  351. if (parentElement != null)
  352. ElementInformation.Reset (parentElement.ElementInformation);
  353. else
  354. InitializeDefault ();
  355. }
  356. protected internal virtual void ResetModified ()
  357. {
  358. modified = false;
  359. foreach (PropertyInformation p in ElementInformation.Properties)
  360. p.IsModified = false;
  361. }
  362. protected internal virtual bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
  363. {
  364. PreSerialize (writer);
  365. if (serializeCollectionKey) {
  366. ConfigurationPropertyCollection props = GetKeyProperties ();
  367. foreach (ConfigurationProperty prop in props)
  368. writer.WriteAttributeString (prop.Name, prop.ConvertToString (this[prop.Name]));
  369. return props.Count > 0;
  370. }
  371. bool wroteData = false;
  372. foreach (PropertyInformation prop in ElementInformation.Properties)
  373. {
  374. if (prop.IsElement || prop.ValueOrigin == PropertyValueOrigin.Default)
  375. continue;
  376. if (!object.Equals (prop.Value, prop.DefaultValue)) {
  377. writer.WriteAttributeString (prop.Name, prop.GetStringValue ());
  378. wroteData = true;
  379. }
  380. }
  381. foreach (PropertyInformation prop in ElementInformation.Properties)
  382. {
  383. if (!prop.IsElement)
  384. continue;
  385. ConfigurationElement val = (ConfigurationElement) prop.Value;
  386. if (val != null && val.HasValues ()) {
  387. wroteData = val.SerializeToXmlElement (writer, prop.Name) || wroteData;
  388. }
  389. }
  390. return wroteData;
  391. }
  392. protected internal virtual bool SerializeToXmlElement (
  393. XmlWriter writer, string elementName)
  394. {
  395. if (elementName != null && elementName != "")
  396. writer.WriteStartElement (elementName);
  397. bool res = SerializeElement (writer, false);
  398. if (elementName != null && elementName != "")
  399. writer.WriteEndElement ();
  400. return res;
  401. }
  402. protected internal virtual void Unmerge (
  403. ConfigurationElement source, ConfigurationElement parent,
  404. ConfigurationSaveMode updateMode)
  405. {
  406. if (parent != null && source.GetType() != parent.GetType())
  407. throw new ConfigurationException ("Can't unmerge two elements of different type");
  408. foreach (PropertyInformation prop in source.ElementInformation.Properties)
  409. {
  410. if (prop.ValueOrigin == PropertyValueOrigin.Default)
  411. continue;
  412. PropertyInformation unmergedProp = ElementInformation.Properties [prop.Name];
  413. object sourceValue = prop.Value;
  414. if (parent == null || !parent.HasValue (prop.Name)) {
  415. unmergedProp.Value = sourceValue;
  416. continue;
  417. }
  418. else if (sourceValue != null) {
  419. object parentValue = parent [prop.Name];
  420. if (prop.IsElement) {
  421. if (parentValue != null) {
  422. ConfigurationElement copy = (ConfigurationElement) unmergedProp.Value;
  423. copy.Unmerge ((ConfigurationElement) sourceValue, (ConfigurationElement) parentValue, updateMode);
  424. }
  425. else
  426. unmergedProp.Value = sourceValue;
  427. }
  428. else {
  429. if (!object.Equals (sourceValue, parentValue) ||
  430. (updateMode == ConfigurationSaveMode.Full) ||
  431. (updateMode == ConfigurationSaveMode.Modified && prop.ValueOrigin == PropertyValueOrigin.SetHere))
  432. unmergedProp.Value = sourceValue;
  433. }
  434. }
  435. }
  436. }
  437. internal bool HasValue (string propName)
  438. {
  439. PropertyInformation info = ElementInformation.Properties [propName];
  440. return info != null && info.ValueOrigin != PropertyValueOrigin.Default;
  441. }
  442. internal bool IsReadFromConfig (string propName)
  443. {
  444. PropertyInformation info = ElementInformation.Properties [propName];
  445. return info != null && info.ValueOrigin == PropertyValueOrigin.SetHere;
  446. }
  447. }
  448. internal class ElementMap
  449. {
  450. static Hashtable elementMaps = new Hashtable ();
  451. ConfigurationPropertyCollection properties;
  452. ConfigurationPropertyCollection keyProperties;
  453. ConfigurationProperty defaultCollectionProperty;
  454. ConfigurationCollectionAttribute collectionAttribute;
  455. public static ElementMap GetMap (Type t)
  456. {
  457. lock (elementMaps) {
  458. ElementMap map = elementMaps [t] as ElementMap;
  459. if (map != null) return map;
  460. map = new ElementMap (t);
  461. elementMaps [t] = map;
  462. return map;
  463. }
  464. }
  465. public ElementMap (Type t)
  466. {
  467. ReflectProperties (t);
  468. }
  469. protected void ReflectProperties (Type t)
  470. {
  471. collectionAttribute = Attribute.GetCustomAttribute (t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
  472. PropertyInfo[] props = t.GetProperties ();
  473. foreach (PropertyInfo prop in props)
  474. {
  475. ConfigurationPropertyAttribute at = Attribute.GetCustomAttribute (prop, typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute;
  476. if (at == null) continue;
  477. string name = at.Name != null ? at.Name : prop.Name;
  478. if (
  479. /* if we have no default value, don't bother to check further */
  480. at.DefaultValue != null && at.DefaultValue != ConfigurationProperty.NoDefaultValue
  481. )
  482. {
  483. try {
  484. Convert.ChangeType (at.DefaultValue, prop.PropertyType);
  485. }
  486. catch {
  487. throw new ConfigurationErrorsException (String.Format ("The default value for property '{0}' has a different type than the one of the property itself",
  488. name));
  489. }
  490. }
  491. ConfigurationValidatorAttribute validatorAttr = Attribute.GetCustomAttribute (t, typeof(ConfigurationValidatorAttribute)) as ConfigurationValidatorAttribute;
  492. ConfigurationValidatorBase validator = validatorAttr != null ? validatorAttr.ValidatorInstance : new DefaultValidator();
  493. TypeConverter converter = TypeDescriptor.GetConverter (prop.PropertyType);
  494. ConfigurationProperty cp = new ConfigurationProperty (name, prop.PropertyType, at.DefaultValue, converter, validator, at.Options);
  495. cp.CollectionAttribute = Attribute.GetCustomAttribute (prop, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
  496. if (properties == null) properties = new ConfigurationPropertyCollection ();
  497. properties.Add (cp);
  498. }
  499. }
  500. public bool HasProperties
  501. {
  502. get { return properties != null && properties.Count > 0; }
  503. }
  504. public ConfigurationPropertyCollection Properties
  505. {
  506. get {
  507. if (properties == null) properties = new ConfigurationPropertyCollection ();
  508. return properties;
  509. }
  510. }
  511. public ConfigurationPropertyCollection KeyProperties {
  512. get {
  513. if (keyProperties == null) {
  514. keyProperties = new ConfigurationPropertyCollection ();
  515. if (properties != null)
  516. foreach (ConfigurationProperty p in properties)
  517. if (p.IsKey) keyProperties.Add (p);
  518. }
  519. return keyProperties;
  520. }
  521. }
  522. public ConfigurationCollectionAttribute CollectionAttribute {
  523. get { return collectionAttribute; }
  524. }
  525. public ConfigurationProperty DefaultCollectionProperty {
  526. get {
  527. if (defaultCollectionProperty == null) {
  528. if (properties != null)
  529. foreach (ConfigurationProperty p in properties) {
  530. if (p.IsDefaultCollection) defaultCollectionProperty = p;
  531. break;
  532. }
  533. }
  534. return defaultCollectionProperty;
  535. }
  536. }
  537. }
  538. }
  539. #endif