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