]> wagnertech.de Git - mDoc.git/blob - csharp/mutil/Configuration.cs
Bugfix 126
[mDoc.git] / csharp / mutil / Configuration.cs
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4
5 namespace mutil {
6
7 public class Configuration {
8     private Dictionary<string,string> configs = new Dictionary<string,string>();
9     private string filename;
10     private Configuration(string filename) {
11         this.filename = filename;
12         if (File.Exists(filename)) {
13             XmlExtractor xmle = new XmlExtractor();
14             xmle.openInput(filename);
15             xmle.requireChild("configuration");
16             string elem;
17             string value;
18             Dictionary<string,string> attrs;
19
20             int ctl = xmle.extractElement(XmlExtractor.EC_BEG, out elem, out value, out attrs);
21             while (ctl != XmlExtractor.EC_END) {
22                 if (elem != "entry") throw new ApplicationException("entry tag expected.");
23                 configs.Add(attrs["key"], value);
24                 ctl = xmle.extractElement(ctl, out elem, out value, out attrs);
25             }
26         }
27     }
28     static private Configuration theInstance = null;
29     static public Configuration getInstance(string filename) {
30         if (theInstance == null) theInstance = new Configuration(filename);
31         return theInstance;
32     }
33     static public Configuration getInstance() {
34         if (theInstance == null) throw new System.Exception("parameter filename missing.");
35         return theInstance;
36     }
37     
38     public void Add(string key, string value) {
39         string dummy;
40         if (this.configs.TryGetValue(key, out dummy)) this.configs[key] = value;
41         else this.configs.Add(key, value);
42     }
43     
44     public string Require(string key) {
45         return this.configs[key];
46     }
47
48     public string Get(string key) {
49         string value;
50         this.configs.TryGetValue(key, out value);
51         return value;
52     }
53
54     public string Get(string key, string defaut) {
55         string value;
56         if (! this.configs.TryGetValue(key, out value)) return defaut;
57         return value;
58     }
59
60     ~Configuration() {
61         StreamWriter outfile;
62         using ( outfile = new StreamWriter (this.filename)) {
63             outfile.WriteLine("<configuration>");
64             foreach(var config in this.configs) {
65                 outfile.WriteLine("<entry key=\"{0}\">{1}</entry>", config.Key, config.Value);
66             }
67             outfile.WriteLine("</configuration>");
68         }    
69     }
70 }
71
72 }
73