Merge pull request #642 from Ventero/CleanCopyLocal
[mono.git] / mcs / class / System.Configuration / System.Configuration / Configuration.cs
1 //
2 // System.Configuration.Configuration.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 using System;
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Configuration.Internal;
34 using System.ComponentModel;
35 using System.Reflection;
36 using System.Xml;
37 using System.IO;
38
39 namespace System.Configuration {
40
41         // For configuration document, use this XmlDocument instead of the standard one. This ignores xmlns attribute for MS.
42         internal class ConfigurationXmlDocument : XmlDocument
43         {
44                 public override XmlElement CreateElement (string prefix, string localName, string namespaceURI)
45                 {
46                         if (namespaceURI == "http://schemas.microsoft.com/.NetConfiguration/v2.0")
47                                 return base.CreateElement (String.Empty, localName, String.Empty);
48                         else
49                                 return base.CreateElement (prefix, localName, namespaceURI);
50                 }
51         }
52
53         public sealed class Configuration
54         {               
55                 Configuration parent;
56                 Hashtable elementData = new Hashtable ();
57                 string streamName;
58                 ConfigurationSectionGroup rootSectionGroup;
59                 ConfigurationLocationCollection locations;
60                 SectionGroupInfo rootGroup;
61                 IConfigSystem system;
62                 bool hasFile;
63                 string rootNamespace;
64                 
65                 string configPath;
66                 string locationConfigPath;
67                 string locationSubPath;
68
69                 internal static event ConfigurationSaveEventHandler SaveStart;
70                 internal static event ConfigurationSaveEventHandler SaveEnd;
71                 
72                 internal Configuration (Configuration parent, string locationSubPath)
73                 {
74                         this.parent = parent;
75                         this.system = parent.system;
76                         this.rootGroup = parent.rootGroup;
77                         this.locationSubPath = locationSubPath;
78                         this.configPath = parent.ConfigPath;
79                 }
80                 
81                 internal Configuration (InternalConfigurationSystem system, string locationSubPath)
82                 {
83                         hasFile = true;
84                         this.system = system;
85
86                         system.InitForConfiguration (ref locationSubPath, out configPath, out locationConfigPath);
87                         
88                         Configuration parent = null;
89                         
90                         if (locationSubPath != null) {
91                                 parent = new Configuration (system, locationSubPath);
92                                 if (locationConfigPath != null)
93                                         parent = parent.FindLocationConfiguration (locationConfigPath, parent);
94                         }
95                         
96                         Init (system, configPath, parent);
97                 }
98                 
99                 internal Configuration FindLocationConfiguration (string relativePath, Configuration defaultConfiguration)
100                 {
101                         Configuration parentConfig = defaultConfiguration;
102
103                         if (!String.IsNullOrEmpty (LocationConfigPath)) {
104                                 Configuration parentFile = GetParentWithFile ();
105                                 if (parentFile != null) {
106                                         string parentRelativePath = system.Host.GetConfigPathFromLocationSubPath (configPath, relativePath);
107                                         parentConfig = parentFile.FindLocationConfiguration (parentRelativePath, defaultConfiguration);
108                                 }
109                         }
110
111                         string relConfigPath = configPath.Substring (1) + "/";
112                         if (relativePath.StartsWith (relConfigPath, StringComparison.Ordinal))
113                                 relativePath = relativePath.Substring (relConfigPath.Length);
114
115                         ConfigurationLocation loc = Locations.FindBest (relativePath);
116                         if (loc == null)
117                                 return parentConfig;
118                         
119                         loc.SetParentConfiguration (parentConfig);
120                         return loc.OpenConfiguration ();
121                 }
122                 
123                 internal void Init (IConfigSystem system, string configPath, Configuration parent)
124                 {
125                         this.system = system;
126                         this.configPath = configPath;
127                         streamName = system.Host.GetStreamName (configPath);
128                         this.parent = parent;
129                         if (parent != null)
130                                 rootGroup = parent.rootGroup;
131                         else {
132                                 rootGroup = new SectionGroupInfo ();
133                                 rootGroup.StreamName = streamName;
134                         }
135                         
136                         if (streamName != null)
137                                 Load ();
138                 }
139                 
140                 internal Configuration Parent {
141                         get { return parent; }
142                         set { parent = value; }
143                 }
144                 
145                 internal Configuration GetParentWithFile ()
146                 {
147                         Configuration parentFile = Parent;
148                         while (parentFile != null && !parentFile.HasFile)
149                                 parentFile = parentFile.Parent;
150                         return parentFile;
151                 }
152                 
153                 internal string FileName {
154                         get { return streamName; }
155                 }
156
157                 internal IInternalConfigHost ConfigHost {
158                         get { return system.Host; }
159                 }
160                 
161                 internal string LocationConfigPath {
162                         get { return locationConfigPath; }
163                 }
164
165                 internal string GetLocationSubPath ()
166                 {
167                         Configuration confg = parent;
168                         string path = null;
169                         while (confg != null) {
170                                 path = confg.locationSubPath;
171                                 if (!String.IsNullOrEmpty (path))
172                                         return path;
173                                 confg = confg.parent;
174                         }
175                         return path;
176                 }
177
178                 internal string ConfigPath {
179                         get { return configPath; }
180                 }
181
182                 public AppSettingsSection AppSettings {
183                         get { return (AppSettingsSection) GetSection ("appSettings"); }
184                 }
185
186                 public ConnectionStringsSection ConnectionStrings {
187                         get { return (ConnectionStringsSection) GetSection ("connectionStrings"); }
188                 }
189
190                 // MSDN: If the value for this FilePath property represents a merged view and 
191                 // no actual file exists for the application, the path to the parent configuration 
192                 // file is returned.
193                 public string FilePath {
194                         get {
195                                 if (streamName == null && parent != null)
196                                         return parent.FilePath;
197                                 return streamName;
198                         }
199                 }
200
201                 public bool HasFile {
202                         get {
203                                 return hasFile;
204                         }
205                 }
206
207                 ContextInformation evaluationContext;
208                 public ContextInformation EvaluationContext {
209                         get {
210                                 if (evaluationContext == null) {
211                                         object ctx = system.Host.CreateConfigurationContext (configPath, GetLocationSubPath() );
212                                         evaluationContext = new ContextInformation (this, ctx);
213                                 }
214
215
216                                 return evaluationContext;
217                         }
218                 }
219                 
220                 public ConfigurationLocationCollection Locations {
221                         get {
222                                 if (locations == null) locations = new ConfigurationLocationCollection ();
223                                 return locations;
224                         }
225                 }
226
227                 public bool NamespaceDeclared {
228                         get { return rootNamespace != null; }
229                         set { rootNamespace = value ? "http://schemas.microsoft.com/.NetConfiguration/v2.0" : null; }
230                 }
231
232                 public ConfigurationSectionGroup RootSectionGroup {
233                         get {
234                                 if (rootSectionGroup == null) {
235                                         rootSectionGroup = new ConfigurationSectionGroup ();
236                                         rootSectionGroup.Initialize (this, rootGroup);
237                                 }
238                                 return rootSectionGroup;
239                         }
240                 }
241
242                 public ConfigurationSectionGroupCollection SectionGroups {
243                         get { return RootSectionGroup.SectionGroups; }
244                 }
245
246                 public ConfigurationSectionCollection Sections {
247                         get { return RootSectionGroup.Sections; }
248                 }
249                 
250                 public ConfigurationSection GetSection (string path)
251                 {
252                         string[] parts = path.Split ('/');
253                         if (parts.Length == 1)
254                                 return Sections [parts[0]];
255
256                         ConfigurationSectionGroup group = SectionGroups [parts[0]];
257                         for (int n=1; group != null && n<parts.Length-1; n++)
258                                 group = group.SectionGroups [parts [n]];
259
260                         if (group != null)
261                                 return group.Sections [parts [parts.Length - 1]];
262                         else
263                                 return null;
264                 }
265                 
266                 public ConfigurationSectionGroup GetSectionGroup (string path)
267                 {
268                         string[] parts = path.Split ('/');
269                         ConfigurationSectionGroup group = SectionGroups [parts[0]];
270                         for (int n=1; group != null && n<parts.Length; n++)
271                                 group = group.SectionGroups [parts [n]];
272                         return group;
273                 }
274                 
275                 internal ConfigurationSection GetSectionInstance (SectionInfo config, bool createDefaultInstance)
276                 {
277                         object data = elementData [config];
278                         ConfigurationSection sec = data as ConfigurationSection;
279                         if (sec != null || !createDefaultInstance) return sec;
280                         
281                         object secObj = config.CreateInstance ();
282                         sec = secObj as ConfigurationSection;
283                         if (sec == null) {
284                                 DefaultSection ds = new DefaultSection ();
285                                 ds.SectionHandler = secObj as IConfigurationSectionHandler;
286                                 sec = ds;
287                         }
288                         sec.Configuration = this;
289
290                         ConfigurationSection parentSection = null;
291                         if (parent != null) {
292                                 parentSection = parent.GetSectionInstance (config, true);
293                                 sec.SectionInformation.SetParentSection (parentSection);
294                         }
295                         sec.SectionInformation.ConfigFilePath = FilePath;
296
297                         sec.ConfigContext = system.Host.CreateDeprecatedConfigContext(configPath);
298                         
299                         string xml = data as string;
300                         sec.RawXml = xml;
301                         sec.Reset (parentSection);
302
303                         if (xml != null) {
304                                 XmlTextReader r = new ConfigXmlTextReader (new StringReader (xml), FilePath);
305                                 sec.DeserializeSection (r);
306                                 r.Close ();
307
308                                 if (!String.IsNullOrEmpty (sec.SectionInformation.ConfigSource) && !String.IsNullOrEmpty (FilePath))
309                                         sec.DeserializeConfigSource (Path.GetDirectoryName (FilePath));
310                         }
311                         
312                         elementData [config] = sec;
313                         return sec;
314                 }
315                 
316                 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
317                 {
318                         ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
319                         if (gr != null) gr.Initialize (this, group);
320                         return gr;
321                 }
322                 
323                 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
324                 {
325                         elementData [config] = sec;
326                 }
327                 
328                 internal void SetSectionXml (SectionInfo config, string data)
329                 {
330                         elementData [config] = data;
331                 }
332                 
333                 internal string GetSectionXml (SectionInfo config)
334                 {
335                         return elementData [config] as string;
336                 }
337                 
338                 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
339                 {
340                         if (group.HasChild (name))
341                                 throw new ConfigurationErrorsException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
342                                 
343                         if (!HasFile && !sec.SectionInformation.AllowLocation)
344                                 throw new ConfigurationErrorsException ("The configuration section <" + name + "> cannot be defined inside a <location> element."); 
345
346                         if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
347                                 object ctx = sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication ? (object) sec.SectionInformation.AllowExeDefinition : (object) sec.SectionInformation.AllowDefinition;
348                                 throw new ConfigurationErrorsException ("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + ctx + "').");
349                         }
350
351                         if (sec.SectionInformation.Type == null)
352                                 sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
353
354                         SectionInfo section = new SectionInfo (name, sec.SectionInformation);
355                         section.StreamName = streamName;
356                         section.ConfigHost = system.Host;
357                         group.AddChild (section);
358                         elementData [section] = sec;
359                         sec.Configuration = this;
360                 }
361                 
362                 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
363                 {
364                         if (parentGroup.HasChild (name)) throw new ConfigurationErrorsException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
365                         if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
366                         sec.SetName (name);
367
368                         SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
369                         section.StreamName = streamName;
370                         section.ConfigHost = system.Host;
371                         parentGroup.AddChild (section);
372                         elementData [section] = sec;
373
374                         sec.Initialize (this, section);
375                 }
376                 
377                 internal void RemoveConfigInfo (ConfigInfo config)
378                 {
379                         elementData.Remove (config);
380                 }
381                 
382                 public void Save ()
383                 {
384                         Save (ConfigurationSaveMode.Modified, false);
385                 }
386                 
387                 public void Save (ConfigurationSaveMode mode)
388                 {
389                         Save (mode, false);
390                 }
391                 
392                 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
393                 {
394                         if (!forceUpdateAll && (mode != ConfigurationSaveMode.Full) && !HasValues (mode)) {
395                                 ResetModified ();
396                                 return;
397                         }
398
399                         ConfigurationSaveEventHandler saveStart = SaveStart;
400                         ConfigurationSaveEventHandler saveEnd = SaveEnd;
401                         
402                         object ctx = null;
403                         Exception saveEx = null;
404                         Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
405                         try {
406                                 if (saveStart != null)
407                                         saveStart (this, new ConfigurationSaveEventArgs (streamName, true, null, ctx));
408                                 
409                                 Save (stream, mode, forceUpdateAll);
410                                 system.Host.WriteCompleted (streamName, true, ctx);
411                         } catch (Exception ex) {
412                                 saveEx = ex;
413                                 system.Host.WriteCompleted (streamName, false, ctx);
414                                 throw;
415                         } finally {
416                                 stream.Close ();
417                                 if (saveEnd != null)
418                                         saveEnd (this, new ConfigurationSaveEventArgs (streamName, false, saveEx, ctx));
419                         }
420                 }
421                 
422                 public void SaveAs (string filename)
423                 {
424                         SaveAs (filename, ConfigurationSaveMode.Modified, false);
425                 }
426                 
427                 public void SaveAs (string filename, ConfigurationSaveMode mode)
428                 {
429                         SaveAs (filename, mode, false);
430                 }
431
432                 [MonoInternalNote ("Detect if file has changed")]
433                 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
434                 {
435                         if (!forceUpdateAll && (mode != ConfigurationSaveMode.Full) && !HasValues (mode)) {
436                                 ResetModified ();
437                                 return;
438                         }
439                         
440                         string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
441                         if (!Directory.Exists (dir))
442                                 Directory.CreateDirectory (dir);
443                         Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
444                 }
445
446                 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
447                 {
448                         XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
449                         tw.Formatting = Formatting.Indented;
450                         try {
451                                 tw.WriteStartDocument ();
452                                 if (rootNamespace != null)
453                                         tw.WriteStartElement ("configuration", rootNamespace);
454                                 else
455                                         tw.WriteStartElement ("configuration");
456                                 if (rootGroup.HasConfigContent (this)) {
457                                         rootGroup.WriteConfig (this, tw, mode);
458                                 }
459                                 
460                                 foreach (ConfigurationLocation loc in Locations) {
461                                         if (loc.OpenedConfiguration == null) {
462                                                 tw.WriteRaw ("\n");
463                                                 tw.WriteRaw (loc.XmlContent);
464                                         }
465                                         else {
466                                                 tw.WriteStartElement ("location");
467                                                 tw.WriteAttributeString ("path", loc.Path); 
468                                                 if (!loc.AllowOverride)
469                                                         tw.WriteAttributeString ("allowOverride", "false");
470                                                 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
471                                                 tw.WriteEndElement ();
472                                         }
473                                 }
474                                 
475                                 SaveData (tw, mode, forceUpdateAll);
476                                 tw.WriteEndElement ();
477                                 ResetModified ();
478                         }
479                         finally {
480                                 tw.Flush ();
481                                 tw.Close ();
482                         }
483                 }
484                 
485                 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
486                 {
487                         rootGroup.WriteRootData (tw, this, mode);
488                 }
489
490                 bool HasValues (ConfigurationSaveMode mode)
491                 {
492                         foreach (ConfigurationLocation loc in Locations) {
493                                 if (loc.OpenedConfiguration == null)
494                                         continue;
495                                 if (loc.OpenedConfiguration.HasValues (mode))
496                                         return true;
497                         }
498
499                         return rootGroup.HasValues (this, mode);
500                 }
501
502                 void ResetModified ()
503                 {
504                         foreach (ConfigurationLocation loc in Locations) {
505                                 if (loc.OpenedConfiguration == null)
506                                         continue;
507                                 loc.OpenedConfiguration.ResetModified ();
508                         }
509                         
510                         rootGroup.ResetModified (this);
511                 }
512                 
513                 bool Load ()
514                 {
515                         if (String.IsNullOrEmpty (streamName))
516                                 return true;
517
518                         Stream stream = null;
519                         try {
520                                 stream = system.Host.OpenStreamForRead (streamName);
521                                 if (stream == null)
522                                         return false;
523                         } catch {
524                                 return false;
525                         }
526
527                         using (XmlTextReader reader = new ConfigXmlTextReader (stream, streamName)) {
528                                 ReadConfigFile (reader, streamName);
529                         }
530                         ResetModified ();
531                         return true;
532                 }
533
534                 void ReadConfigFile (XmlReader reader, string fileName)
535                 {
536                         reader.MoveToContent ();
537
538                         if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
539                                 ThrowException ("Configuration file does not have a valid root element", reader);
540
541                         if (reader.HasAttributes) {
542                                 while (reader.MoveToNextAttribute ()) {
543                                         if (reader.LocalName == "xmlns") {
544                                                 rootNamespace = reader.Value;
545                                                 continue;
546                                         }
547                                         ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
548                                 }
549                         }
550
551                         reader.MoveToElement ();
552
553                         if (reader.IsEmptyElement) {
554                                 reader.Skip ();
555                                 return;
556                         }
557                         
558                         reader.ReadStartElement ();
559                         reader.MoveToContent ();
560
561                         if (reader.LocalName == "configSections") {
562                                 if (reader.HasAttributes)
563                                         ThrowException ("Unrecognized attribute in <configSections>.", reader);
564                                 
565                                 rootGroup.ReadConfig (this, fileName, reader);
566                         }
567                         
568                         rootGroup.ReadRootData (reader, this, true);
569                 }
570
571                 internal void ReadData (XmlReader reader, bool allowOverride)
572                 {
573                         rootGroup.ReadData (this, reader, allowOverride);
574                 }
575                 
576
577                 private void ThrowException (string text, XmlReader reader)
578                 {
579                         IXmlLineInfo li = reader as IXmlLineInfo;
580                         throw new ConfigurationErrorsException (text, streamName, li != null ? li.LineNumber : 0);
581                 }
582         }
583 }
584