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;
68 internal Configuration (InternalConfigurationSystem system, string locationSubPath)
73 system.InitForConfiguration (ref locationSubPath, out configPath, out locationConfigPath);
75 Configuration parent = null;
77 if (locationSubPath != null) {
78 parent = new Configuration (system, locationSubPath);
79 if (locationConfigPath != null)
80 parent = parent.FindLocationConfiguration (locationConfigPath, parent);
83 Init (system, configPath, parent);
86 internal Configuration FindLocationConfiguration (string relativePath, Configuration defaultConfiguration)
88 ConfigurationLocation loc = Locations.Find (relativePath);
90 Configuration parentConfig = defaultConfiguration;
92 if (LocationConfigPath != null) {
93 Configuration parentFile = GetParentWithFile ();
94 if (parentFile != null) {
95 string parentRelativePath = system.Host.GetConfigPathFromLocationSubPath (LocationConfigPath, relativePath);
96 parentConfig = parentFile.FindLocationConfiguration (parentRelativePath, defaultConfiguration);
103 loc.SetParentConfiguration (parentConfig);
104 return loc.OpenConfiguration ();
107 internal void Init (IConfigSystem system, string configPath, Configuration parent)
109 this.system = system;
110 this.configPath = configPath;
111 streamName = system.Host.GetStreamName (configPath);
112 this.parent = parent;
114 rootGroup = parent.rootGroup;
116 rootGroup = new SectionGroupInfo ();
117 rootGroup.StreamName = streamName;
120 if (streamName != null)
124 internal Configuration Parent {
125 get { return parent; }
126 set { parent = value; }
129 internal Configuration GetParentWithFile ()
131 Configuration parentFile = Parent;
132 while (parentFile != null && !parentFile.HasFile)
133 parentFile = parentFile.Parent;
137 internal string FileName {
138 get { return streamName; }
141 internal IInternalConfigHost ConfigHost {
142 get { return system.Host; }
145 internal string LocationConfigPath {
146 get { return locationConfigPath; }
149 internal string GetLocationSubPath ()
151 Configuration confg = parent;
153 while (confg != null) {
154 path = confg.locationSubPath;
155 if (!String.IsNullOrEmpty (path))
157 confg = confg.parent;
162 internal string ConfigPath {
163 get { return configPath; }
166 public AppSettingsSection AppSettings {
167 get { return (AppSettingsSection) GetSection ("appSettings"); }
170 public ConnectionStringsSection ConnectionStrings {
171 get { return (ConnectionStringsSection) GetSection ("connectionStrings"); }
174 // MSDN: If the value for this FilePath property represents a merged view and
175 // no actual file exists for the application, the path to the parent configuration
177 public string FilePath {
179 if (streamName == null && parent != null)
180 return parent.FilePath;
185 public bool HasFile {
191 ContextInformation evaluationContext;
192 public ContextInformation EvaluationContext {
194 if (evaluationContext == null) {
195 object ctx = system.Host.CreateConfigurationContext (configPath, GetLocationSubPath() );
196 evaluationContext = new ContextInformation (this, ctx);
200 return evaluationContext;
204 public ConfigurationLocationCollection Locations {
206 if (locations == null) locations = new ConfigurationLocationCollection ();
211 public bool NamespaceDeclared {
212 get { return rootNamespace != null; }
213 set { rootNamespace = value ? "http://schemas.microsoft.com/.NetConfiguration/v2.0" : null; }
216 public ConfigurationSectionGroup RootSectionGroup {
218 if (rootSectionGroup == null) {
219 rootSectionGroup = new ConfigurationSectionGroup ();
220 rootSectionGroup.Initialize (this, rootGroup);
222 return rootSectionGroup;
226 public ConfigurationSectionGroupCollection SectionGroups {
227 get { return RootSectionGroup.SectionGroups; }
230 public ConfigurationSectionCollection Sections {
231 get { return RootSectionGroup.Sections; }
234 public ConfigurationSection GetSection (string path)
236 string[] parts = path.Split ('/');
237 if (parts.Length == 1)
238 return Sections [parts[0]];
240 ConfigurationSectionGroup group = SectionGroups [parts[0]];
241 for (int n=1; group != null && n<parts.Length-1; n++)
242 group = group.SectionGroups [parts [n]];
245 return group.Sections [parts [parts.Length - 1]];
250 public ConfigurationSectionGroup GetSectionGroup (string path)
252 string[] parts = path.Split ('/');
253 ConfigurationSectionGroup group = SectionGroups [parts[0]];
254 for (int n=1; group != null && n<parts.Length; n++)
255 group = group.SectionGroups [parts [n]];
259 internal ConfigurationSection GetSectionInstance (SectionInfo config, bool createDefaultInstance)
261 object data = elementData [config];
262 ConfigurationSection sec = data as ConfigurationSection;
263 if (sec != null || !createDefaultInstance) return sec;
265 object secObj = config.CreateInstance ();
266 sec = secObj as ConfigurationSection;
268 DefaultSection ds = new DefaultSection ();
269 ds.SectionHandler = secObj as IConfigurationSectionHandler;
272 sec.Configuration = this;
274 ConfigurationSection parentSection = null;
275 if (parent != null) {
276 parentSection = parent.GetSectionInstance (config, true);
277 sec.SectionInformation.SetParentSection (parentSection);
279 sec.SectionInformation.ConfigFilePath = FilePath;
281 sec.ConfigContext = system.Host.CreateDeprecatedConfigContext(configPath);
283 string xml = data as string;
285 sec.Reset (parentSection);
287 if (xml != null && xml == data) {
288 XmlTextReader r = new ConfigXmlTextReader (new StringReader (xml), FilePath);
289 sec.DeserializeSection (r);
292 if (!String.IsNullOrEmpty (sec.SectionInformation.ConfigSource) && !String.IsNullOrEmpty (FilePath))
293 sec.DeserializeConfigSource (Path.GetDirectoryName (FilePath));
296 elementData [config] = sec;
300 internal ConfigurationSectionGroup GetSectionGroupInstance (SectionGroupInfo group)
302 ConfigurationSectionGroup gr = group.CreateInstance () as ConfigurationSectionGroup;
303 if (gr != null) gr.Initialize (this, group);
307 internal void SetConfigurationSection (SectionInfo config, ConfigurationSection sec)
309 elementData [config] = sec;
312 internal void SetSectionXml (SectionInfo config, string data)
314 elementData [config] = data;
317 internal string GetSectionXml (SectionInfo config)
319 return elementData [config] as string;
322 internal void CreateSection (SectionGroupInfo group, string name, ConfigurationSection sec)
324 if (group.HasChild (name))
325 throw new ConfigurationException ("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
327 if (!HasFile && !sec.SectionInformation.AllowLocation)
328 throw new ConfigurationErrorsException ("The configuration section <" + name + "> cannot be defined inside a <location> element.");
330 if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
331 object ctx = sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication ? (object) sec.SectionInformation.AllowExeDefinition : (object) sec.SectionInformation.AllowDefinition;
332 throw new ConfigurationErrorsException ("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + ctx + "').");
335 if (sec.SectionInformation.Type == null)
336 sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());
338 SectionInfo section = new SectionInfo (name, sec.SectionInformation);
339 section.StreamName = streamName;
340 section.ConfigHost = system.Host;
341 group.AddChild (section);
342 elementData [section] = sec;
345 internal void CreateSectionGroup (SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
347 if (parentGroup.HasChild (name)) throw new ConfigurationException ("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
348 if (sec.Type == null) sec.Type = system.Host.GetConfigTypeName (sec.GetType ());
351 SectionGroupInfo section = new SectionGroupInfo (name, sec.Type);
352 section.StreamName = streamName;
353 section.ConfigHost = system.Host;
354 parentGroup.AddChild (section);
355 elementData [section] = sec;
357 sec.Initialize (this, section);
360 internal void RemoveConfigInfo (ConfigInfo config)
362 elementData.Remove (config);
367 Save (ConfigurationSaveMode.Modified, false);
370 public void Save (ConfigurationSaveMode mode)
375 public void Save (ConfigurationSaveMode mode, bool forceUpdateAll)
377 ConfigurationSaveEventHandler saveStart = SaveStart;
378 ConfigurationSaveEventHandler saveEnd = SaveEnd;
381 Exception saveEx = null;
382 Stream stream = system.Host.OpenStreamForWrite (streamName, null, ref ctx);
384 if (saveStart != null)
385 saveStart (this, new ConfigurationSaveEventArgs (streamName, true, null, ctx));
387 Save (stream, mode, forceUpdateAll);
388 system.Host.WriteCompleted (streamName, true, ctx);
389 } catch (Exception ex) {
391 system.Host.WriteCompleted (streamName, false, ctx);
396 saveEnd (this, new ConfigurationSaveEventArgs (streamName, false, saveEx, ctx));
400 public void SaveAs (string filename)
402 SaveAs (filename, ConfigurationSaveMode.Modified, false);
405 public void SaveAs (string filename, ConfigurationSaveMode mode)
407 SaveAs (filename, mode, false);
410 [MonoInternalNote ("Detect if file has changed")]
411 public void SaveAs (string filename, ConfigurationSaveMode mode, bool forceUpdateAll)
413 string dir = Path.GetDirectoryName (Path.GetFullPath (filename));
414 if (!Directory.Exists (dir))
415 Directory.CreateDirectory (dir);
416 Save (new FileStream (filename, FileMode.OpenOrCreate, FileAccess.Write), mode, forceUpdateAll);
419 void Save (Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
421 XmlTextWriter tw = new XmlTextWriter (new StreamWriter (stream));
422 tw.Formatting = Formatting.Indented;
424 tw.WriteStartDocument ();
425 if (rootNamespace != null)
426 tw.WriteStartElement ("configuration", rootNamespace);
428 tw.WriteStartElement ("configuration");
429 if (rootGroup.HasConfigContent (this)) {
430 rootGroup.WriteConfig (this, tw, mode);
433 foreach (ConfigurationLocation loc in Locations) {
434 if (loc.OpenedConfiguration == null) {
436 tw.WriteRaw (loc.XmlContent);
439 tw.WriteStartElement ("location");
440 tw.WriteAttributeString ("path", loc.Path);
441 if (!loc.AllowOverride)
442 tw.WriteAttributeString ("allowOverride", "false");
443 loc.OpenedConfiguration.SaveData (tw, mode, forceUpdateAll);
444 tw.WriteEndElement ();
448 SaveData (tw, mode, forceUpdateAll);
449 tw.WriteEndElement ();
456 void SaveData (XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
458 rootGroup.WriteRootData (tw, this, mode);
463 if (String.IsNullOrEmpty (streamName))
466 if (!File.Exists (streamName))
469 Stream stream = stream = system.Host.OpenStreamForRead (streamName);
470 using (XmlTextReader reader = new ConfigXmlTextReader (stream, streamName)) {
471 ReadConfigFile (reader, streamName);
476 void ReadConfigFile (XmlReader reader, string fileName)
478 reader.MoveToContent ();
480 if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
481 ThrowException ("Configuration file does not have a valid root element", reader);
483 if (reader.HasAttributes) {
484 while (reader.MoveToNextAttribute ()) {
485 if (reader.LocalName == "xmlns") {
486 rootNamespace = reader.Value;
489 ThrowException (String.Format ("Unrecognized attribute '{0}' in root element", reader.LocalName), reader);
493 reader.MoveToElement ();
495 if (reader.IsEmptyElement) {
500 reader.ReadStartElement ();
501 reader.MoveToContent ();
503 if (reader.LocalName == "configSections") {
504 if (reader.HasAttributes)
505 ThrowException ("Unrecognized attribute in <configSections>.", reader);
507 rootGroup.ReadConfig (this, fileName, reader);
510 rootGroup.ReadRootData (reader, this, true);
513 internal void ReadData (XmlReader reader, bool allowOverride)
515 rootGroup.ReadData (this, reader, allowOverride);
519 private void ThrowException (string text, XmlReader reader)
521 IXmlLineInfo li = reader as IXmlLineInfo;
522 throw new ConfigurationException (text, streamName, li != null ? li.LineNumber : 0);