2008-03-20 Igor Zelmanovich <igorz@mainsoft.com>
[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                         sec.Configuration = this;
269
270                         ConfigurationSection parentSection = null;
271                         if (parent != null) {
272                                 parentSection = parent.GetSectionInstance (config, true);
273                                 sec.SectionInformation.SetParentSection (parentSection);
274                         }
275                         sec.SectionInformation.ConfigFilePath = FilePath;
276                         
277                         string xml = data as string;
278                         sec.RawXml = xml;
279                         sec.Reset (parentSection);
280
281                         if (xml != null && xml == data) {
282                                 XmlTextReader r = new XmlTextReader (new StringReader (xml));
283                                 sec.DeserializeSection (r);
284                                 r.Close ();
285
286                                 if (!String.IsNullOrEmpty (sec.SectionInformation.ConfigSource) && !String.IsNullOrEmpty (FilePath))
287                                         sec.DeserializeConfigSource (Path.GetDirectoryName (FilePath));
288                         }
289                         
290                         elementData [config] = sec;
291                         return sec;
292                 }
293                 
294                 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
295                 {
296                         ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
297                         if (gr != null) gr.Initialize (this, group);
298                         return gr;
299                 }
300                 
301                 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
302                 {
303                         elementData [config] = sec;
304                 }
305                 
306                 internal void SetSectionXml (SectionInfo config, string data)
307                 {
308                         elementData [config] = data;
309                 }
310                 
311                 internal string GetSectionXml (SectionInfo config)
312                 {
313                         return elementData [config] as string;
314                 }
315                 
316                 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
317                 {
318                         if (group.HasChild (name))
319                                 throw new ConfigurationException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
320                                 
321                         if (!HasFile && !sec.SectionInformation.AllowLocation)
322                                 throw new ConfigurationErrorsException ("The configuration section <" + name + "> cannot be defined inside a <location> element."); 
323
324                         if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
325                                 object ctx = sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication ? (object) sec.SectionInformation.AllowExeDefinition : (object) sec.SectionInformation.AllowDefinition;
326                                 throw new ConfigurationErrorsException ("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + ctx + "').");
327                         }
328                                                 
329                         if (sec.SectionInformation.Type == null)
330                                 sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
331                         
332                         SectionInfo section = new SectionInfo (name, sec.SectionInformation);
333                         section.StreamName = streamName;
334                         section.ConfigHost = system.Host;
335                         group.AddChild (section);
336                         elementData [section] = sec;
337                 }
338                 
339                 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
340                 {
341                         if (parentGroup.HasChild (name)) throw new ConfigurationException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
342                         if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
343                         sec.SetName (name);
344
345                         SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
346                         section.StreamName = streamName;
347                         section.ConfigHost = system.Host;
348                         parentGroup.AddChild (section);
349                         elementData [section] = sec;
350
351                         sec.Initialize (this, section);
352                 }
353                 
354                 internal void RemoveConfigInfo (ConfigInfo config)
355                 {
356                         elementData.Remove (config);
357                 }
358                 
359                 public void Save ()
360                 {
361                         Save (ConfigurationSaveMode.Modified, false);
362                 }
363                 
364                 public void Save (ConfigurationSaveMode mode)
365                 {
366                         Save (mode, false);
367                 }
368                 
369                 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
370                 {
371                         object ctx = null;
372                         Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
373                         try {
374                                 Save (stream, mode, forceUpdateAll);
375                                 system.Host.WriteCompleted (streamName, true, ctx);
376                         } catch (Exception) {
377                                 system.Host.WriteCompleted (streamName, false, ctx);
378                                 throw;
379                         } finally {
380                                 stream.Close ();
381                         }
382                 }
383                 
384                 public void SaveAs (string filename)
385                 {
386                         SaveAs (filename, ConfigurationSaveMode.Modified, false);
387                 }
388                 
389                 public void SaveAs (string filename, ConfigurationSaveMode mode)
390                 {
391                         SaveAs (filename, mode, false);
392                 }
393
394                 [MonoInternalNote ("Detect if file has changed")]
395                 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
396                 {
397                         string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
398                         if (!Directory.Exists (dir))
399                                 Directory.CreateDirectory (dir);
400                         Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
401                 }
402
403                 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
404                 {
405                         XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
406                         tw.Formatting = Formatting.Indented;
407                         try {
408                                 tw.WriteStartDocument ();
409                                 if (rootNamespace != null)
410                                         tw.WriteStartElement ("configuration", rootNamespace);
411                                 else
412                                         tw.WriteStartElement ("configuration");
413                                 if (rootGroup.HasConfigContent (this)) {
414                                         rootGroup.WriteConfig (this, tw, mode);
415                                 }
416                                 
417                                 foreach (ConfigurationLocation loc in Locations) {
418                                         if (loc.OpenedConfiguration == null) {
419                                                 tw.WriteRaw ("\n");
420                                                 tw.WriteRaw (loc.XmlContent);
421                                         }
422                                         else {
423                                                 tw.WriteStartElement ("location");
424                                                 tw.WriteAttributeString ("path", loc.Path); 
425                                                 if (!loc.AllowOverride)
426                                                         tw.WriteAttributeString ("allowOverride", "false");
427                                                 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
428                                                 tw.WriteEndElement ();
429                                         }
430                                 }
431                                 
432                                 SaveData (tw, mode, forceUpdateAll);
433                                 tw.WriteEndElement ();
434                         }
435                         finally {
436                                 tw.Close ();
437                         }
438                 }
439                 
440                 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
441                 {
442                         rootGroup.WriteRootData (tw, this, mode);
443                 }
444                 
445                 bool Load ()
446                 {
447                         if (String.IsNullOrEmpty (streamName))
448                                 return true;
449
450                         XmlTextReader reader = null;
451                         Stream stream = null;
452                         
453                         // FIXME: we should remove this kind of hack that
454                         // hides the actual error
455                         try {
456                                 stream = system.Host.OpenStreamForRead (streamName);
457                         } catch (Exception) {
458                                 return false;
459                         }
460
461                         try {
462                                 reader = new XmlTextReader (stream);
463                                 ReadConfigFile (reader, streamName);
464                         } finally {
465                                 if (reader != null)
466                                         reader.Close();
467                         }
468                         return true;
469                 }
470
471
472                 void ReadConfigFile (XmlTextReader reader, string fileName)
473                 {
474                         reader.MoveToContent ();
475
476                         if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
477                                 ThrowException ("Configuration file does not have a valid root element", reader);
478
479                         if (reader.HasAttributes) {
480                                 while (reader.MoveToNextAttribute ()) {
481                                         if (reader.LocalName == "xmlns") {
482                                                 rootNamespace = reader.Value;
483                                                 continue;
484                                         }
485                                         ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
486                                 }
487                         }
488
489                         reader.MoveToElement ();
490
491                         if (reader.IsEmptyElement) {
492                                 reader.Skip ();
493                                 return;
494                         }
495                         
496                         reader.ReadStartElement ();
497                         reader.MoveToContent ();
498
499                         if (reader.LocalName == "configSections") {
500                                 if (reader.HasAttributes)
501                                         ThrowException ("Unrecognized attribute in <configSections>.", reader);
502                                 
503                                 rootGroup.ReadConfig (this, fileName, reader);
504                         }
505                         
506                         rootGroup.ReadRootData (reader, this, true);
507                 }
508                 
509                 internal void ReadData (XmlTextReader reader, bool allowOverride)
510                 {
511                         rootGroup.ReadData (this, reader, allowOverride);
512                 }
513                 
514
515                 private void ThrowException (string text, XmlTextReader reader)
516                 {
517                         throw new ConfigurationException (text, streamName, reader.LineNumber);
518                 }
519         }
520 }
521
522 #endif