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.Configuration.Internal;
34 using System.ComponentModel;
35 using System.Reflection;
39 namespace System.Configuration {
41 public sealed class Configuration
44 Hashtable elementData = new Hashtable ();
46 ConfigurationSectionGroup rootSectionGroup;
47 ConfigurationLocationCollection locations;
48 SectionGroupInfo rootGroup;
54 string locationConfigPath;
55 string locationSubPath;
57 internal static event ConfigurationSaveEventHandler SaveStart;
58 internal static event ConfigurationSaveEventHandler SaveEnd;
60 internal Configuration (Configuration parent, string locationSubPath)
63 this.system = parent.system;
64 this.rootGroup = parent.rootGroup;
65 this.locationSubPath = locationSubPath;
66 this.configPath = parent.ConfigPath;
69 internal Configuration (InternalConfigurationSystem system, string locationSubPath)
74 system.InitForConfiguration (ref locationSubPath, out configPath, out locationConfigPath);
76 Configuration parent = null;
78 if (locationSubPath != null) {
79 parent = new Configuration (system, locationSubPath);
80 if (locationConfigPath != null)
81 parent = parent.FindLocationConfiguration (locationConfigPath, parent);
84 Init (system, configPath, parent);
87 internal Configuration FindLocationConfiguration (string relativePath, Configuration defaultConfiguration)
89 Configuration parentConfig = defaultConfiguration;
91 if (!String.IsNullOrEmpty (LocationConfigPath)) {
92 Configuration parentFile = GetParentWithFile ();
93 if (parentFile != null) {
94 string parentRelativePath = system.Host.GetConfigPathFromLocationSubPath (configPath, relativePath);
95 parentConfig = parentFile.FindLocationConfiguration (parentRelativePath, defaultConfiguration);
99 string relConfigPath = configPath.Substring (1) + "/";
100 if (relativePath.StartsWith (relConfigPath, StringComparison.Ordinal))
101 relativePath = relativePath.Substring (relConfigPath.Length);
103 ConfigurationLocation loc = Locations.Find (relativePath);
107 loc.SetParentConfiguration (parentConfig);
108 return loc.OpenConfiguration ();
111 internal void Init (IConfigSystem system, string configPath, Configuration parent)
113 this.system = system;
114 this.configPath = configPath;
115 streamName = system.Host.GetStreamName (configPath);
116 this.parent = parent;
118 rootGroup = parent.rootGroup;
120 rootGroup = new SectionGroupInfo ();
121 rootGroup.StreamName = streamName;
124 if (streamName != null)
128 internal Configuration Parent {
129 get { return parent; }
130 set { parent = value; }
133 internal Configuration GetParentWithFile ()
135 Configuration parentFile = Parent;
136 while (parentFile != null && !parentFile.HasFile)
137 parentFile = parentFile.Parent;
141 internal string FileName {
142 get { return streamName; }
145 internal IInternalConfigHost ConfigHost {
146 get { return system.Host; }
149 internal string LocationConfigPath {
150 get { return locationConfigPath; }
153 internal string GetLocationSubPath ()
155 Configuration confg = parent;
157 while (confg != null) {
158 path = confg.locationSubPath;
159 if (!String.IsNullOrEmpty (path))
161 confg = confg.parent;
166 internal string ConfigPath {
167 get { return configPath; }
170 public AppSettingsSection AppSettings {
171 get { return (AppSettingsSection) GetSection ("appSettings"); }
174 public ConnectionStringsSection ConnectionStrings {
175 get { return (ConnectionStringsSection) GetSection ("connectionStrings"); }
178 // MSDN: If the value for this FilePath property represents a merged view and
179 // no actual file exists for the application, the path to the parent configuration
181 public string FilePath {
183 if (streamName == null && parent != null)
184 return parent.FilePath;
189 public bool HasFile {
195 ContextInformation evaluationContext;
196 public ContextInformation EvaluationContext {
198 if (evaluationContext == null) {
199 object ctx = system.Host.CreateConfigurationContext (configPath, GetLocationSubPath() );
200 evaluationContext = new ContextInformation (this, ctx);
204 return evaluationContext;
208 public ConfigurationLocationCollection Locations {
210 if (locations == null) locations = new ConfigurationLocationCollection ();
215 public bool NamespaceDeclared {
216 get { return rootNamespace != null; }
217 set { rootNamespace = value ? "http://schemas.microsoft.com/.NetConfiguration/v2.0" : null; }
220 public ConfigurationSectionGroup RootSectionGroup {
222 if (rootSectionGroup == null) {
223 rootSectionGroup = new ConfigurationSectionGroup ();
224 rootSectionGroup.Initialize (this, rootGroup);
226 return rootSectionGroup;
230 public ConfigurationSectionGroupCollection SectionGroups {
231 get { return RootSectionGroup.SectionGroups; }
234 public ConfigurationSectionCollection Sections {
235 get { return RootSectionGroup.Sections; }
238 public ConfigurationSection GetSection (string path)
240 string[] parts = path.Split ('/');
241 if (parts.Length == 1)
242 return Sections [parts[0]];
244 ConfigurationSectionGroup group = SectionGroups [parts[0]];
245 for (int n=1; group != null && n<parts.Length-1; n++)
246 group = group.SectionGroups [parts [n]];
249 return group.Sections [parts [parts.Length - 1]];
254 public ConfigurationSectionGroup GetSectionGroup (string path)
256 string[] parts = path.Split ('/');
257 ConfigurationSectionGroup group = SectionGroups [parts[0]];
258 for (int n=1; group != null && n<parts.Length; n++)
259 group = group.SectionGroups [parts [n]];
263 internal ConfigurationSection GetSectionInstance (SectionInfo config, bool createDefaultInstance)
265 object data = elementData [config];
266 ConfigurationSection sec = data as ConfigurationSection;
267 if (sec != null || !createDefaultInstance) return sec;
269 object secObj = config.CreateInstance ();
270 sec = secObj as ConfigurationSection;
272 DefaultSection ds = new DefaultSection ();
273 ds.SectionHandler = secObj as IConfigurationSectionHandler;
276 sec.Configuration = this;
278 ConfigurationSection parentSection = null;
279 if (parent != null) {
280 parentSection = parent.GetSectionInstance (config, true);
281 sec.SectionInformation.SetParentSection (parentSection);
283 sec.SectionInformation.ConfigFilePath = FilePath;
285 sec.ConfigContext = system.Host.CreateDeprecatedConfigContext(configPath);
287 string xml = data as string;
289 sec.Reset (parentSection);
291 if (xml != null && xml == data) {
292 XmlTextReader r = new ConfigXmlTextReader (new StringReader (xml), FilePath);
293 sec.DeserializeSection (r);
296 if (!String.IsNullOrEmpty (sec.SectionInformation.ConfigSource) && !String.IsNullOrEmpty (FilePath))
297 sec.DeserializeConfigSource (Path.GetDirectoryName (FilePath));
300 elementData [config] = sec;
304 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
306 ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
307 if (gr != null) gr.Initialize (this, group);
311 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
313 elementData [config] = sec;
316 internal void SetSectionXml (SectionInfo config, string data)
318 elementData [config] = data;
321 internal string GetSectionXml (SectionInfo config)
323 return elementData [config] as string;
326 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
328 if (group.HasChild (name))
329 throw new ConfigurationException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
331 if (!HasFile && !sec.SectionInformation.AllowLocation)
332 throw new ConfigurationErrorsException ("The configuration section <" + name + "> cannot be defined inside a <location> element.");
334 if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
335 object ctx = sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication ? (object) sec.SectionInformation.AllowExeDefinition : (object) sec.SectionInformation.AllowDefinition;
336 throw new ConfigurationErrorsException ("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + ctx + "').");
339 if (sec.SectionInformation.Type == null)
340 sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
342 SectionInfo section = new SectionInfo (name, sec.SectionInformation);
343 section.StreamName = streamName;
344 section.ConfigHost = system.Host;
345 group.AddChild (section);
346 elementData [section] = sec;
349 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
351 if (parentGroup.HasChild (name)) throw new ConfigurationException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
352 if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
355 SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
356 section.StreamName = streamName;
357 section.ConfigHost = system.Host;
358 parentGroup.AddChild (section);
359 elementData [section] = sec;
361 sec.Initialize (this, section);
364 internal void RemoveConfigInfo (ConfigInfo config)
366 elementData.Remove (config);
371 Save (ConfigurationSaveMode.Modified, false);
374 public void Save (ConfigurationSaveMode mode)
379 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
381 ConfigurationSaveEventHandler saveStart = SaveStart;
382 ConfigurationSaveEventHandler saveEnd = SaveEnd;
385 Exception saveEx = null;
386 Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
388 if (saveStart != null)
389 saveStart (this, new ConfigurationSaveEventArgs (streamName, true, null, ctx));
391 Save (stream, mode, forceUpdateAll);
392 system.Host.WriteCompleted (streamName, true, ctx);
393 } catch (Exception ex) {
395 system.Host.WriteCompleted (streamName, false, ctx);
400 saveEnd (this, new ConfigurationSaveEventArgs (streamName, false, saveEx, ctx));
404 public void SaveAs (string filename)
406 SaveAs (filename, ConfigurationSaveMode.Modified, false);
409 public void SaveAs (string filename, ConfigurationSaveMode mode)
411 SaveAs (filename, mode, false);
414 [MonoInternalNote ("Detect if file has changed")]
415 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
417 string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
418 if (!Directory.Exists (dir))
419 Directory.CreateDirectory (dir);
420 Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
423 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
425 XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
426 tw.Formatting = Formatting.Indented;
428 tw.WriteStartDocument ();
429 if (rootNamespace != null)
430 tw.WriteStartElement ("configuration", rootNamespace);
432 tw.WriteStartElement ("configuration");
433 if (rootGroup.HasConfigContent (this)) {
434 rootGroup.WriteConfig (this, tw, mode);
437 foreach (ConfigurationLocation loc in Locations) {
438 if (loc.OpenedConfiguration == null) {
440 tw.WriteRaw (loc.XmlContent);
443 tw.WriteStartElement ("location");
444 tw.WriteAttributeString ("path", loc.Path);
445 if (!loc.AllowOverride)
446 tw.WriteAttributeString ("allowOverride", "false");
447 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
448 tw.WriteEndElement ();
452 SaveData (tw, mode, forceUpdateAll);
453 tw.WriteEndElement ();
461 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
463 rootGroup.WriteRootData (tw, this, mode);
468 if (String.IsNullOrEmpty (streamName))
471 Stream stream = null;
473 stream = system.Host.OpenStreamForRead (streamName);
480 using (XmlTextReader reader = new ConfigXmlTextReader (stream, streamName)) {
481 ReadConfigFile (reader, streamName);
486 void ReadConfigFile (XmlReader reader, string fileName)
488 reader.MoveToContent ();
490 if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
491 ThrowException ("Configuration file does not have a valid root element", reader);
493 if (reader.HasAttributes) {
494 while (reader.MoveToNextAttribute ()) {
495 if (reader.LocalName == "xmlns") {
496 rootNamespace = reader.Value;
499 ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
503 reader.MoveToElement ();
505 if (reader.IsEmptyElement) {
510 reader.ReadStartElement ();
511 reader.MoveToContent ();
513 if (reader.LocalName == "configSections") {
514 if (reader.HasAttributes)
515 ThrowException ("Unrecognized attribute in <configSections>.", reader);
517 rootGroup.ReadConfig (this, fileName, reader);
520 rootGroup.ReadRootData (reader, this, true);
523 internal void ReadData (XmlReader reader, bool allowOverride)
525 rootGroup.ReadData (this, reader, allowOverride);
529 private void ThrowException (string text, XmlReader reader)
531 IXmlLineInfo li = reader as IXmlLineInfo;
532 throw new ConfigurationException (text, streamName, li != null ? li.LineNumber : 0);