Merged into single file, added assertions
[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                 }
360                 
361                 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
362                 {
363                         if (parentGroup.HasChild (name)) throw new ConfigurationErrorsException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
364                         if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
365                         sec.SetName (name);
366
367                         SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
368                         section.StreamName = streamName;
369                         section.ConfigHost = system.Host;
370                         parentGroup.AddChild (section);
371                         elementData [section] = sec;
372
373                         sec.Initialize (this, section);
374                 }
375                 
376                 internal void RemoveConfigInfo (ConfigInfo config)
377                 {
378                         elementData.Remove (config);
379                 }
380                 
381                 public void Save ()
382                 {
383                         Save (ConfigurationSaveMode.Modified, false);
384                 }
385                 
386                 public void Save (ConfigurationSaveMode mode)
387                 {
388                         Save (mode, false);
389                 }
390                 
391                 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
392                 {
393                         ConfigurationSaveEventHandler saveStart = SaveStart;
394                         ConfigurationSaveEventHandler saveEnd = SaveEnd;
395                         
396                         object ctx = null;
397                         Exception saveEx = null;
398                         Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
399                         try {
400                                 if (saveStart != null)
401                                         saveStart (this, new ConfigurationSaveEventArgs (streamName, true, null, ctx));
402                                 
403                                 Save (stream, mode, forceUpdateAll);
404                                 system.Host.WriteCompleted (streamName, true, ctx);
405                         } catch (Exception ex) {
406                                 saveEx = ex;
407                                 system.Host.WriteCompleted (streamName, false, ctx);
408                                 throw;
409                         } finally {
410                                 stream.Close ();
411                                 if (saveEnd != null)
412                                         saveEnd (this, new ConfigurationSaveEventArgs (streamName, false, saveEx, ctx));
413                         }
414                 }
415                 
416                 public void SaveAs (string filename)
417                 {
418                         SaveAs (filename, ConfigurationSaveMode.Modified, false);
419                 }
420                 
421                 public void SaveAs (string filename, ConfigurationSaveMode mode)
422                 {
423                         SaveAs (filename, mode, false);
424                 }
425
426                 [MonoInternalNote ("Detect if file has changed")]
427                 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
428                 {
429                         string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
430                         if (!Directory.Exists (dir))
431                                 Directory.CreateDirectory (dir);
432                         Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
433                 }
434
435                 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
436                 {
437                         XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
438                         tw.Formatting = Formatting.Indented;
439                         try {
440                                 tw.WriteStartDocument ();
441                                 if (rootNamespace != null)
442                                         tw.WriteStartElement ("configuration", rootNamespace);
443                                 else
444                                         tw.WriteStartElement ("configuration");
445                                 if (rootGroup.HasConfigContent (this)) {
446                                         rootGroup.WriteConfig (this, tw, mode);
447                                 }
448                                 
449                                 foreach (ConfigurationLocation loc in Locations) {
450                                         if (loc.OpenedConfiguration == null) {
451                                                 tw.WriteRaw ("\n");
452                                                 tw.WriteRaw (loc.XmlContent);
453                                         }
454                                         else {
455                                                 tw.WriteStartElement ("location");
456                                                 tw.WriteAttributeString ("path", loc.Path); 
457                                                 if (!loc.AllowOverride)
458                                                         tw.WriteAttributeString ("allowOverride", "false");
459                                                 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
460                                                 tw.WriteEndElement ();
461                                         }
462                                 }
463                                 
464                                 SaveData (tw, mode, forceUpdateAll);
465                                 tw.WriteEndElement ();
466                         }
467                         finally {
468                                 tw.Flush ();
469                                 tw.Close ();
470                         }
471                 }
472                 
473                 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
474                 {
475                         rootGroup.WriteRootData (tw, this, mode);
476                 }
477                 
478                 bool Load ()
479                 {
480                         if (String.IsNullOrEmpty (streamName))
481                                 return true;
482
483                         Stream stream = null;
484                         try {
485                                 stream = system.Host.OpenStreamForRead (streamName);
486                                 if (stream == null)
487                                         return false;
488                         } catch {
489                                 return false;
490                         }
491
492                         using (XmlTextReader reader = new ConfigXmlTextReader (stream, streamName)) {
493                                 ReadConfigFile (reader, streamName);
494                         }
495                         return true;
496                 }
497
498                 void ReadConfigFile (XmlReader reader, string fileName)
499                 {
500                         reader.MoveToContent ();
501
502                         if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
503                                 ThrowException ("Configuration file does not have a valid root element", reader);
504
505                         if (reader.HasAttributes) {
506                                 while (reader.MoveToNextAttribute ()) {
507                                         if (reader.LocalName == "xmlns") {
508                                                 rootNamespace = reader.Value;
509                                                 continue;
510                                         }
511                                         ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
512                                 }
513                         }
514
515                         reader.MoveToElement ();
516
517                         if (reader.IsEmptyElement) {
518                                 reader.Skip ();
519                                 return;
520                         }
521                         
522                         reader.ReadStartElement ();
523                         reader.MoveToContent ();
524
525                         if (reader.LocalName == "configSections") {
526                                 if (reader.HasAttributes)
527                                         ThrowException ("Unrecognized attribute in <configSections>.", reader);
528                                 
529                                 rootGroup.ReadConfig (this, fileName, reader);
530                         }
531                         
532                         rootGroup.ReadRootData (reader, this, true);
533                 }
534
535                 internal void ReadData (XmlReader reader, bool allowOverride)
536                 {
537                         rootGroup.ReadData (this, reader, allowOverride);
538                 }
539                 
540
541                 private void ThrowException (string text, XmlReader reader)
542                 {
543                         IXmlLineInfo li = reader as IXmlLineInfo;
544                         throw new ConfigurationErrorsException (text, streamName, li != null ? li.LineNumber : 0);
545                 }
546         }
547 }
548
549 #endif