using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Collections.Generic;
namespace XMLFileLoad.Common
{
public class StepRuleSetting
{
private const string SettingsPath = "StepRule.xml";
private static StepRuleSetting _instance;
private readonly DataTable StepRuleDT = new DataTable();
private readonly Dictionary<string,List<string>> DicRules = new Dictionary<string,List<string>>();
private List<string> Rules = new List<string>();
private StepRuleSetting()
{
}
public static StepRuleSetting Instance
{
get
{
if (_instance == null) _instance = new StepRuleSetting();
_instance.Load();
return _instance;
}
}
public bool HasContainsKey(string stepType)
{
return DicRules.ContainsKey(stepType);
}
public List<string> GetStepRules(string stepType)
{
if (HasContainsKey(stepType))
{
Rules = DicRules[stepType];
if (Rules.Count <= 0)
{
MessageWindow.Show(MessageLevel.Warning, "No rules under this steptype: " + SettingsPath);
}
}
return Rules;
}
private void Load()
{
var xml = new XmlDocument();
try
{
xml.Load(Path.Combine(Environment.CurrentDirectory, "Settings", SettingsPath));
var ruleListRoot = xml.DocumentElement.SelectSingleNode("/RuleList");
if (ruleListRoot == null)
{
return;
}
var stepTypeLists = xml.DocumentElement.SelectNodes("/RuleList/StepType");
foreach (XmlNode node in stepTypeLists)
{
if (node.Attributes["name"] == null)
{
throw new ArgumentException("Required attribute ‘name‘ is missing in configuration file " +
SettingsPath);
}
}
foreach (XmlNode node in stepTypeLists)
{
var stepRuleLists = node.ChildNodes;
List<string> rules = new List<string>();
foreach (XmlNode rule in stepRuleLists)
{
if (rule.Name == "Rule")
{
rules.Add(rule.InnerText);
}
}
if (!DicRules.ContainsKey(node.Attributes["name"].Value))
{
DicRules.Add(node.Attributes["name"].Value, rules);
}
}
}
catch (ArgumentException ex)
{
// Ignore the duplicate key.
MessageWindow.Show(MessageLevel.Warning, "There is configuration error in config file: " + SettingsPath);
}
catch (Exception ex)
{
var errMsg = string.Format("Errors occured while reading TreeNode setting from file [{0}].",
SettingsPath);
// Color list configuration failure does not affect functionality. Just show warnings.
// TODO: do localization for this message.
MessageWindow.Show(MessageLevel.Warning, "There is configuration error in config file: " + SettingsPath);
//Insert Exeption log
}
finally
{
xml = null;
}
}
}
}