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)
190 // There are no attributes on <switch/>
191 ValidateInvalidAttributes (node.Attributes, node);
193 IDictionary newNodes = new Hashtable ();
195 foreach (XmlNode child in node.ChildNodes) {
196 XmlNodeType t = child.NodeType;
197 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
199 if (t == XmlNodeType.Element) {
200 XmlAttributeCollection attributes = child.Attributes;
203 switch (child.Name) {
205 name = GetAttribute (attributes, "name", true, child);
206 value = GetAttribute (attributes, "value", true, child);
207 newNodes [name] = GetSwitchValue (name, value);
210 name = GetAttribute (attributes, "name", true, child);
211 newNodes.Remove (name);
217 ThrowUnrecognizedElement (child);
220 ValidateInvalidAttributes (attributes, child);
223 ThrowUnrecognizedNode (child);
226 d [node.Name] = newNodes;
230 private static object GetSwitchValue (string name, string value)
235 private void AddTraceNode (IDictionary d, XmlNode node)
237 AddTraceAttributes (d, node);
239 foreach (XmlNode child in node.ChildNodes) {
240 XmlNodeType t = child.NodeType;
241 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
243 if (t == XmlNodeType.Element) {
244 if (child.Name == "listeners")
245 AddTraceListeners (d, child, configValues.Listeners);
247 ThrowUnrecognizedElement (child);
248 ValidateInvalidAttributes (child.Attributes, child);
251 ThrowUnrecognizedNode (child);
255 // all attributes are optional
256 private void AddTraceAttributes (IDictionary d, XmlNode node)
258 XmlAttributeCollection c = node.Attributes;
259 string autoflushConf = GetAttribute (c, "autoflush", false, node);
260 string indentsizeConf = GetAttribute (c, "indentsize", false, node);
261 ValidateInvalidAttributes (c, node);
262 if (autoflushConf != null) {
263 bool autoflush = false;
265 autoflush = bool.Parse (autoflushConf);
266 d ["autoflush"] = autoflush;
267 } catch (Exception e) {
268 throw new ConfigurationException ("The `autoflush' attribute must be `true' or `false'",
271 configValues.AutoFlush = autoflush;
273 if (indentsizeConf != null) {
276 indentsize = int.Parse (indentsizeConf);
277 d ["indentsize"] = indentsize;
278 } catch (Exception e) {
279 throw new ConfigurationException ("The `indentsize' attribute must be an integral value.",
282 configValues.IndentSize = indentsize;
286 private TraceListenerCollection GetSharedListeners (IDictionary d)
288 TraceListenerCollection shared_listeners = d ["sharedListeners"] as TraceListenerCollection;
289 if (shared_listeners == null) {
290 shared_listeners = new TraceListenerCollection (false);
291 d ["sharedListeners"] = shared_listeners;
293 return shared_listeners;
296 private void AddSourcesNode (IDictionary d, XmlNode node)
298 // FIXME: are there valid attributes?
299 ValidateInvalidAttributes (node.Attributes, node);
300 Hashtable sources = d ["sources"] as Hashtable;
301 if (sources == null) {
302 sources = new Hashtable ();
303 d ["sources"] = sources;
306 foreach (XmlNode child in node.ChildNodes) {
307 XmlNodeType t = child.NodeType;
308 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
310 if (t == XmlNodeType.Element) {
311 if (child.Name == "source")
312 AddTraceSource (d, sources, child);
314 ThrowUnrecognizedElement (child);
315 // ValidateInvalidAttributes (child.Attributes, child);
318 ThrowUnrecognizedNode (child);
322 private void AddTraceSource (IDictionary d, Hashtable sources, XmlNode node)
325 SourceLevels levels = SourceLevels.Error;
326 StringDictionary atts = new StringDictionary ();
327 foreach (XmlAttribute a in node.Attributes) {
333 levels = (SourceLevels) Enum.Parse (typeof (SourceLevels), a.Value);
336 atts [a.Name] = a.Value;
341 throw new ConfigurationException ("Mandatory attribute 'name' is missing in 'source' element.");
343 // ignore duplicate ones (no error occurs)
344 if (sources.ContainsKey (name))
347 TraceSourceInfo sinfo = new TraceSourceInfo (name, levels, configValues);
348 sources.Add (sinfo.Name, sinfo);
350 foreach (XmlNode child in node.ChildNodes) {
351 XmlNodeType t = child.NodeType;
352 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
354 if (t == XmlNodeType.Element) {
355 if (child.Name == "listeners")
356 AddTraceListeners (d, child, sinfo.Listeners);
358 ThrowUnrecognizedElement (child);
359 ValidateInvalidAttributes (child.Attributes, child);
362 ThrowUnrecognizedNode (child);
366 // only defines "add" and "remove", but "clear" also works
367 // for add, "name" is required; initializeData is optional; "type" is required in 1.x, optional in 2.0.
368 private void AddTraceListeners (IDictionary d, XmlNode listenersNode, TraceListenerCollection listeners)
371 // There are no attributes on <listeners/>
372 ValidateInvalidAttributes (listenersNode.Attributes, listenersNode);
374 foreach (XmlNode child in listenersNode.ChildNodes) {
375 XmlNodeType t = child.NodeType;
376 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
378 if (t == XmlNodeType.Element) {
379 XmlAttributeCollection attributes = child.Attributes;
381 switch (child.Name) {
383 AddTraceListener (d, child, attributes, listeners);
386 name = GetAttribute (attributes, "name", true, child);
387 RemoveTraceListener (name);
390 configValues.Listeners.Clear ();
393 ThrowUnrecognizedElement (child);
396 ValidateInvalidAttributes (attributes, child);
399 ThrowUnrecognizedNode (child);
404 private void AddTraceListener (IDictionary d, XmlNode child, XmlAttributeCollection attributes, TraceListenerCollection listeners)
406 string name = GetAttribute (attributes, "name", true, child);
409 #if CONFIGURATION_DEP
410 type = GetAttribute (attributes, "type", false, child);
412 // indicated by name.
413 TraceListener shared = GetSharedListeners (d) [name];
415 throw new ConfigurationException (String.Format ("Shared trace listener {0} does not exist.", name));
416 if (attributes.Count != 0)
417 throw new ConfigurationErrorsException (string.Format (
418 "Listener '{0}' references a shared " +
419 "listener and can only have a 'Name' " +
420 "attribute.", name));
421 listeners.Add (shared, configValues);
425 type = GetAttribute (attributes, "type", true, child);
428 Type t = Type.GetType (type);
430 throw new ConfigurationException (string.Format ("Invalid Type Specified: {0}", type));
435 string initializeData = GetAttribute (attributes, "initializeData", false, child);
436 if (initializeData != null) {
437 args = new object[] { initializeData };
438 types = new Type[] { typeof(string) };
441 types = Type.EmptyTypes;
444 BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
445 if (t.Assembly == GetType ().Assembly)
446 flags |= BindingFlags.NonPublic;
448 ConstructorInfo ctor = t.GetConstructor (flags, null, types, null);
450 throw new ConfigurationException ("Couldn't find constructor for class " + type);
452 TraceListener l = (TraceListener) ctor.Invoke (args);
455 #if CONFIGURATION_DEP
456 string trace = GetAttribute (attributes, "traceOutputOptions", false, child);
458 if (trace != trace.Trim ())
459 throw new ConfigurationErrorsException (string.Format (
460 "Invalid value '{0}' for 'traceOutputOptions'.",
463 TraceOptions trace_options;
466 trace_options = (TraceOptions) Enum.Parse (
467 typeof (TraceOptions), trace);
468 } catch (ArgumentException) {
469 throw new ConfigurationErrorsException (string.Format (
470 "Invalid value '{0}' for 'traceOutputOptions'.",
474 l.TraceOutputOptions = trace_options;
477 string [] supported_attributes = l.GetSupportedAttributes ();
478 if (supported_attributes != null) {
479 for (int i = 0; i < supported_attributes.Length; i++) {
480 string key = supported_attributes [i];
481 string value = GetAttribute (attributes, key, false, child);
483 l.Attributes.Add (key, value);
488 listeners.Add (l, configValues);
491 private void RemoveTraceListener (string name)
494 configValues.Listeners.Remove (name);
496 catch (ArgumentException) {
497 // The specified listener wasn't in the collection
498 // Ignore this; .NET does.
500 catch (Exception e) {
501 throw new ConfigurationException (
502 string.Format ("Unknown error removing listener: {0}", name),
507 private string GetAttribute (XmlAttributeCollection attrs, string attr, bool required, XmlNode node)
509 XmlAttribute a = attrs[attr];
516 ValidateAttribute (attr, r, node);
520 ThrowMissingAttribute (attr, node);
525 private void ValidateAttribute (string attribute, string value, XmlNode node)
527 if (value == null || value.Length == 0)
528 throw new ConfigurationException (string.Format ("Required attribute '{0}' cannot be empty.", attribute), node);
531 private void ValidateInvalidAttributes (XmlAttributeCollection c, XmlNode node)
534 ThrowUnrecognizedAttribute (c[0].Name, node);
537 private void ThrowMissingAttribute (string attribute, XmlNode node)
539 throw new ConfigurationException (string.Format ("Required attribute '{0}' not found.", attribute), node);
542 private void ThrowUnrecognizedNode (XmlNode node)
544 throw new ConfigurationException (
545 string.Format ("Unrecognized node `{0}'; nodeType={1}", node.Name, node.NodeType),
549 private void ThrowUnrecognizedElement (XmlNode node)
551 throw new ConfigurationException (
552 string.Format ("Unrecognized element '{0}'.", node.Name),
556 private void ThrowUnrecognizedAttribute (string attribute, XmlNode node)
558 throw new ConfigurationException (
559 string.Format ("Unrecognized attribute '{0}' on element <{1}/>.", attribute, node.Name),