Created
November 28, 2016 11:02
-
-
Save mvacha/5db21a3b64f4d03d5c1a894f48937646 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Newtonsoft.Json; | |
| using PipeGuard.Data.Code; | |
| using System; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| namespace PipeGuard.Data.Services | |
| { | |
| public class ConfigService | |
| { | |
| private class Config | |
| { | |
| public string ConnectionString { get; set; } | |
| public List<Unit> Units { get; set; } | |
| } | |
| private class Unit | |
| { | |
| public string Dev { get; set; } | |
| public int HwAddr { get; set; } | |
| } | |
| public string ConnectionString => _config.ConnectionString; | |
| public readonly Dictionary<string, int> UnitsByDev; | |
| private readonly Config _config; | |
| public ConfigService(string configPath) | |
| { | |
| var text = File.ReadAllText(configPath); | |
| var json = JsonConvert.DeserializeObject<Config>(text); | |
| Validate(json); | |
| UnitsByDev = json.Units.ToDictionary(u => u.Dev, u => u.HwAddr); | |
| _config = json; | |
| } | |
| private static void Validate(Config config) | |
| { | |
| if (string.IsNullOrEmpty(config.ConnectionString)) | |
| throw new ConfigException("Connection string is null or empty"); | |
| if (!config.Units.AreDistinct(d => d.Dev)) | |
| throw new ConfigException("Duplicite dev in unit array"); | |
| if (!config.Units.AreDistinct(d => d.HwAddr)) | |
| throw new ConfigException("Duplicite hwAddr in unit array"); | |
| if (config.Units.Any(d => string.IsNullOrEmpty(d.Dev))) | |
| throw new ConfigException("Dev is null or empty string"); | |
| if (config.Units.Any(d => d.HwAddr < 1)) | |
| throw new ConfigException("HwAddr is less than 1"); | |
| } | |
| } | |
| public class ConfigException : Exception | |
| { | |
| public ConfigException(string msg) : base(msg) | |
| { | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment