Merge pull request #347 from JamesB7/master
[mono.git] / mcs / class / System.Configuration / System.Configuration / ConfigurationElement.cs
1 //
2 // System.Configuration.ConfigurationElement.cs
3 //
4 // Authors:
5 //      Duncan Mak (duncan@ximian.com)
6 //      Lluis Sanchez Gual (lluis@novell.com)
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
30 #if NET_2_0
31 using System.Collections;
32 using System.Xml;
33 using System.Reflection;
34 using System.IO;
35 using System.ComponentModel;
36
37 namespace System.Configuration
38 {
39         public abstract class ConfigurationElement
40         {
41                 string rawXml;
42                 bool modified;
43                 ElementMap map;
44                 ConfigurationPropertyCollection keyProps;
45                 ConfigurationElementCollection defaultCollection;
46                 bool readOnly;
47                 ElementInformation elementInfo;
48                 ConfigurationElementProperty elementProperty;
49                 Configuration _configuration;
50                 bool elementPresent;
51
52                 internal Configuration Configuration {
53                         get { return _configuration; }
54                         set { _configuration = value; }
55                 }
56
57                 protected ConfigurationElement ()
58                 {
59                 }
60                 
61                 internal virtual void InitFromProperty (PropertyInformation propertyInfo)
62                 {
63                         elementInfo = new ElementInformation (this, propertyInfo);
64                         Init ();
65                 }
66                 
67                 public ElementInformation ElementInformation {
68                         get {
69                                 if (elementInfo == null)
70                                         elementInfo = new ElementInformation (this, null);
71                                 return elementInfo;
72                         }
73                 }
74
75                 internal string RawXml {
76                         get { return rawXml; }
77                         set {
78                                 // FIXME: this hack is nasty. We should make
79                                 // some refactory on the entire assembly.
80                                 if (rawXml == null || value != null)
81                                         rawXml = value;
82                         }
83                 }
84
85                 protected internal virtual void Init ()
86                 {
87                 }
88
89                 protected internal virtual ConfigurationElementProperty ElementProperty {
90                         get {
91                                 if (elementProperty == null)
92                                         elementProperty = new ConfigurationElementProperty (ElementInformation.Validator);
93                                 return elementProperty;
94                         }
95                 }
96
97                 [MonoTODO]
98                 protected ContextInformation EvaluationContext {
99                         get {
100                                 if (Configuration != null)
101                                         return Configuration.EvaluationContext;
102                                 throw new NotImplementedException ();
103                         }
104                 }
105
106                 ConfigurationLockCollection lockAllAttributesExcept;
107                 public ConfigurationLockCollection LockAllAttributesExcept {
108                         get {
109                                 if (lockAllAttributesExcept == null) {
110                                         lockAllAttributesExcept = new ConfigurationLockCollection (this, ConfigurationLockType.Attribute | ConfigurationLockType.Exclude);
111                                 }
112
113                                 return lockAllAttributesExcept;
114                         }
115                 }
116
117                 ConfigurationLockCollection lockAllElementsExcept;
118                 public ConfigurationLockCollection LockAllElementsExcept {
119                         get {
120                                 if (lockAllElementsExcept == null) {
121                                         lockAllElementsExcept = new ConfigurationLockCollection (this, ConfigurationLockType.Element | ConfigurationLockType.Exclude);
122                                 }
123
124                                 return lockAllElementsExcept;
125                         }
126                 }
127
128                 ConfigurationLockCollection lockAttributes;
129                 public ConfigurationLockCollection LockAttributes {
130                         get {
131                                 if (lockAttributes == null) {
132                                         lockAttributes = new ConfigurationLockCollection (this, ConfigurationLockType.Attribute);
133                                 }
134
135                                 return lockAttributes;
136                         }
137                 }
138
139                 ConfigurationLockCollection lockElements;
140                 public ConfigurationLockCollection LockElements {
141                         get {
142                                 if (lockElements == null) {
143                                         lockElements = new ConfigurationLockCollection (this, ConfigurationLockType.Element);
144                                 }
145
146                                 return lockElements;
147                         }
148                 }
149
150                 bool lockItem;
151                 public bool LockItem {
152                         get { return lockItem; }
153                         set { lockItem = value; }
154                 }
155
156                 [MonoTODO]
157                 protected virtual void ListErrors (IList list)
158                 {
159                         throw new NotImplementedException ();
160                 }
161
162                 [MonoTODO]
163                 protected void SetPropertyValue (ConfigurationProperty prop, object value, bool ignoreLocks)
164                 {
165                         try {
166                                 /* XXX all i know for certain is that Validation happens here */
167                                 prop.Validate (value);
168
169                                 /* XXX presumably the actual setting of the
170                                  * property happens here instead of in the
171                                  * set_Item code below, but that would mean
172                                  * the Value needs to be stuffed in the
173                                  * property, not the propertyinfo (or else the
174                                  * property needs a ref to the property info
175                                  * to correctly set the value). */
176                         }
177                         catch (Exception e) {
178                                 throw new ConfigurationErrorsException (String.Format ("The value for the property '{0}' is not valid. The error is: {1}", prop.Name, e.Message), e);
179                         }
180                 }
181
182                 internal ConfigurationPropertyCollection GetKeyProperties ()
183                 {
184                         if (keyProps != null) return keyProps;
185                         
186                         ConfigurationPropertyCollection tmpkeyProps = new ConfigurationPropertyCollection ();
187                                 foreach (ConfigurationProperty prop in Properties) {
188                                         if (prop.IsKey)
189                                         tmpkeyProps.Add (prop);
190                                 }
191
192                         return keyProps = tmpkeyProps;
193                 }
194
195                 internal ConfigurationElementCollection GetDefaultCollection ()
196                 {
197                         if (defaultCollection != null) return defaultCollection;
198
199                         ConfigurationProperty defaultCollectionProp = null;
200
201                         foreach (ConfigurationProperty prop in Properties) {
202                                 if (prop.IsDefaultCollection) {
203                                         defaultCollectionProp = prop;
204                                         break;
205                                 }
206                         }
207
208                         if (defaultCollectionProp != null) {
209                                 defaultCollection = this [defaultCollectionProp] as ConfigurationElementCollection;
210                         }
211
212                         return defaultCollection;
213                 }
214
215                 protected internal object this [ConfigurationProperty property] {
216                         get { return this [property.Name]; }
217                         set { this [property.Name] = value; }
218                 }
219
220                 protected internal object this [string property_name] {
221                         get {
222                                 PropertyInformation pi = ElementInformation.Properties [property_name];
223                                 if (pi == null)
224                                         throw new InvalidOperationException ("Property '" + property_name + "' not found in configuration element");
225
226                                 return pi.Value;
227                         }
228
229                         set {
230                                 PropertyInformation pi = ElementInformation.Properties [property_name];
231                                 if (pi == null)
232                                         throw new InvalidOperationException ("Property '" + property_name + "' not found in configuration element");
233
234                                 SetPropertyValue (pi.Property, value, false);
235
236                                 pi.Value = value;
237                                 modified = true;
238                         }
239                 }
240
241                 protected internal virtual ConfigurationPropertyCollection Properties {
242                         get {
243                                 if (map == null)
244                                         map = ElementMap.GetMap (GetType());
245                                 return map.Properties;
246                         }
247                 }
248
249                 public override bool Equals (object compareTo)
250                 {
251                         ConfigurationElement other = compareTo as ConfigurationElement;
252                         if (other == null) return false;
253                         if (GetType() != other.GetType()) return false;
254                         
255                         foreach (ConfigurationProperty prop in Properties) {
256                                 if (!object.Equals (this [prop], other [prop]))
257                                         return false;
258                         }
259                         return true;
260                 }
261
262                 public override int GetHashCode ()
263                 {
264                         int code = 0;
265                         object o;
266                         
267                         foreach (ConfigurationProperty prop in Properties) {
268                                 o = this [prop];
269                                 if (o == null)
270                                         continue;
271                                 
272                                 code += o.GetHashCode ();
273                         }
274                         
275                         return code;
276                 }
277
278                 internal virtual bool HasValues ()
279                 {
280                         foreach (PropertyInformation pi in ElementInformation.Properties)
281                                 if (pi.ValueOrigin != PropertyValueOrigin.Default)
282                                         return true;
283                         
284                         return false;
285                 }
286
287                 internal virtual bool HasLocalModifications ()
288                 {
289                         foreach (PropertyInformation pi in ElementInformation.Properties)
290                                 if (pi.ValueOrigin == PropertyValueOrigin.SetHere && pi.IsModified)
291                                         return true;
292                         
293                         return false;
294                 }
295                 
296                 protected internal virtual void DeserializeElement (XmlReader reader, bool serializeCollectionKey)
297                 {
298                         Hashtable readProps = new Hashtable ();
299                         
300                         reader.MoveToContent ();
301                         elementPresent = true;
302                         
303                         while (reader.MoveToNextAttribute ())
304                         {
305                                 PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
306                                 if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
307                                         /* handle the built in ConfigurationElement attributes here */
308                                         if (reader.LocalName == "lockAllAttributesExcept") {
309                                                 LockAllAttributesExcept.SetFromList (reader.Value);
310                                         }
311                                         else if (reader.LocalName == "lockAllElementsExcept") {
312                                                 LockAllElementsExcept.SetFromList (reader.Value);
313                                         }
314                                         else if (reader.LocalName == "lockAttributes") {
315                                                 LockAttributes.SetFromList (reader.Value);
316                                         }
317                                         else if (reader.LocalName == "lockElements") {
318                                                 LockElements.SetFromList (reader.Value);
319                                         }
320                                         else if (reader.LocalName == "lockItem") {
321                                                 LockItem = (reader.Value.ToLowerInvariant () == "true");
322                                         }
323                                         else if (reader.LocalName == "xmlns") {
324                                                 /* ignore */
325                                         } else if (this is ConfigurationSection && reader.LocalName == "configSource") {
326                                                 /* ignore */
327                                         } else if (!OnDeserializeUnrecognizedAttribute (reader.LocalName, reader.Value))
328                                                 throw new ConfigurationErrorsException ("Unrecognized attribute '" + reader.LocalName + "'.", reader);
329
330                                         continue;
331                                 }
332                                 
333                                 if (readProps.ContainsKey (prop))
334                                         throw new ConfigurationErrorsException ("The attribute '" + prop.Name + "' may only appear once in this element.", reader);
335
336                                 string value = null;
337                                 try {
338                                         value = reader.Value;
339                                         ValidateValue (prop.Property, value);
340                                         prop.SetStringValue (value);
341                                 } catch (ConfigurationErrorsException) {
342                                         throw;
343                                 } catch (ConfigurationException) {
344                                         throw;
345                                 } catch (Exception ex) {
346                                         string msg = String.Format ("The value for the property '{0}' is not valid. The error is: {1}", prop.Name, ex.Message);
347                                         throw new ConfigurationErrorsException (msg, reader);
348                                 }
349                                 readProps [prop] = prop.Name;
350                         
351                                 ConfigXmlTextReader _reader = reader as ConfigXmlTextReader;
352                                 if (_reader != null){
353                                         prop.Source = _reader.Filename;
354                                         prop.LineNumber = _reader.LineNumber;
355                                 }
356                         }
357                         
358                         reader.MoveToElement ();
359                         if (reader.IsEmptyElement) {
360                                 reader.Skip ();
361                         } else {
362                                 int depth = reader.Depth;
363
364                                 reader.ReadStartElement ();
365                                 reader.MoveToContent ();
366
367                                 do {
368                                         if (reader.NodeType != XmlNodeType.Element) {
369                                                 reader.Skip ();
370                                                 continue;
371                                         }
372                                         
373                                         PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
374                                         if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
375                                                 if (!OnDeserializeUnrecognizedElement (reader.LocalName, reader)) {
376                                                         if (prop == null) {
377                                                                 ConfigurationElementCollection c = GetDefaultCollection ();
378                                                                 if (c != null && c.OnDeserializeUnrecognizedElement (reader.LocalName, reader))
379                                                                         continue;
380                                                         }
381                                                         throw new ConfigurationErrorsException ("Unrecognized element '" + reader.LocalName + "'.", reader);
382                                                 }
383                                                 continue;
384                                         }
385                                         
386                                         if (!prop.IsElement)
387                                                 throw new ConfigurationErrorsException ("Property '" + prop.Name + "' is not a ConfigurationElement.");
388                                         
389                                         if (readProps.Contains (prop))
390                                                 throw new ConfigurationErrorsException ("The element <" + prop.Name + "> may only appear once in this section.", reader);
391                                         
392                                         ConfigurationElement val = (ConfigurationElement) prop.Value;
393                                         val.DeserializeElement (reader, serializeCollectionKey);
394                                         readProps [prop] = prop.Name;
395
396                                         if(depth == reader.Depth)
397                                                 reader.Read();
398
399                                 } while (depth < reader.Depth);                         
400                         }
401                         
402                         modified = false;
403                                 
404                         foreach (PropertyInformation prop in ElementInformation.Properties)
405                                 if (!String.IsNullOrEmpty(prop.Name) && prop.IsRequired && !readProps.ContainsKey (prop)) {
406                                         PropertyInformation p = ElementInformation.Properties [prop.Name];
407                                         if (p == null) {
408                                                 object val = OnRequiredPropertyNotFound (prop.Name);
409                                                 if (!object.Equals (val, prop.DefaultValue)) {
410                                                         prop.Value = val;
411                                                         prop.IsModified = false;
412                                                 }
413                                         }
414                                 }
415
416                         PostDeserialize ();
417                 }
418
419                 protected virtual bool OnDeserializeUnrecognizedAttribute (string name, string value)
420                 {
421                         return false;
422                 }
423
424                 protected virtual bool OnDeserializeUnrecognizedElement (string element, XmlReader reader)
425                 {
426                         return false;
427                 }
428                 
429                 protected virtual object OnRequiredPropertyNotFound (string name)
430                 {
431                         throw new ConfigurationErrorsException ("Required attribute '" + name + "' not found.");
432                 }
433                 
434                 protected virtual void PreSerialize (XmlWriter writer)
435                 {
436                 }
437
438                 protected virtual void PostDeserialize ()
439                 {
440                 }
441
442                 protected internal virtual void InitializeDefault ()
443                 {
444                 }
445
446                 protected internal virtual bool IsModified ()
447                 {
448                         return modified;
449                 }
450                 
451                 protected internal virtual void SetReadOnly ()
452                 {
453                         readOnly = true;
454                 }
455                 
456                 public virtual bool IsReadOnly ()
457                 {
458                         return readOnly;
459                 }
460
461                 protected internal virtual void Reset (ConfigurationElement parentElement)
462                 {
463                         elementPresent = false;
464                         
465                         if (parentElement != null)
466                                 ElementInformation.Reset (parentElement.ElementInformation);
467                         else
468                                 InitializeDefault ();
469                 }
470
471                 protected internal virtual void ResetModified ()
472                 {
473                         modified = false;
474                         foreach (PropertyInformation p in ElementInformation.Properties)
475                                 p.IsModified = false;
476                 }
477
478                 protected internal virtual bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
479                 {
480                         PreSerialize (writer);
481                         
482                         if (serializeCollectionKey) {
483                                 ConfigurationPropertyCollection props = GetKeyProperties ();
484                                 foreach (ConfigurationProperty prop in props)
485                                         writer.WriteAttributeString (prop.Name, prop.ConvertToString (this[prop.Name]));
486                                 return props.Count > 0;
487                         }
488                         
489                         bool wroteData = false;
490                         
491                         foreach (PropertyInformation prop in ElementInformation.Properties)
492                         {
493                                 if (prop.IsElement || prop.ValueOrigin == PropertyValueOrigin.Default)
494                                         continue;
495                                 
496                                 if (!object.Equals (prop.Value, prop.DefaultValue)) {
497                                         writer.WriteAttributeString (prop.Name, prop.GetStringValue ());
498                                         wroteData = true;
499                                 }
500                         }
501                         
502                         foreach (PropertyInformation prop in ElementInformation.Properties)
503                         {
504                                 if (!prop.IsElement)
505                                         continue;
506                                 
507                                 ConfigurationElement val = (ConfigurationElement) prop.Value;
508                                 if (val != null)
509                                         wroteData = val.SerializeToXmlElement (writer, prop.Name) || wroteData;
510                         }
511                         return wroteData;
512                 }
513                                 
514                 protected internal virtual bool SerializeToXmlElement (
515                                 XmlWriter writer, string elementName)
516                 {
517                         if (!HasValues ())
518                                 return false;
519
520                         if (elementName != null && elementName != "")
521                                 writer.WriteStartElement (elementName);
522                         bool res = SerializeElement (writer, false);
523                         if (elementName != null && elementName != "")
524                                 writer.WriteEndElement ();
525                         return res;
526                 }
527
528                 protected internal virtual void Unmerge (
529                                 ConfigurationElement source, ConfigurationElement parent,
530                                 ConfigurationSaveMode updateMode)
531                 {
532                         if (parent != null && source.GetType() != parent.GetType())
533                                 throw new ConfigurationErrorsException ("Can't unmerge two elements of different type");
534                         
535                         foreach (PropertyInformation prop in source.ElementInformation.Properties)
536                         {
537                                 if (prop.ValueOrigin == PropertyValueOrigin.Default)
538                                         continue;
539                                 
540                                 PropertyInformation unmergedProp = ElementInformation.Properties [prop.Name];
541                                 
542                                 object sourceValue = prop.Value;
543                                 if      (parent == null || !parent.HasValue (prop.Name)) {
544                                         unmergedProp.Value = sourceValue;
545                                         continue;
546                                 }
547                                 else if (sourceValue != null) {
548                                         object parentValue = parent [prop.Name];
549                                         if (prop.IsElement) {
550                                                 if (parentValue != null) {
551                                                         ConfigurationElement copy = (ConfigurationElement) unmergedProp.Value;
552                                                         copy.Unmerge ((ConfigurationElement) sourceValue, (ConfigurationElement) parentValue, updateMode);
553                                                 }
554                                                 else
555                                                         unmergedProp.Value = sourceValue;
556                                         }
557                                         else {
558                                                 if (!object.Equals (sourceValue, parentValue) || 
559                                                         (updateMode == ConfigurationSaveMode.Full) ||
560                                                         (updateMode == ConfigurationSaveMode.Modified && prop.ValueOrigin == PropertyValueOrigin.SetHere))
561                                                         unmergedProp.Value = sourceValue;
562                                         }
563                                 }
564                         }
565                 }
566                 
567                 internal bool HasValue (string propName)
568                 {
569                         PropertyInformation info = ElementInformation.Properties [propName];
570                         return info != null && info.ValueOrigin != PropertyValueOrigin.Default;
571                 }
572                 
573                 internal bool IsReadFromConfig (string propName)
574                 {
575                         PropertyInformation info = ElementInformation.Properties [propName];
576                         return info != null && info.ValueOrigin == PropertyValueOrigin.SetHere;
577                 }
578
579                 internal bool IsElementPresent
580                 {
581                         get {   return elementPresent;  }
582                 }
583
584                 void ValidateValue (ConfigurationProperty p, string value)
585                 {
586                         ConfigurationValidatorBase validator;
587                         if (p == null || (validator = p.Validator) == null)
588                                 return;
589                         
590                         if (!validator.CanValidate (p.Type))
591                                 throw new ConfigurationErrorsException (
592                                         String.Format ("Validator does not support type {0}", p.Type));
593                         validator.Validate (p.ConvertFromString (value));
594                 }
595         }
596         
597         internal class ElementMap
598         {
599 #if TARGET_JVM
600                 const string elementMapsKey = "ElementMap_elementMaps";
601                 static Hashtable elementMaps
602                 {
603                         get
604                         {
605                                 Hashtable tbl = (Hashtable) AppDomain.CurrentDomain.GetData (elementMapsKey);
606                                 if (tbl == null) {
607                                         lock (typeof (ElementMap)) {
608                                                 tbl = (Hashtable) AppDomain.CurrentDomain.GetData (elementMapsKey);
609                                                 if (tbl == null) {
610                                                         tbl = Hashtable.Synchronized (new Hashtable ());
611                                                         AppDomain.CurrentDomain.SetData (elementMapsKey, tbl);
612                                                 }
613                                         }
614                                 }
615                                 return tbl;
616                         }
617                 }
618 #else
619                 static readonly Hashtable elementMaps = Hashtable.Synchronized (new Hashtable ());
620 #endif
621
622                 readonly ConfigurationPropertyCollection properties;
623                 readonly ConfigurationCollectionAttribute collectionAttribute;
624
625                 public static ElementMap GetMap (Type t)
626                 {
627                         ElementMap map = elementMaps [t] as ElementMap;
628                         if (map != null) return map;
629                         map = new ElementMap (t);
630                         elementMaps [t] = map;
631                         return map;
632                 }
633                 
634                 public ElementMap (Type t)
635                 {
636                         properties = new ConfigurationPropertyCollection ();
637                 
638                         collectionAttribute = Attribute.GetCustomAttribute (t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
639                         
640                         PropertyInfo[] props = t.GetProperties (BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static|BindingFlags.Instance);
641                         foreach (PropertyInfo prop in props)
642                         {
643                                 ConfigurationPropertyAttribute at = Attribute.GetCustomAttribute (prop, typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute;
644                                 if (at == null) continue;
645                                 string name = at.Name != null ? at.Name : prop.Name;
646
647                                 ConfigurationValidatorAttribute validatorAttr = Attribute.GetCustomAttribute (prop, typeof (ConfigurationValidatorAttribute)) as ConfigurationValidatorAttribute;
648                                 ConfigurationValidatorBase validator = validatorAttr != null ? validatorAttr.ValidatorInstance : null;
649
650                                 TypeConverterAttribute convertAttr = (TypeConverterAttribute) Attribute.GetCustomAttribute (prop, typeof (TypeConverterAttribute));
651                                 TypeConverter converter = convertAttr != null ? (TypeConverter) Activator.CreateInstance (Type.GetType (convertAttr.ConverterTypeName), true) : null;
652                                 ConfigurationProperty cp = new ConfigurationProperty (name, prop.PropertyType, at.DefaultValue, converter, validator, at.Options);
653
654                                 cp.CollectionAttribute = Attribute.GetCustomAttribute (prop, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;                             
655                                 properties.Add (cp);
656                         }
657                 }
658
659                 public ConfigurationCollectionAttribute CollectionAttribute
660                 {
661                         get { return collectionAttribute; }
662                 }
663                 
664                 public bool HasProperties
665                 {
666                         get { return properties.Count > 0; }
667                 }
668                 
669                 public ConfigurationPropertyCollection Properties
670                 {
671                         get {
672                                 return properties;
673                         }
674                 }
675         }
676 }
677
678 #endif