2005-06-23 Lluis Sanchez Gual <lluis@novell.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                 
51                 string configPath;
52                 string locationConfigPath;
53                         
54                 internal Configuration (Configuration parent)
55                 {
56                         Init (parent.system, null, parent);
57                 }
58                 
59                 internal Configuration (InternalConfigurationSystem system, string locationSubPath)
60                 {
61                         hasFile = true;
62                         this.system = system;
63                         
64                         system.InitForConfiguration (ref locationSubPath, out configPath, out locationConfigPath);
65                         
66                         Configuration parent = null;
67                         
68                         if (locationSubPath != null) {
69                                 parent = new Configuration (system, locationSubPath);
70                                 if (locationConfigPath != null)
71                                         parent = parent.FindLocationConfiguration (locationConfigPath, parent);
72                         }
73                         
74                         Init (system, configPath, parent);
75                 }
76                 
77                 internal Configuration FindLocationConfiguration (string relativePath, Configuration defaultConfiguration)
78                 {
79                         ConfigurationLocation loc = Locations.Find (relativePath);
80                         
81                         Configuration parentConfig = defaultConfiguration;
82                         
83                         if (LocationConfigPath != null) {
84                                 Configuration parentFile = GetParentWithFile ();
85                                 if (parentFile != null) {
86                                         string parentRelativePath = system.Host.GetConfigPathFromLocationSubPath (LocationConfigPath, relativePath);
87                                         parentConfig = parentFile.FindLocationConfiguration (parentRelativePath, defaultConfiguration);
88                                 }
89                         }
90
91                         if (loc == null)
92                                 return parentConfig;
93                         
94                         loc.SetParentConfiguration (parentConfig);
95                         return loc.OpenConfiguration ();
96                 }
97                 
98                 internal void Init (IConfigSystem system, string configPath, Configuration parent)
99                 {
100                         this.system = system;
101                         streamName = system.Host.GetStreamName (configPath);
102                         this.parent = parent;
103                         if (parent != null)
104                                 rootGroup = parent.rootGroup;
105                         else {
106                                 rootGroup = new SectionGroupInfo ();
107                                 rootGroup.StreamName = streamName;
108                         }
109                         
110                         if (configPath != null)
111                                 Load ();
112                 }
113                 
114                 internal Configuration Parent {
115                         get { return parent; }
116                         set { parent = value; }
117                 }
118                 
119                 internal Configuration GetParentWithFile ()
120                 {
121                         Configuration parentFile = Parent;
122                         while (parentFile != null && !parentFile.HasFile)
123                                 parentFile = parentFile.Parent;
124                         return parentFile;
125                 }
126                 
127                 internal string FileName {
128                         get { return streamName; }
129                 }
130
131                 internal IInternalConfigHost ConfigHost {
132                         get { return system.Host; }
133                 }
134                 
135                 internal string LocationConfigPath {
136                         get { return locationConfigPath; }
137                 }
138
139                 internal string ConfigPath {
140                         get { return configPath; }
141                 }
142
143                 public AppSettingsSection AppSettings {
144                         get { return Sections ["appSettings"] as AppSettingsSection; }
145                 }
146
147                 public ConnectionStringsSection ConnectionStrings {
148                         get { return (ConnectionStringsSection) GetSection ("connectionStrings"); }
149                 }
150
151                 public string FilePath {
152                         get { return streamName; }
153                 }
154
155                 public bool HasFile {
156                         get {
157                                 return hasFile;
158                         }
159                 }
160                 
161                 public ConfigurationLocationCollection Locations {
162                         get {
163                                 if (locations == null) locations = new ConfigurationLocationCollection ();
164                                 return locations;
165                         }
166                 }
167
168                 public ConfigurationSectionGroup RootSectionGroup {
169                         get {
170                                 if (rootSectionGroup == null) {
171                                         rootSectionGroup = new ConfigurationSectionGroup ();
172                                         rootSectionGroup.Initialize (this, rootGroup);
173                                 }
174                                 return rootSectionGroup;
175                         }                        
176                 }
177
178                 public ConfigurationSectionGroupCollection SectionGroups {
179                         get { return RootSectionGroup.SectionGroups; }                        
180                 }
181
182                 public ConfigurationSectionCollection Sections {
183                         get { return RootSectionGroup.Sections; }
184                 }
185                 
186                 public ConfigurationSection GetSection (string path)
187                 {
188                         string[] parts = path.Split ('/');
189                         if (parts.Length == 1)
190                                 return Sections [parts[0]];
191
192                         ConfigurationSectionGroup group = SectionGroups [parts[0]];
193                         for (int n=1; group != null && n<parts.Length-1; n++)
194                                 group = group.SectionGroups [parts [n]];
195
196                         if (group != null)
197                                 return group.Sections [parts [parts.Length - 1]];
198                         else
199                                 return null;
200                 }
201                 
202                 public ConfigurationSectionGroup GetSectionGroup (string path)
203                 {
204                         string[] parts = path.Split ('/');
205                         ConfigurationSectionGroup group = SectionGroups [parts[0]];
206                         for (int n=1; group != null && n<parts.Length; n++)
207                                 group = group.SectionGroups [parts [n]];
208                         return group;
209                 }
210                 
211                 internal ConfigurationSection GetSectionInstance (SectionInfo config, bool createDefaultInstance)
212                 {
213                         object data = elementData [config];
214                         ConfigurationSection sec = data as ConfigurationSection;
215                         if (sec != null || !createDefaultInstance) return sec;
216                         
217                         object secObj = config.CreateInstance () as ConfigurationSection;
218                         if (!(secObj is ConfigurationSection))
219                                 sec = new RuntimeOnlySection ();
220                         else {
221                                 sec = (ConfigurationSection) secObj;
222                         }
223                                 
224                         ConfigurationSection parentSection = parent != null ? parent.GetSectionInstance (config, true) : null;
225                         sec.RawXml = data as string;
226                         sec.Reset (parentSection);
227                         
228                         if (data != null) {
229                                 XmlTextReader r = new XmlTextReader (new StringReader (data as string));
230                                 sec.DeserializeSection (r);
231                                 r.Close ();
232                         }
233                         
234                         elementData [config] = sec;
235                         return sec;
236                 }
237                 
238                 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
239                 {
240                         ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
241                         if (gr != null) gr.Initialize (this, group);
242                         return gr;
243                 }
244                 
245                 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
246                 {
247                         elementData [config] = sec;
248                 }
249                 
250                 internal void SetSectionXml (SectionInfo config, string data)
251                 {
252                         elementData [config] = data;
253                 }
254                 
255                 internal string GetSectionXml (SectionInfo config)
256                 {
257                         return elementData [config] as string;
258                 }
259                 
260                 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
261                 {
262                         if (group.HasChild (name)) throw new ConfigurationException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
263                         if (sec.SectionInformation.Type == null) sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
264                         sec.SectionInformation.SetName (name);
265
266                         SectionInfo section = new SectionInfo (name, sec.SectionInformation.Type, sec.SectionInformation.AllowLocation, sec.SectionInformation.AllowDefinition);
267                         section.StreamName = streamName;
268                         section.ConfigHost = system.Host;
269                         group.AddChild (section);
270                         elementData [section] = sec;
271                 }
272                 
273                 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
274                 {
275                         if (parentGroup.HasChild (name)) throw new ConfigurationException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
276                         if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
277                         sec.SetName (name);
278
279                         SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
280                         section.StreamName = streamName;
281                         section.ConfigHost = system.Host;
282                         parentGroup.AddChild (section);
283                         elementData [section] = sec;
284                 }
285                 
286                 internal void RemoveConfigInfo (ConfigInfo config)
287                 {
288                         elementData.Remove (config);
289                 }
290                 
291                 public void Save ()
292                 {
293                         Save (ConfigurationSaveMode.Modified, false);
294                 }
295                 
296                 public void Save (ConfigurationSaveMode mode)
297                 {
298                         Save (mode, false);
299                 }
300                 
301                 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
302                 {
303                         object ctx = null;
304                         Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
305                         try {
306                                 Save (stream, mode, forceUpdateAll);
307                                 system.Host.WriteCompleted (streamName, true, ctx);
308                         } catch (Exception ex) {
309                                 system.Host.WriteCompleted (streamName, false, ctx);
310                                 throw;
311                         } finally {
312                                 stream.Close ();
313                         }
314                 }
315                 
316                 public void SaveAs (string filename)
317                 {
318                         SaveAs (filename, ConfigurationSaveMode.Modified, false);
319                 }
320                 
321                 public void SaveAs (string filename, ConfigurationSaveMode mode)
322                 {
323                         SaveAs (filename, mode, false);
324                 }
325                 
326                 [MonoTODO ("Detect if file has changed")]
327                 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
328                 {
329                         Save (new FileStream (filename, FileMode.Open, FileAccess.Write), mode, forceUpdateAll);
330                 }
331                 
332                 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
333                 {
334                         XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
335                         tw.Formatting = Formatting.Indented;
336                         try {
337                                 tw.WriteStartElement ("configuration");
338                                 if (rootGroup.HasConfigContent (this)) {
339                                         rootGroup.WriteConfig (this, tw, mode);
340                                 }
341                                 rootGroup.WriteRootData (tw, this, mode);
342                                 tw.WriteEndElement ();
343                         }
344                         finally {
345                                 tw.Close ();
346                         }
347                 }
348                 
349                 bool Load ()
350                 {
351                         if (streamName == null)
352                                 return true;
353                         
354                         Stream stream = system.Host.OpenStreamForRead (streamName);
355                         XmlTextReader reader = null;
356
357                         try {
358                                 reader = new XmlTextReader (stream);
359                                 ReadConfigFile (reader, streamName);
360 /*                      } catch (ConfigurationException) {
361                                 throw;
362                         } catch (Exception e) {
363                                 throw new ConfigurationException ("Error reading " + fileName, e);
364 */                      } finally {
365                                 if (reader != null)
366                                         reader.Close();
367                         }
368                         return true;
369                 }
370
371
372                 internal void ReadConfigFile (XmlTextReader reader, string fileName)
373                 {
374                         reader.MoveToContent ();
375                         if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
376                                 ThrowException ("Configuration file does not have a valid root element", reader);
377
378                         if (reader.HasAttributes)
379                                 ThrowException ("Unrecognized attribute in root element", reader);
380
381                         if (reader.IsEmptyElement) {
382                                 reader.Skip ();
383                                 return;
384                         }
385                         
386                         reader.ReadStartElement ();
387                         reader.MoveToContent ();
388
389                         if (reader.LocalName == "configSections") {
390                                 if (reader.HasAttributes)
391                                         ThrowException ("Unrecognized attribute in <configSections>.", reader);
392                                 
393                                 rootGroup.ReadConfig (this, fileName, reader);
394                         }
395                         
396                         rootGroup.ReadRootData (reader, this);
397                 }
398                 
399                 internal void ReadData (XmlTextReader reader)
400                 {
401                         rootGroup.ReadRootData (reader, this);
402                 }
403                 
404
405                 private void ThrowException (string text, XmlTextReader reader)
406                 {
407                         throw new ConfigurationException (text, streamName, reader.LineNumber);
408                 }
409         }
410 }
411
412 #endif