2 // System.Diagnostics.DiagnosticsConfigurationHandler.cs
4 // Comments from John R. Hicks <angryjohn69@nc.rr.com> original implementation
5 // can be found at: /mcs/docs/apidocs/xml/en/System.Diagnostics
8 // John R. Hicks <angryjohn69@nc.rr.com>
9 // Jonathan Pryor <jonpryor@vt.edu>
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Configuration;
38 using System.Reflection;
39 using System.Threading;
43 namespace System.Diagnostics
45 // It handles following elements in <system.diagnostics> :
46 // - <sharedListeners> [2.0]
49 // - <listeners> (collection)
51 // - <add name=string value=string />
52 // - <trace autoflush=bool indentsize=int useGlobalLock=bool>
54 internal sealed class DiagnosticsConfiguration
57 private static object lock_ = new object();
59 private static object settings;
61 public static IDictionary Settings {
64 if (settings == null) {
65 object s = ConfigurationSettings.GetConfig ("system.diagnostics");
67 throw new Exception ("INTERNAL configuration error: failed to get configuration 'system.diagnostics'");
68 Thread.MemoryBarrier ();
69 while (Interlocked.CompareExchange (ref settings, s, null) == null) {
70 // do nothing; we're just setting settings.
72 Thread.MemoryBarrier ();
77 settings = ConfigurationSettings.GetConfig ("system.diagnostics");
80 return (IDictionary) settings;
85 [Obsolete ("This class is obsoleted")]
86 public class DiagnosticsConfigurationHandler : IConfigurationSectionHandler
88 TraceImplSettings configValues;
90 delegate void ElementHandler (IDictionary d, XmlNode node);
92 IDictionary elementHandlers = new Hashtable ();
94 public DiagnosticsConfigurationHandler ()
96 elementHandlers ["assert"] = new ElementHandler (AddAssertNode);
97 elementHandlers ["switches"] = new ElementHandler (AddSwitchesNode);
98 elementHandlers ["trace"] = new ElementHandler (AddTraceNode);
99 elementHandlers ["sources"] = new ElementHandler (AddSourcesNode);
102 public virtual object Create (object parent, object configContext, XmlNode section)
106 d = new Hashtable (CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
108 d = (IDictionary) ((ICloneable)parent).Clone();
110 if (d.Contains (TraceImplSettings.Key))
111 configValues = (TraceImplSettings) d [TraceImplSettings.Key];
113 d.Add (TraceImplSettings.Key, configValues = new TraceImplSettings ());
115 // process <sharedListeners> first
116 foreach (XmlNode child in section.ChildNodes) {
117 switch (child.NodeType) {
118 case XmlNodeType.Element:
119 if (child.LocalName != "sharedListeners")
121 AddTraceListeners (d, child, GetSharedListeners (d));
126 foreach (XmlNode child in section.ChildNodes) {
127 XmlNodeType type = child.NodeType;
131 case XmlNodeType.Whitespace:
132 case XmlNodeType.Comment:
134 case XmlNodeType.Element:
135 if (child.LocalName == "sharedListeners")
137 ElementHandler eh = (ElementHandler) elementHandlers [child.Name];
141 ThrowUnrecognizedElement (child);
144 ThrowUnrecognizedElement (child);
152 // Remarks: Both attribute are optional
153 private void AddAssertNode (IDictionary d, XmlNode node)
155 XmlAttributeCollection c = node.Attributes;
156 string assertuienabled = GetAttribute (c, "assertuienabled", false, node);
157 string logfilename = GetAttribute (c, "logfilename", false, node);
158 ValidateInvalidAttributes (c, node);
159 if (assertuienabled != null) {
161 d ["assertuienabled"] = bool.Parse (assertuienabled);
163 catch (Exception e) {
164 throw new ConfigurationException ("The `assertuienabled' attribute must be `true' or `false'",
169 if (logfilename != null)
170 d ["logfilename"] = logfilename;
172 DefaultTraceListener dtl = (DefaultTraceListener) configValues.Listeners["Default"];
174 if (assertuienabled != null)
175 dtl.AssertUiEnabled = (bool) d ["assertuienabled"];
176 if (logfilename != null)
177 dtl.LogFileName = logfilename;
180 if (node.ChildNodes.Count > 0)
181 ThrowUnrecognizedElement (node.ChildNodes[0]);
184 // name and value attributes are required
185 // Docs do not define "remove" or "clear" elements, but .NET recognizes
187 private void AddSwitchesNode (IDictionary d, XmlNode node)
189 // There are no attributes on <switch/>
190 ValidateInvalidAttributes (node.Attributes, node);
192 IDictionary newNodes = new Hashtable ();
194 foreach (XmlNode child in node.ChildNodes) {
195 XmlNodeType t = child.NodeType;
196 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
198 if (t == XmlNodeType.Element) {
199 XmlAttributeCollection attributes = child.Attributes;
202 switch (child.Name) {
204 name = GetAttribute (attributes, "name", true, child);
205 value = GetAttribute (attributes, "value", true, child);
206 newNodes [name] = GetSwitchValue (name, value);
209 name = GetAttribute (attributes, "name", true, child);
210 newNodes.Remove (name);
216 ThrowUnrecognizedElement (child);
219 ValidateInvalidAttributes (attributes, child);
222 ThrowUnrecognizedNode (child);
225 d [node.Name] = newNodes;
228 private static object GetSwitchValue (string name, string value)
233 private void AddTraceNode (IDictionary d, XmlNode node)
235 AddTraceAttributes (d, node);
237 foreach (XmlNode child in node.ChildNodes) {
238 XmlNodeType t = child.NodeType;
239 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
241 if (t == XmlNodeType.Element) {
242 if (child.Name == "listeners")
243 AddTraceListeners (d, child, configValues.Listeners);
245 ThrowUnrecognizedElement (child);
246 ValidateInvalidAttributes (child.Attributes, child);
249 ThrowUnrecognizedNode (child);
253 // all attributes are optional
254 private void AddTraceAttributes (IDictionary d, XmlNode node)
256 XmlAttributeCollection c = node.Attributes;
257 string autoflushConf = GetAttribute (c, "autoflush", false, node);
258 string indentsizeConf = GetAttribute (c, "indentsize", false, node);
259 ValidateInvalidAttributes (c, node);
260 if (autoflushConf != null) {
261 bool autoflush = false;
263 autoflush = bool.Parse (autoflushConf);
264 d ["autoflush"] = autoflush;
265 } catch (Exception e) {
266 throw new ConfigurationException ("The `autoflush' attribute must be `true' or `false'",
269 configValues.AutoFlush = autoflush;
271 if (indentsizeConf != null) {
274 indentsize = int.Parse (indentsizeConf);
275 d ["indentsize"] = indentsize;
276 } catch (Exception e) {
277 throw new ConfigurationException ("The `indentsize' attribute must be an integral value.",
280 configValues.IndentSize = indentsize;
284 private TraceListenerCollection GetSharedListeners (IDictionary d)
286 TraceListenerCollection shared_listeners = d ["sharedListeners"] as TraceListenerCollection;
287 if (shared_listeners == null) {
288 shared_listeners = new TraceListenerCollection (false);
289 d ["sharedListeners"] = shared_listeners;
291 return shared_listeners;
294 private void AddSourcesNode (IDictionary d, XmlNode node)
296 // FIXME: are there valid attributes?
297 ValidateInvalidAttributes (node.Attributes, node);
298 Hashtable sources = d ["sources"] as Hashtable;
299 if (sources == null) {
300 sources = new Hashtable ();
301 d ["sources"] = sources;
304 foreach (XmlNode child in node.ChildNodes) {
305 XmlNodeType t = child.NodeType;
306 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
308 if (t == XmlNodeType.Element) {
309 if (child.Name == "source")
310 AddTraceSource (d, sources, child);
312 ThrowUnrecognizedElement (child);
313 // ValidateInvalidAttributes (child.Attributes, child);
316 ThrowUnrecognizedNode (child);
320 private void AddTraceSource (IDictionary d, Hashtable sources, XmlNode node)
323 SourceLevels levels = SourceLevels.Error;
324 StringDictionary atts = new StringDictionary ();
325 foreach (XmlAttribute a in node.Attributes) {
331 levels = (SourceLevels) Enum.Parse (typeof (SourceLevels), a.Value);
334 atts [a.Name] = a.Value;
339 throw new ConfigurationException ("Mandatory attribute 'name' is missing in 'source' element.");
341 // ignore duplicate ones (no error occurs)
342 if (sources.ContainsKey (name))
345 TraceSourceInfo sinfo = new TraceSourceInfo (name, levels, configValues);
346 sources.Add (sinfo.Name, sinfo);
348 foreach (XmlNode child in node.ChildNodes) {
349 XmlNodeType t = child.NodeType;
350 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
352 if (t == XmlNodeType.Element) {
353 if (child.Name == "listeners")
354 AddTraceListeners (d, child, sinfo.Listeners);
356 ThrowUnrecognizedElement (child);
357 ValidateInvalidAttributes (child.Attributes, child);
360 ThrowUnrecognizedNode (child);
364 // only defines "add" and "remove", but "clear" also works
365 // for add, "name" is required; initializeData is optional; "type" is required in 1.x, optional in 2.0.
366 private void AddTraceListeners (IDictionary d, XmlNode listenersNode, TraceListenerCollection listeners)
368 // There are no attributes on <listeners/>
369 ValidateInvalidAttributes (listenersNode.Attributes, listenersNode);
371 foreach (XmlNode child in listenersNode.ChildNodes) {
372 XmlNodeType t = child.NodeType;
373 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
375 if (t == XmlNodeType.Element) {
376 XmlAttributeCollection attributes = child.Attributes;
378 switch (child.Name) {
380 AddTraceListener (d, child, attributes, listeners);
383 name = GetAttribute (attributes, "name", true, child);
384 RemoveTraceListener (name);
387 configValues.Listeners.Clear ();
390 ThrowUnrecognizedElement (child);
393 ValidateInvalidAttributes (attributes, child);
396 ThrowUnrecognizedNode (child);
400 private void AddTraceListener (IDictionary d, XmlNode child, XmlAttributeCollection attributes, TraceListenerCollection listeners)
402 string name = GetAttribute (attributes, "name", true, child);
405 #if CONFIGURATION_DEP
406 type = GetAttribute (attributes, "type", false, child);
408 // indicated by name.
409 TraceListener shared = GetSharedListeners (d) [name];
411 throw new ConfigurationException (String.Format ("Shared trace listener {0} does not exist.", name));
412 if (attributes.Count != 0)
413 throw new ConfigurationErrorsException (string.Format (
414 "Listener '{0}' references a shared " +
415 "listener and can only have a 'Name' " +
416 "attribute.", name));
417 listeners.Add (shared, configValues);
421 type = GetAttribute (attributes, "type", true, child);
424 Type t = Type.GetType (type);
426 throw new ConfigurationException (string.Format ("Invalid Type Specified: {0}", type));
431 string initializeData = GetAttribute (attributes, "initializeData", false, child);
432 if (initializeData != null) {
433 args = new object[] { initializeData };
434 types = new Type[] { typeof(string) };
437 types = Type.EmptyTypes;
440 BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
441 if (t.Assembly == GetType ().Assembly)
442 flags |= BindingFlags.NonPublic;
444 ConstructorInfo ctor = t.GetConstructor (flags, null, types, null);
446 throw new ConfigurationException ("Couldn't find constructor for class " + type);
448 TraceListener l = (TraceListener) ctor.Invoke (args);
451 #if CONFIGURATION_DEP
452 string trace = GetAttribute (attributes, "traceOutputOptions", false, child);
454 if (trace != trace.Trim ())
455 throw new ConfigurationErrorsException (string.Format (
456 "Invalid value '{0}' for 'traceOutputOptions'.",
459 TraceOptions trace_options;
462 trace_options = (TraceOptions) Enum.Parse (
463 typeof (TraceOptions), trace);
464 } catch (ArgumentException) {
465 throw new ConfigurationErrorsException (string.Format (
466 "Invalid value '{0}' for 'traceOutputOptions'.",
470 l.TraceOutputOptions = trace_options;
473 string [] supported_attributes = l.GetSupportedAttributes ();
474 if (supported_attributes != null) {
475 for (int i = 0; i < supported_attributes.Length; i++) {
476 string key = supported_attributes [i];
477 string value = GetAttribute (attributes, key, false, child);
479 l.Attributes.Add (key, value);
484 listeners.Add (l, configValues);
487 private void RemoveTraceListener (string name)
490 configValues.Listeners.Remove (name);
492 catch (ArgumentException) {
493 // The specified listener wasn't in the collection
494 // Ignore this; .NET does.
496 catch (Exception e) {
497 throw new ConfigurationException (
498 string.Format ("Unknown error removing listener: {0}", name),
503 private string GetAttribute (XmlAttributeCollection attrs, string attr, bool required, XmlNode node)
505 XmlAttribute a = attrs[attr];
512 ValidateAttribute (attr, r, node);
516 ThrowMissingAttribute (attr, node);
521 private void ValidateAttribute (string attribute, string value, XmlNode node)
523 if (value == null || value.Length == 0)
524 throw new ConfigurationException (string.Format ("Required attribute '{0}' cannot be empty.", attribute), node);
527 private void ValidateInvalidAttributes (XmlAttributeCollection c, XmlNode node)
530 ThrowUnrecognizedAttribute (c[0].Name, node);
533 private void ThrowMissingAttribute (string attribute, XmlNode node)
535 throw new ConfigurationException (string.Format ("Required attribute '{0}' not found.", attribute), node);
538 private void ThrowUnrecognizedNode (XmlNode node)
540 throw new ConfigurationException (
541 string.Format ("Unrecognized node `{0}'; nodeType={1}", node.Name, node.NodeType),
545 private void ThrowUnrecognizedElement (XmlNode node)
547 throw new ConfigurationException (
548 string.Format ("Unrecognized element '{0}'.", node.Name),
552 private void ThrowUnrecognizedAttribute (string attribute, XmlNode node)
554 throw new ConfigurationException (
555 string.Format ("Unrecognized attribute '{0}' on element <{1}/>.", attribute, node.Name),