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 // For configuration document, use this XmlDocument instead of the standard one. This ignores xmlns attribute for MS.
42 internal class ConfigurationXmlDocument : XmlDocument
44 public override XmlElement CreateElement (string prefix, string localName, string namespaceURI)
46 if (namespaceURI == "http://schemas.microsoft.com/.NetConfiguration/v2.0")
47 return base.CreateElement (String.Empty, localName, String.Empty);
49 return base.CreateElement (prefix, localName, namespaceURI);
53 public sealed class Configuration
56 Hashtable elementData = new Hashtable ();
58 ConfigurationSectionGroup rootSectionGroup;
59 ConfigurationLocationCollection locations;
60 SectionGroupInfo rootGroup;
66 string locationConfigPath;
67 string locationSubPath;
69 internal static event ConfigurationSaveEventHandler SaveStart;
70 internal static event ConfigurationSaveEventHandler SaveEnd;
72 internal Configuration (Configuration parent, string locationSubPath)
75 this.system = parent.system;
76 this.rootGroup = parent.rootGroup;
77 this.locationSubPath = locationSubPath;
78 this.configPath = parent.ConfigPath;
81 internal Configuration (InternalConfigurationSystem system, string locationSubPath)
86 system.InitForConfiguration (ref locationSubPath, out configPath, out locationConfigPath);
88 Configuration parent = null;
90 if (locationSubPath != null) {
91 parent = new Configuration (system, locationSubPath);
92 if (locationConfigPath != null)
93 parent = parent.FindLocationConfiguration (locationConfigPath, parent);
96 Init (system, configPath, parent);
99 internal Configuration FindLocationConfiguration (string relativePath, Configuration defaultConfiguration)
101 Configuration parentConfig = defaultConfiguration;
103 if (!String.IsNullOrEmpty (LocationConfigPath)) {
104 Configuration parentFile = GetParentWithFile ();
105 if (parentFile != null) {
106 string parentRelativePath = system.Host.GetConfigPathFromLocationSubPath (configPath, relativePath);
107 parentConfig = parentFile.FindLocationConfiguration (parentRelativePath, defaultConfiguration);
111 string relConfigPath = configPath.Substring (1) + "/";
112 if (relativePath.StartsWith (relConfigPath, StringComparison.Ordinal))
113 relativePath = relativePath.Substring (relConfigPath.Length);
115 ConfigurationLocation loc = Locations.FindBest (relativePath);
119 loc.SetParentConfiguration (parentConfig);
120 return loc.OpenConfiguration ();
123 internal void Init (IConfigSystem system, string configPath, Configuration parent)
125 this.system = system;
126 this.configPath = configPath;
127 streamName = system.Host.GetStreamName (configPath);
128 this.parent = parent;
130 rootGroup = parent.rootGroup;
132 rootGroup = new SectionGroupInfo ();
133 rootGroup.StreamName = streamName;
136 if (streamName != null)
140 internal Configuration Parent {
141 get { return parent; }
142 set { parent = value; }
145 internal Configuration GetParentWithFile ()
147 Configuration parentFile = Parent;
148 while (parentFile != null && !parentFile.HasFile)
149 parentFile = parentFile.Parent;
153 internal string FileName {
154 get { return streamName; }
157 internal IInternalConfigHost ConfigHost {
158 get { return system.Host; }
161 internal string LocationConfigPath {
162 get { return locationConfigPath; }
165 internal string GetLocationSubPath ()
167 Configuration confg = parent;
169 while (confg != null) {
170 path = confg.locationSubPath;
171 if (!String.IsNullOrEmpty (path))
173 confg = confg.parent;
178 internal string ConfigPath {
179 get { return configPath; }
182 public AppSettingsSection AppSettings {
183 get { return (AppSettingsSection) GetSection ("appSettings"); }
186 public ConnectionStringsSection ConnectionStrings {
187 get { return (ConnectionStringsSection) GetSection ("connectionStrings"); }
190 // MSDN: If the value for this FilePath property represents a merged view and
191 // no actual file exists for the application, the path to the parent configuration
193 public string FilePath {
195 if (streamName == null && parent != null)
196 return parent.FilePath;
201 public bool HasFile {
207 ContextInformation evaluationContext;
208 public ContextInformation EvaluationContext {
210 if (evaluationContext == null) {
211 object ctx = system.Host.CreateConfigurationContext (configPath, GetLocationSubPath() );
212 evaluationContext = new ContextInformation (this, ctx);
216 return evaluationContext;
220 public ConfigurationLocationCollection Locations {
222 if (locations == null) locations = new ConfigurationLocationCollection ();
227 public bool NamespaceDeclared {
228 get { return rootNamespace != null; }
229 set { rootNamespace = value ? "http://schemas.microsoft.com/.NetConfiguration/v2.0" : null; }
232 public ConfigurationSectionGroup RootSectionGroup {
234 if (rootSectionGroup == null) {
235 rootSectionGroup = new ConfigurationSectionGroup ();
236 rootSectionGroup.Initialize (this, rootGroup);
238 return rootSectionGroup;
242 public ConfigurationSectionGroupCollection SectionGroups {
243 get { return RootSectionGroup.SectionGroups; }
246 public ConfigurationSectionCollection Sections {
247 get { return RootSectionGroup.Sections; }
250 public ConfigurationSection GetSection (string path)
252 string[] parts = path.Split ('/');
253 if (parts.Length == 1)
254 return Sections [parts[0]];
256 ConfigurationSectionGroup group = SectionGroups [parts[0]];
257 for (int n=1; group != null && n<parts.Length-1; n++)
258 group = group.SectionGroups [parts [n]];
261 return group.Sections [parts [parts.Length - 1]];
266 public ConfigurationSectionGroup GetSectionGroup (string path)
268 string[] parts = path.Split ('/');
269 ConfigurationSectionGroup group = SectionGroups [parts[0]];
270 for (int n=1; group != null && n<parts.Length; n++)
271 group = group.SectionGroups [parts [n]];
275 internal ConfigurationSection GetSectionInstance (SectionInfo config, bool createDefaultInstance)
277 object data = elementData [config];
278 ConfigurationSection sec = data as ConfigurationSection;
279 if (sec != null || !createDefaultInstance) return sec;
281 object secObj = config.CreateInstance ();
282 sec = secObj as ConfigurationSection;
284 DefaultSection ds = new DefaultSection ();
285 ds.SectionHandler = secObj as IConfigurationSectionHandler;
288 sec.Configuration = this;
290 ConfigurationSection parentSection = null;
291 if (parent != null) {
292 parentSection = parent.GetSectionInstance (config, true);
293 sec.SectionInformation.SetParentSection (parentSection);
295 sec.SectionInformation.ConfigFilePath = FilePath;
297 sec.ConfigContext = system.Host.CreateDeprecatedConfigContext(configPath);
299 string xml = data as string;
301 sec.Reset (parentSection);
304 XmlTextReader r = new ConfigXmlTextReader (new StringReader (xml), FilePath);
305 sec.DeserializeSection (r);
308 if (!String.IsNullOrEmpty (sec.SectionInformation.ConfigSource) && !String.IsNullOrEmpty (FilePath))
309 sec.DeserializeConfigSource (Path.GetDirectoryName (FilePath));
312 elementData [config] = sec;
316 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
318 ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
319 if (gr != null) gr.Initialize (this, group);
323 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
325 elementData [config] = sec;
328 internal void SetSectionXml (SectionInfo config, string data)
330 elementData [config] = data;
333 internal string GetSectionXml (SectionInfo config)
335 return elementData [config] as string;
338 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
340 if (group.HasChild (name))
341 throw new ConfigurationErrorsException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
343 if (!HasFile && !sec.SectionInformation.AllowLocation)
344 throw new ConfigurationErrorsException ("The configuration section <" + name + "> cannot be defined inside a <location> element.");
346 if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
347 object ctx = sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication ? (object) sec.SectionInformation.AllowExeDefinition : (object) sec.SectionInformation.AllowDefinition;
348 throw new ConfigurationErrorsException ("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + ctx + "').");
351 if (sec.SectionInformation.Type == null)
352 sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
354 SectionInfo section = new SectionInfo (name, sec.SectionInformation);
355 section.StreamName = streamName;
356 section.ConfigHost = system.Host;
357 group.AddChild (section);
358 elementData [section] = sec;
359 sec.Configuration = this;
362 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
364 if (parentGroup.HasChild (name)) throw new ConfigurationErrorsException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
365 if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
368 SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
369 section.StreamName = streamName;
370 section.ConfigHost = system.Host;
371 parentGroup.AddChild (section);
372 elementData [section] = sec;
374 sec.Initialize (this, section);
377 internal void RemoveConfigInfo (ConfigInfo config)
379 elementData.Remove (config);
384 Save (ConfigurationSaveMode.Modified, false);
387 public void Save (ConfigurationSaveMode mode)
392 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
394 if (!forceUpdateAll && (mode != ConfigurationSaveMode.Full) && !HasValues (mode)) {
399 ConfigurationSaveEventHandler saveStart = SaveStart;
400 ConfigurationSaveEventHandler saveEnd = SaveEnd;
403 Exception saveEx = null;
404 Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
406 if (saveStart != null)
407 saveStart (this, new ConfigurationSaveEventArgs (streamName, true, null, ctx));
409 Save (stream, mode, forceUpdateAll);
410 system.Host.WriteCompleted (streamName, true, ctx);
411 } catch (Exception ex) {
413 system.Host.WriteCompleted (streamName, false, ctx);
418 saveEnd (this, new ConfigurationSaveEventArgs (streamName, false, saveEx, ctx));
422 public void SaveAs (string filename)
424 SaveAs (filename, ConfigurationSaveMode.Modified, false);
427 public void SaveAs (string filename, ConfigurationSaveMode mode)
429 SaveAs (filename, mode, false);
432 [MonoInternalNote ("Detect if file has changed")]
433 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
435 if (!forceUpdateAll && (mode != ConfigurationSaveMode.Full) && !HasValues (mode)) {
440 string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
441 if (!Directory.Exists (dir))
442 Directory.CreateDirectory (dir);
443 Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
446 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
448 XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
449 tw.Formatting = Formatting.Indented;
451 tw.WriteStartDocument ();
452 if (rootNamespace != null)
453 tw.WriteStartElement ("configuration", rootNamespace);
455 tw.WriteStartElement ("configuration");
456 if (rootGroup.HasConfigContent (this)) {
457 rootGroup.WriteConfig (this, tw, mode);
460 foreach (ConfigurationLocation loc in Locations) {
461 if (loc.OpenedConfiguration == null) {
463 tw.WriteRaw (loc.XmlContent);
466 tw.WriteStartElement ("location");
467 tw.WriteAttributeString ("path", loc.Path);
468 if (!loc.AllowOverride)
469 tw.WriteAttributeString ("allowOverride", "false");
470 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
471 tw.WriteEndElement ();
475 SaveData (tw, mode, forceUpdateAll);
476 tw.WriteEndElement ();
485 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
487 rootGroup.WriteRootData (tw, this, mode);
490 bool HasValues (ConfigurationSaveMode mode)
492 foreach (ConfigurationLocation loc in Locations) {
493 if (loc.OpenedConfiguration == null)
495 if (loc.OpenedConfiguration.HasValues (mode))
499 return rootGroup.HasValues (this, mode);
502 void ResetModified ()
504 foreach (ConfigurationLocation loc in Locations) {
505 if (loc.OpenedConfiguration == null)
507 loc.OpenedConfiguration.ResetModified ();
510 rootGroup.ResetModified (this);
515 if (String.IsNullOrEmpty (streamName))
518 Stream stream = null;
520 stream = system.Host.OpenStreamForRead (streamName);
527 using (XmlTextReader reader = new ConfigXmlTextReader (stream, streamName)) {
528 ReadConfigFile (reader, streamName);
534 void ReadConfigFile (XmlReader reader, string fileName)
536 reader.MoveToContent ();
538 if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
539 ThrowException ("Configuration file does not have a valid root element", reader);
541 if (reader.HasAttributes) {
542 while (reader.MoveToNextAttribute ()) {
543 if (reader.LocalName == "xmlns") {
544 rootNamespace = reader.Value;
547 ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
551 reader.MoveToElement ();
553 if (reader.IsEmptyElement) {
558 reader.ReadStartElement ();
559 reader.MoveToContent ();
561 if (reader.LocalName == "configSections") {
562 if (reader.HasAttributes)
563 ThrowException ("Unrecognized attribute in <configSections>.", reader);
565 rootGroup.ReadConfig (this, fileName, reader);
568 rootGroup.ReadRootData (reader, this, true);
571 internal void ReadData (XmlReader reader, bool allowOverride)
573 rootGroup.ReadData (this, reader, allowOverride);
577 private void ThrowException (string text, XmlReader reader)
579 IXmlLineInfo li = reader as IXmlLineInfo;
580 throw new ConfigurationErrorsException (text, streamName, li != null ? li.LineNumber : 0);