Merge pull request #495 from nicolas-raoul/fix-for-issue2907-with-no-formatting-changes
[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 #if NET_2_0
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                         ConfigurationSaveEventHandler saveStart = SaveStart;
395                         ConfigurationSaveEventHandler saveEnd = SaveEnd;
396                         
397                         object ctx = null;
398                         Exception saveEx = null;
399                         Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
400                         try {
401                                 if (saveStart != null)
402                                         saveStart (this, new ConfigurationSaveEventArgs (streamName, true, null, ctx));
403                                 
404                                 Save (stream, mode, forceUpdateAll);
405                                 system.Host.WriteCompleted (streamName, true, ctx);
406                         } catch (Exception ex) {
407                                 saveEx = ex;
408                                 system.Host.WriteCompleted (streamName, false, ctx);
409                                 throw;
410                         } finally {
411                                 stream.Close ();
412                                 if (saveEnd != null)
413                                         saveEnd (this, new ConfigurationSaveEventArgs (streamName, false, saveEx, ctx));
414                         }
415                 }
416                 
417                 public void SaveAs (string filename)
418                 {
419                         SaveAs (filename, ConfigurationSaveMode.Modified, false);
420                 }
421                 
422                 public void SaveAs (string filename, ConfigurationSaveMode mode)
423                 {
424                         SaveAs (filename, mode, false);
425                 }
426
427                 [MonoInternalNote ("Detect if file has changed")]
428                 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
429                 {
430                         string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
431                         if (!Directory.Exists (dir))
432                                 Directory.CreateDirectory (dir);
433                         Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
434                 }
435
436                 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
437                 {
438                         XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
439                         tw.Formatting = Formatting.Indented;
440                         try {
441                                 tw.WriteStartDocument ();
442                                 if (rootNamespace != null)
443                                         tw.WriteStartElement ("configuration", rootNamespace);
444                                 else
445                                         tw.WriteStartElement ("configuration");
446                                 if (rootGroup.HasConfigContent (this)) {
447                                         rootGroup.WriteConfig (this, tw, mode);
448                                 }
449                                 
450                                 foreach (ConfigurationLocation loc in Locations) {
451                                         if (loc.OpenedConfiguration == null) {
452                                                 tw.WriteRaw ("\n");
453                                                 tw.WriteRaw (loc.XmlContent);
454                                         }
455                                         else {
456                                                 tw.WriteStartElement ("location");
457                                                 tw.WriteAttributeString ("path", loc.Path); 
458                                                 if (!loc.AllowOverride)
459                                                         tw.WriteAttributeString ("allowOverride", "false");
460                                                 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
461                                                 tw.WriteEndElement ();
462                                         }
463                                 }
464                                 
465                                 SaveData (tw, mode, forceUpdateAll);
466                                 tw.WriteEndElement ();
467                         }
468                         finally {
469                                 tw.Flush ();
470                                 tw.Close ();
471                         }
472                 }
473                 
474                 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
475                 {
476                         rootGroup.WriteRootData (tw, this, mode);
477                 }
478                 
479                 bool Load ()
480                 {
481                         if (String.IsNullOrEmpty (streamName))
482                                 return true;
483
484                         Stream stream = null;
485                         try {
486                                 stream = system.Host.OpenStreamForRead (streamName);
487                                 if (stream == null)
488                                         return false;
489                         } catch {
490                                 return false;
491                         }
492
493                         using (XmlTextReader reader = new ConfigXmlTextReader (stream, streamName)) {
494                                 ReadConfigFile (reader, streamName);
495                         }
496                         return true;
497                 }
498
499                 void ReadConfigFile (XmlReader reader, string fileName)
500                 {
501                         reader.MoveToContent ();
502
503                         if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
504                                 ThrowException ("Configuration file does not have a valid root element", reader);
505
506                         if (reader.HasAttributes) {
507                                 while (reader.MoveToNextAttribute ()) {
508                                         if (reader.LocalName == "xmlns") {
509                                                 rootNamespace = reader.Value;
510                                                 continue;
511                                         }
512                                         ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
513                                 }
514                         }
515
516                         reader.MoveToElement ();
517
518                         if (reader.IsEmptyElement) {
519                                 reader.Skip ();
520                                 return;
521                         }
522                         
523                         reader.ReadStartElement ();
524                         reader.MoveToContent ();
525
526                         if (reader.LocalName == "configSections") {
527                                 if (reader.HasAttributes)
528                                         ThrowException ("Unrecognized attribute in <configSections>.", reader);
529                                 
530                                 rootGroup.ReadConfig (this, fileName, reader);
531                         }
532                         
533                         rootGroup.ReadRootData (reader, this, true);
534                 }
535
536                 internal void ReadData (XmlReader reader, bool allowOverride)
537                 {
538                         rootGroup.ReadData (this, reader, allowOverride);
539                 }
540                 
541
542                 private void ThrowException (string text, XmlReader reader)
543                 {
544                         IXmlLineInfo li = reader as IXmlLineInfo;
545                         throw new ConfigurationErrorsException (text, streamName, li != null ? li.LineNumber : 0);
546                 }
547         }
548 }
549
550 #endif