System.Drawing: added email to icon and test file headers
[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                                 
353                                 prop.Source = _reader.Filename;
354                                 prop.LineNumber = _reader.LineNumber;
355                         }
356                         
357                         reader.MoveToElement ();
358                         if (reader.IsEmptyElement) {
359                                 reader.Skip ();
360                         } else {
361                                 int depth = reader.Depth;
362
363                                 reader.ReadStartElement ();
364                                 reader.MoveToContent ();
365
366                                 do {
367                                         if (reader.NodeType != XmlNodeType.Element) {
368                                                 reader.Skip ();
369                                                 continue;
370                                         }
371                                         
372                                         PropertyInformation prop = ElementInformation.Properties [reader.LocalName];
373                                         if (prop == null || (serializeCollectionKey && !prop.IsKey)) {
374                                                 if (!OnDeserializeUnrecognizedElement (reader.LocalName, reader)) {
375                                                         if (prop == null) {
376                                                                 ConfigurationElementCollection c = GetDefaultCollection ();
377                                                                 if (c != null && c.OnDeserializeUnrecognizedElement (reader.LocalName, reader))
378                                                                         continue;
379                                                         }
380                                                         throw new ConfigurationErrorsException ("Unrecognized element '" + reader.LocalName + "'.", reader);
381                                                 }
382                                                 continue;
383                                         }
384                                         
385                                         if (!prop.IsElement)
386                                                 throw new ConfigurationErrorsException ("Property '" + prop.Name + "' is not a ConfigurationElement.");
387                                         
388                                         if (readProps.Contains (prop))
389                                                 throw new ConfigurationErrorsException ("The element <" + prop.Name + "> may only appear once in this section.", reader);
390                                         
391                                         ConfigurationElement val = (ConfigurationElement) prop.Value;
392                                         val.DeserializeElement (reader, serializeCollectionKey);
393                                         readProps [prop] = prop.Name;
394
395                                         if(depth == reader.Depth)
396                                                 reader.Read();
397
398                                 } while (depth < reader.Depth);                         
399                         }
400                         
401                         modified = false;
402                                 
403                         foreach (PropertyInformation prop in ElementInformation.Properties)
404                                 if (!String.IsNullOrEmpty(prop.Name) && prop.IsRequired && !readProps.ContainsKey (prop)) {
405                                         PropertyInformation p = ElementInformation.Properties [prop.Name];
406                                         if (p == null) {
407                                                 object val = OnRequiredPropertyNotFound (prop.Name);
408                                                 if (!object.Equals (val, prop.DefaultValue)) {
409                                                         prop.Value = val;
410                                                         prop.IsModified = false;
411                                                 }
412                                         }
413                                 }
414
415                         PostDeserialize ();
416                 }
417
418                 protected virtual bool OnDeserializeUnrecognizedAttribute (string name, string value)
419                 {
420                         return false;
421                 }
422
423                 protected virtual bool OnDeserializeUnrecognizedElement (string element, XmlReader reader)
424                 {
425                         return false;
426                 }
427                 
428                 protected virtual object OnRequiredPropertyNotFound (string name)
429                 {
430                         throw new ConfigurationErrorsException ("Required attribute '" + name + "' not found.");
431                 }
432                 
433                 protected virtual void PreSerialize (XmlWriter writer)
434                 {
435                 }
436
437                 protected virtual void PostDeserialize ()
438                 {
439                 }
440
441                 protected internal virtual void InitializeDefault ()
442                 {
443                 }
444
445                 protected internal virtual bool IsModified ()
446                 {
447                         return modified;
448                 }
449                 
450                 protected internal virtual void SetReadOnly ()
451                 {
452                         readOnly = true;
453                 }
454                 
455                 public virtual bool IsReadOnly ()
456                 {
457                         return readOnly;
458                 }
459
460                 protected internal virtual void Reset (ConfigurationElement parentElement)
461                 {
462                         elementPresent = false;
463                         
464                         if (parentElement != null)
465                                 ElementInformation.Reset (parentElement.ElementInformation);
466                         else
467                                 InitializeDefault ();
468                 }
469
470                 protected internal virtual void ResetModified ()
471                 {
472                         modified = false;
473                         foreach (PropertyInformation p in ElementInformation.Properties)
474                                 p.IsModified = false;
475                 }
476
477                 protected internal virtual bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
478                 {
479                         PreSerialize (writer);
480                         
481                         if (serializeCollectionKey) {
482                                 ConfigurationPropertyCollection props = GetKeyProperties ();
483                                 foreach (ConfigurationProperty prop in props)
484                                         writer.WriteAttributeString (prop.Name, prop.ConvertToString (this[prop.Name]));
485                                 return props.Count > 0;
486                         }
487                         
488                         bool wroteData = false;
489                         
490                         foreach (PropertyInformation prop in ElementInformation.Properties)
491                         {
492                                 if (prop.IsElement || prop.ValueOrigin == PropertyValueOrigin.Default)
493                                         continue;
494                                 
495                                 if (!object.Equals (prop.Value, prop.DefaultValue)) {
496                                         writer.WriteAttributeString (prop.Name, prop.GetStringValue ());
497                                         wroteData = true;
498                                 }
499                         }
500                         
501                         foreach (PropertyInformation prop in ElementInformation.Properties)
502                         {
503                                 if (!prop.IsElement)
504                                         continue;
505                                 
506                                 ConfigurationElement val = (ConfigurationElement) prop.Value;
507                                 if (val != null)
508                                         wroteData = val.SerializeToXmlElement (writer, prop.Name) || wroteData;
509                         }
510                         return wroteData;
511                 }
512                                 
513                 protected internal virtual bool SerializeToXmlElement (
514                                 XmlWriter writer, string elementName)
515                 {
516                         if (!HasValues ())
517                                 return false;
518
519                         if (elementName != null && elementName != "")
520                                 writer.WriteStartElement (elementName);
521                         bool res = SerializeElement (writer, false);
522                         if (elementName != null && elementName != "")
523                                 writer.WriteEndElement ();
524                         return res;
525                 }
526
527                 protected internal virtual void Unmerge (
528                                 ConfigurationElement source, ConfigurationElement parent,
529                                 ConfigurationSaveMode updateMode)
530                 {
531                         if (parent != null && source.GetType() != parent.GetType())
532                                 throw new ConfigurationErrorsException ("Can't unmerge two elements of different type");
533                         
534                         foreach (PropertyInformation prop in source.ElementInformation.Properties)
535                         {
536                                 if (prop.ValueOrigin == PropertyValueOrigin.Default)
537                                         continue;
538                                 
539                                 PropertyInformation unmergedProp = ElementInformation.Properties [prop.Name];
540                                 
541                                 object sourceValue = prop.Value;
542                                 if      (parent == null || !parent.HasValue (prop.Name)) {
543                                         unmergedProp.Value = sourceValue;
544                                         continue;
545                                 }
546                                 else if (sourceValue != null) {
547                                         object parentValue = parent [prop.Name];
548                                         if (prop.IsElement) {
549                                                 if (parentValue != null) {
550                                                         ConfigurationElement copy = (ConfigurationElement) unmergedProp.Value;
551                                                         copy.Unmerge ((ConfigurationElement) sourceValue, (ConfigurationElement) parentValue, updateMode);
552                                                 }
553                                                 else
554                                                         unmergedProp.Value = sourceValue;
555                                         }
556                                         else {
557                                                 if (!object.Equals (sourceValue, parentValue) || 
558                                                         (updateMode == ConfigurationSaveMode.Full) ||
559                                                         (updateMode == ConfigurationSaveMode.Modified && prop.ValueOrigin == PropertyValueOrigin.SetHere))
560                                                         unmergedProp.Value = sourceValue;
561                                         }
562                                 }
563                         }
564                 }
565                 
566                 internal bool HasValue (string propName)
567                 {
568                         PropertyInformation info = ElementInformation.Properties [propName];
569                         return info != null && info.ValueOrigin != PropertyValueOrigin.Default;
570                 }
571                 
572                 internal bool IsReadFromConfig (string propName)
573                 {
574                         PropertyInformation info = ElementInformation.Properties [propName];
575                         return info != null && info.ValueOrigin == PropertyValueOrigin.SetHere;
576                 }
577
578                 internal bool IsElementPresent
579                 {
580                         get {   return elementPresent;  }
581                 }
582
583                 void ValidateValue (ConfigurationProperty p, string value)
584                 {
585                         ConfigurationValidatorBase validator;
586                         if (p == null || (validator = p.Validator) == null)
587                                 return;
588                         
589                         if (!validator.CanValidate (p.Type))
590                                 throw new ConfigurationErrorsException (
591                                         String.Format ("Validator does not support type {0}", p.Type));
592                         validator.Validate (p.ConvertFromString (value));
593                 }
594         }
595         
596         internal class ElementMap
597         {
598 #if TARGET_JVM
599                 const string elementMapsKey = "ElementMap_elementMaps";
600                 static Hashtable elementMaps
601                 {
602                         get
603                         {
604                                 Hashtable tbl = (Hashtable) AppDomain.CurrentDomain.GetData (elementMapsKey);
605                                 if (tbl == null) {
606                                         lock (typeof (ElementMap)) {
607                                                 tbl = (Hashtable) AppDomain.CurrentDomain.GetData (elementMapsKey);
608                                                 if (tbl == null) {
609                                                         tbl = Hashtable.Synchronized (new Hashtable ());
610                                                         AppDomain.CurrentDomain.SetData (elementMapsKey, tbl);
611                                                 }
612                                         }
613                                 }
614                                 return tbl;
615                         }
616                 }
617 #else
618                 static readonly Hashtable elementMaps = Hashtable.Synchronized (new Hashtable ());
619 #endif
620
621                 readonly ConfigurationPropertyCollection properties;
622                 readonly ConfigurationCollectionAttribute collectionAttribute;
623
624                 public static ElementMap GetMap (Type t)
625                 {
626                         ElementMap map = elementMaps [t] as ElementMap;
627                         if (map != null) return map;
628                         map = new ElementMap (t);
629                         elementMaps [t] = map;
630                         return map;
631                 }
632                 
633                 public ElementMap (Type t)
634                 {
635                         properties = new ConfigurationPropertyCollection ();
636                 
637                         collectionAttribute = Attribute.GetCustomAttribute (t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
638                         
639                         PropertyInfo[] props = t.GetProperties (BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static|BindingFlags.Instance);
640                         foreach (PropertyInfo prop in props)
641                         {
642                                 ConfigurationPropertyAttribute at = Attribute.GetCustomAttribute (prop, typeof(ConfigurationPropertyAttribute)) as ConfigurationPropertyAttribute;
643                                 if (at == null) continue;
644                                 string name = at.Name != null ? at.Name : prop.Name;
645
646                                 ConfigurationValidatorAttribute validatorAttr = Attribute.GetCustomAttribute (prop, typeof (ConfigurationValidatorAttribute)) as ConfigurationValidatorAttribute;
647                                 ConfigurationValidatorBase validator = validatorAttr != null ? validatorAttr.ValidatorInstance : null;
648
649                                 TypeConverterAttribute convertAttr = (TypeConverterAttribute) Attribute.GetCustomAttribute (prop, typeof (TypeConverterAttribute));
650                                 TypeConverter converter = convertAttr != null ? (TypeConverter) Activator.CreateInstance (Type.GetType (convertAttr.ConverterTypeName), true) : null;
651                                 ConfigurationProperty cp = new ConfigurationProperty (name, prop.PropertyType, at.DefaultValue, converter, validator, at.Options);
652
653                                 cp.CollectionAttribute = Attribute.GetCustomAttribute (prop, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;                             
654                                 properties.Add (cp);
655                         }
656                 }
657
658                 public ConfigurationCollectionAttribute CollectionAttribute
659                 {
660                         get { return collectionAttribute; }
661                 }
662                 
663                 public bool HasProperties
664                 {
665                         get { return properties.Count > 0; }
666                 }
667                 
668                 public ConfigurationPropertyCollection Properties
669                 {
670                         get {
671                                 return properties;
672                         }
673                 }
674         }
675 }
676
677 #endif