2 // System.Configuration.Configuration.cs
5 // Duncan Mak (duncan@ximian.com)
6 // Lluis Sanchez Gual (lluis@novell.com)
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:
16 // The above copyright notice and this permission notice shall be
17 // included in all copies or substantial portions of the Software.
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.
27 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Reflection;
36 using System.Configuration.Internal;
38 namespace System.Configuration {
40 public sealed class Configuration
43 Hashtable elementData = new Hashtable ();
45 ConfigurationSectionGroup rootSectionGroup;
46 ConfigurationLocationCollection locations;
47 SectionGroupInfo rootGroup;
52 string locationConfigPath;
54 internal Configuration (Configuration parent)
56 Init (parent.system, null, parent);
59 internal Configuration (InternalConfigurationSystem system, string locationSubPath)
64 system.InitForConfiguration (ref locationSubPath, out configPath, out locationConfigPath);
66 Configuration parent = null;
68 if (locationSubPath != null) {
69 parent = new Configuration (system, locationSubPath);
70 if (locationConfigPath != null)
71 parent = parent.FindLocationConfiguration (locationConfigPath, parent);
74 Init (system, configPath, parent);
77 internal Configuration FindLocationConfiguration (string relativePath, Configuration defaultConfiguration)
79 ConfigurationLocation loc = Locations.Find (relativePath);
81 Configuration parentConfig = defaultConfiguration;
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);
94 loc.SetParentConfiguration (parentConfig);
95 return loc.OpenConfiguration ();
98 internal void Init (IConfigSystem system, string configPath, Configuration parent)
100 this.system = system;
101 streamName = system.Host.GetStreamName (configPath);
102 this.parent = parent;
104 rootGroup = parent.rootGroup;
106 rootGroup = new SectionGroupInfo ();
107 rootGroup.StreamName = streamName;
110 if (configPath != null)
114 internal Configuration Parent {
115 get { return parent; }
116 set { parent = value; }
119 internal Configuration GetParentWithFile ()
121 Configuration parentFile = Parent;
122 while (parentFile != null && !parentFile.HasFile)
123 parentFile = parentFile.Parent;
127 internal string FileName {
128 get { return streamName; }
131 internal IInternalConfigHost ConfigHost {
132 get { return system.Host; }
135 internal string LocationConfigPath {
136 get { return locationConfigPath; }
139 internal string ConfigPath {
140 get { return configPath; }
143 public AppSettingsSection AppSettings {
144 get { return Sections ["appSettings"] as AppSettingsSection; }
147 public ConnectionStringsSection ConnectionStrings {
148 get { return (ConnectionStringsSection) GetSection ("connectionStrings"); }
151 public string FilePath {
152 get { return streamName; }
155 public bool HasFile {
161 public ConfigurationLocationCollection Locations {
163 if (locations == null) locations = new ConfigurationLocationCollection ();
168 public ConfigurationSectionGroup RootSectionGroup {
170 if (rootSectionGroup == null) {
171 rootSectionGroup = new ConfigurationSectionGroup ();
172 rootSectionGroup.Initialize (this, rootGroup);
174 return rootSectionGroup;
178 public ConfigurationSectionGroupCollection SectionGroups {
179 get { return RootSectionGroup.SectionGroups; }
182 public ConfigurationSectionCollection Sections {
183 get { return RootSectionGroup.Sections; }
186 public ConfigurationSection GetSection (string path)
188 string[] parts = path.Split ('/');
189 if (parts.Length == 1)
190 return Sections [parts[0]];
192 ConfigurationSectionGroup group = SectionGroups [parts[0]];
193 for (int n=1; group != null && n<parts.Length-1; n++)
194 group = group.SectionGroups [parts [n]];
197 return group.Sections [parts [parts.Length - 1]];
202 public ConfigurationSectionGroup GetSectionGroup (string path)
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]];
211 internal ConfigurationSection GetSectionInstance (SectionInfo config, bool createDefaultInstance)
213 object data = elementData [config];
214 ConfigurationSection sec = data as ConfigurationSection;
215 if (sec != null || !createDefaultInstance) return sec;
217 object secObj = config.CreateInstance () as ConfigurationSection;
218 if (!(secObj is ConfigurationSection))
219 sec = new RuntimeOnlySection ();
221 sec = (ConfigurationSection) secObj;
224 ConfigurationSection parentSection = parent != null ? parent.GetSectionInstance (config, true) : null;
225 sec.RawXml = data as string;
226 sec.Reset (parentSection);
229 XmlTextReader r = new XmlTextReader (new StringReader (data as string));
230 sec.DeserializeSection (r);
234 elementData [config] = sec;
238 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
240 ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
241 if (gr != null) gr.Initialize (this, group);
245 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
247 elementData [config] = sec;
250 internal void SetSectionXml (SectionInfo config, string data)
252 elementData [config] = data;
255 internal string GetSectionXml (SectionInfo config)
257 return elementData [config] as string;
260 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
262 if (group.HasChild (name))
263 throw new ConfigurationException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
265 if (!HasFile && !sec.SectionInformation.AllowLocation)
266 throw new ConfigurationErrorsException ("The configuration section <" + name + "> cannot be defined inside a <location> element.");
268 if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
269 object ctx = sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication ? (object) sec.SectionInformation.AllowExeDefinition : (object) sec.SectionInformation.AllowDefinition;
270 throw new ConfigurationErrorsException ("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + ctx + "').");
273 if (sec.SectionInformation.Type == null)
274 sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
276 sec.SectionInformation.SetName (name);
278 SectionInfo section = new SectionInfo (name, sec.SectionInformation.Type, sec.SectionInformation.AllowLocation, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition);
279 section.StreamName = streamName;
280 section.ConfigHost = system.Host;
281 group.AddChild (section);
282 elementData [section] = sec;
285 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
287 if (parentGroup.HasChild (name)) throw new ConfigurationException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
288 if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
291 SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
292 section.StreamName = streamName;
293 section.ConfigHost = system.Host;
294 parentGroup.AddChild (section);
295 elementData [section] = sec;
298 internal void RemoveConfigInfo (ConfigInfo config)
300 elementData.Remove (config);
305 Save (ConfigurationSaveMode.Modified, false);
308 public void Save (ConfigurationSaveMode mode)
313 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
316 Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
318 Save (stream, mode, forceUpdateAll);
319 system.Host.WriteCompleted (streamName, true, ctx);
320 } catch (Exception ex) {
321 system.Host.WriteCompleted (streamName, false, ctx);
328 public void SaveAs (string filename)
330 SaveAs (filename, ConfigurationSaveMode.Modified, false);
333 public void SaveAs (string filename, ConfigurationSaveMode mode)
335 SaveAs (filename, mode, false);
338 [MonoTODO ("Detect if file has changed")]
339 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
341 Save (new FileStream (filename, FileMode.Open, FileAccess.Write), mode, forceUpdateAll);
344 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
346 XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
347 tw.Formatting = Formatting.Indented;
349 tw.WriteStartElement ("configuration");
350 if (rootGroup.HasConfigContent (this)) {
351 rootGroup.WriteConfig (this, tw, mode);
354 foreach (ConfigurationLocation loc in Locations) {
355 if (loc.OpenedConfiguration == null) {
357 tw.WriteRaw (loc.XmlContent);
360 tw.WriteStartElement ("location");
361 tw.WriteAttributeString ("path", loc.Path);
362 if (!loc.AllowOverride)
363 tw.WriteAttributeString ("allowOverride", "false");
364 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
365 tw.WriteEndElement ();
369 SaveData (tw, mode, forceUpdateAll);
370 tw.WriteEndElement ();
377 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
379 rootGroup.WriteRootData (tw, this, mode);
384 if (streamName == null)
387 Stream stream = system.Host.OpenStreamForRead (streamName);
388 XmlTextReader reader = null;
391 reader = new XmlTextReader (stream);
392 ReadConfigFile (reader, streamName);
393 /* } catch (ConfigurationException) {
395 } catch (Exception e) {
396 throw new ConfigurationException ("Error reading " + fileName, e);
405 internal void ReadConfigFile (XmlTextReader reader, string fileName)
407 reader.MoveToContent ();
408 if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
409 ThrowException ("Configuration file does not have a valid root element", reader);
411 if (reader.HasAttributes)
412 ThrowException ("Unrecognized attribute in root element", reader);
414 if (reader.IsEmptyElement) {
419 reader.ReadStartElement ();
420 reader.MoveToContent ();
422 if (reader.LocalName == "configSections") {
423 if (reader.HasAttributes)
424 ThrowException ("Unrecognized attribute in <configSections>.", reader);
426 rootGroup.ReadConfig (this, fileName, reader);
429 rootGroup.ReadRootData (reader, this, true);
432 internal void ReadData (XmlTextReader reader, bool allowOverride)
434 rootGroup.ReadRootData (reader, this, allowOverride);
438 private void ThrowException (string text, XmlTextReader reader)
440 throw new ConfigurationException (text, streamName, reader.LineNumber);