-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConfig.cs
1034 lines (985 loc) · 49.1 KB
/
Config.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2004-2010 Azavea, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Xml;
using Azavea.Open.Common.Collections;
using log4net;
namespace Azavea.Open.Common
{
/// <summary>
/// This class reads configuration parameters from a standalone config file
/// identified in the app.config or web.config's "appSettings" section.
/// </summary>
public class Config
{
/// <summary>
/// A logger that can be used by child classes as well.
/// </summary>
protected static readonly ILog _log = LogManager.GetLogger(
new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().DeclaringType.Namespace);
/// <summary>
/// We keep a cache of Config objects that can be accessed via the GetConfig method.
/// </summary>
private static readonly Dictionary<string, Config> _configCache =
new Dictionary<string, Config>(new CaseInsensitiveStringComparer());
/// <summary>
/// The filename (including path) of the config file.
/// </summary>
public readonly string ConfigFile;
/// <summary>
/// The contents of the config file as an XmlDocument.
/// </summary>
public readonly XmlDocument ConfigXmlDoc;
/// <summary>
/// The app name passed in when constructing this object.
/// </summary>
public readonly string Application;
/// <summary>
/// This is a Dictionary of groups of parameters (key/value pairs),
/// keyed by component (component = one section in the config file).
/// The groups are dictionaries to facilitate fast lookups by
/// key.
/// </summary>
protected readonly IDictionary<string, IDictionary<string, string>> _paramsByComponent;
/// <summary>
/// This is a Dictionary of groups of parameters (key/value pairs),
/// keyed by component (component = one section in the config file).
/// The groups are lists, for times when the order of the parameters
/// matters.
/// </summary>
protected readonly IDictionary<string, IList<KeyValuePair<string, string>>> _orderedParamsByComponent;
/// <summary>
/// This is a Dictionary of the XML contents of each component/section,
/// keyed by component (component = one section in the config file).
/// The values are XML strings. This includes the containing "component" tag.
/// </summary>
protected readonly IDictionary<string, string> _outerXmlByComponent;
/// <summary>
/// This is a Dictionary of the XML contents of each component/section,
/// keyed by component (component = one section in the config file).
/// The values are XML strings. This does NOT include the containing "component" tag.
/// </summary>
protected readonly IDictionary<string, string> _innerXmlByComponent;
/// <summary>
/// This allows you to avoid reading the same config file over and over again.
/// Since Config objects are read-only, we can read the file once and hand the
/// same object out over and over without worrying about threading issues.
/// </summary>
/// <param name="appName">Identifies which config file we want.</param>
/// <returns>The config object representing that config file.</returns>
public static Config GetConfig(string appName)
{
if (!StringHelper.IsNonBlank(appName))
{
throw new ArgumentNullException("appName", "Cannot construct a config with a blank/null app name.");
}
Config retVal = null;
lock (_configCache)
{
if (_configCache.ContainsKey(appName))
{
retVal = _configCache[appName];
}
}
if (retVal == null)
{
retVal = new Config(appName);
lock (_configCache)
{
_configCache[appName] = retVal;
}
}
return retVal;
}
/// <summary>
/// Allows you to explicitly remove a config from the cache, for example during
/// unit testing, or any time when you know the config file in the cache is
/// no longer valid.
/// </summary>
/// <param name="appName">Identifies which config file we want.</param>
public static void ClearConfigCache(string appName)
{
lock (_configCache)
{
_configCache.Remove(appName);
}
}
/// <summary>
/// Constructs a config class given the "appName", or the key to look up
/// in the app/web.config's "appSettings" section. The value for that key
/// is the path to the config file we're interested in.
/// </summary>
/// <param name="appName">Identifies which config file we want.</param>
public Config(string appName)
: this(null, appName, null) {}
/// <summary>
/// Constructs a config class given a specific config file to load.
/// </summary>
/// <param name="configFileName">The file name of the configuration file to load.</param>
/// <param name="appName">Since the config file is specified, this app name is just
/// used for identification in log/error messages.</param>
public Config(string configFileName, string appName)
: this(configFileName, appName, null) { }
/// <summary>
/// Construct a config directly from an XML document rather than from a file.
/// </summary>
/// <param name="appName">App name (I.E. config file name or whatever), used for logging.</param>
/// <param name="configXml">The XML containing all the config information.</param>
public Config(string appName, XmlDocument configXml)
: this(null, appName, configXml) { }
/// <summary>
/// Construct a config class. The app name is used for logging, and to get
/// the config file name if the file name was not specified and the XML was
/// not passed directly.
///
/// If you provide the XML, the app name is just used for logging, and the filename
/// is stored but not used for anything (and may be blank).
/// </summary>
/// <param name="configFileName">The file name of the configuration file to load.</param>
/// <param name="appName">App name (I.E. config file name or whatever), used for logging.</param>
/// <param name="configXml">The XML containing all the config information.</param>
public Config(string configFileName, string appName, XmlDocument configXml)
: this(configFileName, appName, configXml, false) { }
/// <summary>
/// The default behavior of Config is to throw an exception if the config file
/// does not exist. This constructor allows a child class to override that,
/// in which case a missing file will be treated as though it were empty
/// (no values loaded, but no exception thrown).
/// </summary>
/// <param name="configFileName">The file name of the configuration file to load.</param>
/// <param name="appName">App name (I.E. config file name or whatever), used for logging.</param>
/// <param name="configXml">The XML containing all the config information.</param>
/// <param name="treatMissingFileAsEmpty">If true, a missing config file will not cause an exception.</param>
protected Config(string configFileName, string appName, XmlDocument configXml,
bool treatMissingFileAsEmpty)
: this(configFileName, appName, configXml, treatMissingFileAsEmpty,
new CheckedDictionary<string, IDictionary<string, string>>(new CaseInsensitiveStringComparer()),
new CheckedDictionary<string, IList<KeyValuePair<string, string>>>(new CaseInsensitiveStringComparer()),
new CheckedDictionary<string, string>(new CaseInsensitiveStringComparer()),
new CheckedDictionary<string, string>(new CaseInsensitiveStringComparer())) { }
/// <summary>
/// This signature lets a child class provide more complicated or specific types of
/// collections.
///
/// Reminder: You probably want to use CaseInsensitiveStringComparers in your
/// dictionaries!
/// </summary>
/// <param name="configFileName">The file name of the configuration file to load.</param>
/// <param name="appName">App name (I.E. config file name or whatever), used for logging.</param>
/// <param name="configXml">The XML containing all the config information.</param>
/// <param name="treatMissingFileAsEmpty">If true, a missing config file will not cause an exception.</param>
/// <param name="paramsByComponent">The dictionary that will hold the parameters keyed by component.</param>
/// <param name="orderedParamsByComponent">The dictionary that will hold the parameters in order from the file, keyed by component.</param>
/// <param name="outerXmlByComponent">The dictionary that will hold XML chunks from the file, keyed by component.</param>
/// <param name="innerXmlByComponent">The dictionary that will hold XML chunks from the file, keyed by component.</param>
protected Config(string configFileName, string appName, XmlDocument configXml,
bool treatMissingFileAsEmpty,
IDictionary<string, IDictionary<string, string>> paramsByComponent,
IDictionary<string, IList<KeyValuePair<string, string>>> orderedParamsByComponent,
IDictionary<string, string> outerXmlByComponent,
IDictionary<string, string> innerXmlByComponent)
{
// First populate the attributes.
_paramsByComponent = paramsByComponent;
_orderedParamsByComponent = orderedParamsByComponent;
_outerXmlByComponent = outerXmlByComponent;
_innerXmlByComponent = innerXmlByComponent;
if (appName == null)
{
throw new ArgumentNullException(appName, "AppName cannot be null, config filename: " + configFileName + ".");
}
if (appName.Length == 0)
{
throw new ArgumentException("AppName cannot be blank, config filename: " + configFileName + ".");
}
Application = appName;
if (configXml == null)
{
// If the XML wasn't passed directly, load it from the filename instead.
if (configFileName != null)
{
if (configFileName.Length == 0)
{
throw new ArgumentException("No XML was provided and config filename was blank, appName: " +
appName + ".");
}
}
else
{
try
{
configFileName = ConfigurationManager.AppSettings[appName];
}
catch (Exception ex)
{
ReThrowException("No XML was provided and we were unable to retrieve config file name for app", new Object[] { appName }, ex);
}
if (configFileName == null)
{
throw new LoggingException("No XML was provided and we got a null config file name for app '" + appName + "'.");
}
if (configFileName.Length == 0)
{
throw new LoggingException("No XML was provided and we got a blank config file name for app '" + appName + "'.");
}
}
// Replace any environment variables in the config file name.
configFileName = ReplaceEnvironmentVariables(configFileName, false);
// Start with a blank doc, we'll either load a file into it or not depending
// on if the file exists.
ConfigXmlDoc = new XmlDocument();
if (!File.Exists(configFileName))
{
if (!treatMissingFileAsEmpty)
{
throw new LoggingException("No XML was provided and the specified config file (" +
configFileName + ") does not exist, app: '" + appName + "'.");
}
}
else
{
try
{
ConfigXmlDoc.Load(configFileName);
}
catch (Exception ex)
{
ReThrowException("Unable to load config file.",
new object[] { Application, configFileName }, ex);
}
}
}
else
{
ConfigXmlDoc = configXml;
}
ConfigFile = configFileName;
try
{
ParseConfigXml();
}
catch (Exception ex)
{
ReThrowException("Unable to parse config XML: " + ConfigXmlDoc.OuterXml,
new object[] { Application, ConfigFile }, ex);
}
}
/// <summary>
/// This is a ugly hack at the moment. This allows child classes to
/// override the internal type of collection we use. This will be
/// removed when we refactor the architecture to have an abstract
/// base class so we can have a "writeable" version of Config that does not
/// conflict with the implementation of this "readonly" Config.
/// </summary>
/// <returns>A dictionary to use to hold parameters we've read from the
/// config file.</returns>
protected virtual IDictionary<string, string> MakeParameterCollection()
{
return new CheckedDictionary<string, string>(new CaseInsensitiveStringComparer());
}
/// <summary>
/// Reads the XML and populates the various attributes based on it
/// (lists of params, dictionaries of params, etc).
/// </summary>
private void ParseConfigXml()
{
try
{
XmlNodeList nodeList = ConfigXmlDoc.GetElementsByTagName("component");
foreach (XmlNode node in nodeList)
{
string componentName = node.Attributes["name"].Value;
// Save the entire XML section for the GetConfigXml method
_outerXmlByComponent[componentName] = node.OuterXml;
_innerXmlByComponent[componentName] = node.InnerXml;
if (_paramsByComponent.ContainsKey(componentName))
{
throw new LoggingException("Component '" + componentName +
"' is defined twice in this config file!");
}
IDictionary<string, string> componentParams = MakeParameterCollection();
_paramsByComponent[componentName] = componentParams;
IList<KeyValuePair<string, string>> orderedComponentParams =
new List<KeyValuePair<string, string>>();
_orderedParamsByComponent[componentName] = orderedComponentParams;
// Now save all the individual parameters.
foreach (XmlNode paramNode in node.ChildNodes)
{
// Ignore any child nodes that aren't parameters.
if (StringHelper.SafeEquals("parameter", paramNode.Name))
{
string paramName = paramNode.Attributes["name"].Value;
if (componentParams.ContainsKey(paramName))
{
throw new LoggingException("Component '" + componentName +
"' has parameter '" + paramName + "' defined twice!");
}
XmlAttribute valueAttr = paramNode.Attributes["value"];
string paramValue;
if (valueAttr != null)
{
paramValue = valueAttr.Value;
}
else
{
XmlNodeList paramKids = paramNode.ChildNodes;
if (paramKids.Count == 1)
{
XmlNode paramKid = paramKids[0];
if (paramKid.NodeType == XmlNodeType.Text || paramKid.NodeType == XmlNodeType.CDATA)
{
paramValue = paramKid.Value;
}
else
{
throw new LoggingException("Component '" + componentName +
"', parameter '" + paramName +
"', has invalid nested XML ('" + paramNode.InnerText +
"'). Only text is supported inside a parameter tag.");
}
}
else
{
throw new LoggingException("Component '" + componentName +
"', parameter '" + paramName +
"', has invalid nested XML ('" + paramNode.InnerText +
"'). Only text is supported inside a parameter tag.");
}
}
componentParams[paramName] = paramValue;
orderedComponentParams.Add(new KeyValuePair<string, string>(paramName, paramValue));
}
}
}
}
catch (Exception e)
{
ReThrowException("Error parsing config XML.",
new object[] { Application, ConfigFile }, e);
}
}
/// <summary>
/// If there are any environment variables (in the form %VAR%) in the
/// input string, replaces them with the values from the environment.
///
/// This method can be tolerant or intolerant of errors, so:
/// "abc" -> "abc"
/// "abc%windir%abc" -> "abcC:\WINDOWSabc"
/// "abc%abc" -> exception (intolerant) or "abc%abc" (tolerant)
/// "abc%nosuchvar%abc" -> exception (intolerant) or "abc%nosuchvar%abc" (tolerant)
/// "abc%windir%abc%" -> exception (intolerant) or "abcC:\WINDOWSabc%" (tolerant)
///
/// Calling this method with "false" for tolerant matches the previous behavior.
///
/// Methods like File.Exists do not parse environment variables, so this
/// method should be called before attempting to use filenames etc.
/// </summary>
/// <param name="val">Input string to search for environment vars.</param>
/// <param name="tolerant">If true, this method logs warnings. If false, it
/// throws exceptions.</param>
/// <returns>The string with variables replaced with values, or the
/// unmodified string if there are no valid variables in it.
/// (Note: input of null means output of null).</returns>
public static string ReplaceEnvironmentVariables(string val, bool tolerant)
{
string retVal = null;
if (val != null)
{
// Seperate all pieces that might be env vars.
string[] parts = val.Split('%');
if (parts.Length == 1) {
// No % in the string, couldn't substitute any vars.
retVal = val;
}
else if (parts.Length == 2)
{
string message = "There was one % in the string, couldn't substitute any vars: '" +
val + "'.";
if (tolerant)
{
retVal = val;
}
else
{
throw new LoggingException(message);
}
}
else
{
StringBuilder returnString = new StringBuilder();
// There's no % before the first part.
bool leadingPerc = false;
// For each part (except the last, which can't be),
// see if it's an environment variable.
for (int index = 0; index < (parts.Length - 1); index++)
{
if (leadingPerc)
{
string envValue = Environment.GetEnvironmentVariable(
parts[index].ToUpper());
if (string.IsNullOrEmpty(envValue))
{
string message = "Value '" + val + "' has substring '%" + parts[index] + "%'" +
" which is not an environment variable.";
if (tolerant)
{
_log.Warn(message);
// Put it back in the output string unchanged.
returnString.Append("%"); // % was stripped out by the 'split' call.
returnString.Append(parts[index]);
// This isn't a variable, so it isn't using the next % either.
// So leave leadingPerc set to 'true',
}
else
{
throw new LoggingException(message);
}
}
else
{
returnString.Append(envValue);
// We just used the following %.
leadingPerc = false;
}
}
else
{
// No preceding %, this part isn't a variable.
returnString.Append(parts[index]);
// Since this isn't a variable, it didn't use the following %.
leadingPerc = true;
}
}
// Now add the last part, with a preceding % if there is one.
if (leadingPerc)
{
string message = "Unmatched % near the end of the input string: " + val;
if (tolerant)
{
_log.Warn(message);
returnString.Append("%");
}
else
{
throw new LoggingException(message);
}
}
returnString.Append(parts[parts.Length - 1]);
retVal = returnString.ToString();
}
}
return retVal;
}
/// <summary>
/// Returns the config parameter for the given component. Throws an exception
/// if there is no such parameter. If you want to know if the parameter exists,
/// call ParameterExists(...).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <returns>The string value for the parameter. Will never be null, if no
/// value could be found this method will throw. Could be ""
/// since "" is a valid thing to have in a config file.</returns>
public string GetParameter(string component, string parameter)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null. Parameter was '" +
parameter + "'.");
}
if (parameter == null)
{
throw new ArgumentNullException("parameter", "Parameter cannot be null. Component was '" +
component + "'.");
}
try
{
return _paramsByComponent[component][parameter];
}
catch (Exception ex)
{
ReThrowException("Unable to read parameter.",
new object[] { ConfigFile, component, parameter }, ex);
// that throws, but the compiler wants a return statement.
return "never gets here";
}
}
/// <summary>
/// Similar to GetParameter, but converts the type for you (if possible, throws if not).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <returns>The value for the parameter. Throws an exception if unable to convert
/// to an integer.</returns>
public int GetParameterAsInt(string component, string parameter)
{
int retVal;
if (!int.TryParse(GetParameter(component, parameter), out retVal))
{
throw new LoggingException("Component " + component + ", parameter " +
parameter + ", value was unable to be converted to an integer.");
}
return retVal;
}
/// <summary>
/// Similar to GetParameter, but converts the type for you (if possible, throws if not).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <returns>The value for the parameter. Throws an exception if unable to convert
/// to a double.</returns>
public double GetParameterAsDouble(string component, string parameter)
{
double retVal;
if (!double.TryParse(GetParameter(component, parameter), out retVal))
{
throw new LoggingException("Component " + component + ", parameter " +
parameter + ", value was unable to be converted to a double.");
}
return retVal;
}
/// <summary>
/// Similar to GetParameter, but converts the type for you (if possible, throws if not).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <returns>The value for the parameter. Throws an exception if unable to convert
/// to a boolean.</returns>
public bool GetParameterAsBool(string component, string parameter)
{
bool retVal;
if (!bool.TryParse(GetParameter(component, parameter), out retVal))
{
throw new LoggingException("Component " + component + ", parameter " +
parameter + ", value was unable to be converted to a boolean.");
}
return retVal;
}
/// <summary>
/// Similar to the regular GetParameter method, except it will substitute
/// environment variables in the values if present.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="tolerant">If true, this method logs warnings for unmatched environment
/// variables. If false, it throws exceptions.</param>
/// <returns>The string value for the parameter. Will never be null, if no
/// value could be found this method will throw. Could be ""
/// since "" is a valid thing to have in a config file.</returns>
public string GetParameterWithSubstitution(string component, string parameter, bool tolerant)
{
string value = GetParameter(component, parameter);
return ReplaceEnvironmentVariables(value, tolerant);
}
/// <summary>
/// Similar to the regular GetParameter method, except it will substitute
/// environment variables in the values if present.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="tolerant">If true, this method logs warnings for unmatched environment
/// variables. If false, it throws exceptions.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The string value for the parameter. Will never be null, if no
/// value could be found this method will throw. Could be ""
/// since "" is a valid thing to have in a config file.</returns>
public string GetParameterWithSubstitution(string component, string parameter,
bool tolerant, string defaultValue)
{
string value = GetParameter(component, parameter, defaultValue);
return ReplaceEnvironmentVariables(value, tolerant);
}
/// <summary>
/// Similar to GetParameter, except rather than throwing an exception if a parameter
/// doesn't exist, returns the default value.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public string GetParameter(string component, string parameter, string defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameter(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Similar to GetParameterWithDefault, except converts the type of the value (if present).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public int GetParameterAsInt(string component, string parameter, int defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameterAsInt(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Similar to GetParameterWithDefault, except converts the type of the value (if present).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public int? GetParameterAsInt(string component, string parameter, int? defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameterAsInt(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Similar to GetParameterWithDefault, except converts the type of the value (if present).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public bool GetParameterAsBool(string component, string parameter, bool defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameterAsBool(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Similar to GetParameterWithDefault, except converts the type of the value (if present).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public bool? GetParameterAsBool(string component, string parameter, bool? defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameterAsBool(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Similar to GetParameterWithDefault, except converts the type of the value (if present).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public double GetParameterAsDouble(string component, string parameter, double defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameterAsDouble(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Similar to GetParameterWithDefault, except converts the type of the value (if present).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <param name="defaultValue">Value to return if the parameter doesn't exist.</param>
/// <returns>The parameter from the config, or the default.</returns>
public double? GetParameterAsDouble(string component, string parameter, double? defaultValue)
{
if (ParameterExists(component, parameter))
{
return GetParameterAsDouble(component, parameter);
}
return defaultValue;
}
/// <summary>
/// Method to check if a parameter exists, prior to calling GetParameter (which
/// throws exceptions if you request an invalid parameter).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <param name="parameter">The name of the config parameter.</param>
/// <returns>True if the component has a section in the config file, and if that
/// section has the parameter. False otherwise.</returns>
public bool ParameterExists(string component, string parameter)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null. Parameter was '" +
parameter + "'.");
}
if (parameter == null)
{
throw new ArgumentNullException("parameter", "Parameter cannot be null. Component was '" +
component + "'.");
}
try
{
if (_paramsByComponent.ContainsKey(component))
{
if (_paramsByComponent[component].ContainsKey(parameter))
{
return true;
}
}
return false;
}
catch(Exception ex)
{
ReThrowException("Unable to check if parameter exists.",
new object[] { ConfigFile, component, parameter }, ex);
// that throws, but the compiler wants a return statement.
return false;
}
}
/// <summary>
/// Method to check if a config section exists for a component, prior to calling
/// GetConfigXml or GetParametersAsHashTable (which throw exceptions if you request
/// an invalid component name).
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <returns>True if the component has a section in the config file. False otherwise.</returns>
public bool ComponentExists(string component)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null.");
}
try
{
if (_paramsByComponent.ContainsKey(component))
{
return true;
}
return false;
}
catch (Exception ex)
{
ReThrowException("Unable to check if component exists.",
new object[] { ConfigFile, component }, ex);
// that throws, but the compiler wants a return statement.
return false;
}
}
/// <summary>
/// Gets you the XML section for the component, allowing you to do any special
/// parsing that may be necessary. This includes the "component" tag, and any
/// text included in that tag.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <returns>The XML section (inclusive of the "component" tag) for the
/// given component.</returns>
public virtual string GetConfigXml(string component)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null.");
}
try
{
return _outerXmlByComponent[component];
}
catch(Exception ex)
{
ReThrowException("Error while getting config XML for component.",
new object[] { ConfigFile, component }, ex);
// that throws, but the compiler wants a return statement.
return null;
}
}
/// <summary>
/// Gets you the XML section for the component, allowing you to do any special
/// parsing that may be necessary. This includes ONLY the children of the
/// "component" tag, and will not have any text included in that tag.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <returns>The XML section (exclusive of the "component" tag) for the
/// given component.</returns>
public virtual string GetConfigInnerXml(string component)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null.");
}
try
{
return _innerXmlByComponent[component];
}
catch (Exception ex)
{
ReThrowException("Error while getting config inner XML for component.",
new object[] { ConfigFile, component }, ex);
// that throws, but the compiler wants a return statement.
return null;
}
}
/// <summary>
/// Gets you a Dictionary of all the parameters for the component.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <returns>A Dictionary, with string values keyed (case insentively) by string parameter names.</returns>
public Dictionary<string, string> GetParametersAsDictionary(string component)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null.");
}
try
{
// Convert to upper for case insensitivity.
return new Dictionary<string, string>(_paramsByComponent[component],
new CaseInsensitiveStringComparer());
}
catch (Exception ex)
{
ReThrowException("Error while getting params as Dictionary.",
new object[] { ConfigFile, component }, ex);
// that throws, but the compiler wants a return statement.
return null;
}
}
/// <summary>
/// Gets you a list of all the parameters for the component as key-value-pairs.
/// This preserves the order of parameters from the config file.
/// </summary>
/// <param name="component">The component or section of the config file, used to
/// locate the parameter.</param>
/// <returns>A list of key-value-pairs, with string values keyed by string parameter names.</returns>
public virtual IList<KeyValuePair<string, string>> GetParametersAsList(string component)
{
if (component == null)
{
throw new ArgumentNullException("component", "Component cannot be null.");
}
try
{
// Convert to upper for case insensitivity.
return new List<KeyValuePair<string, string>>(_orderedParamsByComponent[component]);
}
catch (Exception ex)
{
ReThrowException("Error while getting params as IList.",
new object[] { ConfigFile, component }, ex);
// that throws, but the compiler wants a return statement.
return null;
}
}
/// <summary>
/// All the checks for null are because there was an issue where something about
/// a caught exception was null, which caused the error handling code to bomb.
/// Since error handling code is the worst place to bomb (you lose the original
/// exception), to be safe we manually convert null values into "null" strings.
/// </summary>
protected static void ReThrowException(string msg, object[] paramList, Exception orig)
{
if (msg == null)
{
msg = "null message";
}
if ((paramList != null) && (paramList.Length > 0))
{
msg += " (" + ((paramList[0] == null) ? "null" : paramList[0].ToString());
for (int x = 1; x < paramList.Length; x++)
{
msg += ", " + ((paramList[x] == null) ? "null" : paramList[x].ToString());
}
msg += ")\n";
}
if (orig == null)
{
msg += "Exception was null.";
}
else
{
msg += "Exception Message: " + (orig.Message ?? "null") + "\n";
msg += "Exception StackTrace: " + (orig.StackTrace ?? "null");
}
throw new LoggingException(msg);
}
///<summary>
/// Two Configs with the same config file and appname are Equal.
///</summary>
///
///<returns>
///true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, false.
///</returns>
///
///<param name="obj">The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />. </param>
///<exception cref="T:System.NullReferenceException">The <paramref name="obj" /> parameter is null.</exception><filterpriority>2</filterpriority>
public override bool Equals(object obj)