Set the value of a specific property to a custom attribute

I am currently developing software that will be used by users who should not have access to internal content, but should still be able to easily change the configuration / settings of the application. I decided that the best approach would be a custom โ€œconfiguration file (.cfg)โ€ located at the root of the final build. A simple example .cfg file:

serveraddress='10.10.10.10'
serverport='1234'
servertimeout='15000'

Since I wanted the configuration file to be easily extensible, I decided to use some custom attributes and some simple LINQ. This works the way I expect, but since I'm still new to .net, I'm afraid that I did not go with the best approach, and my question is this: Can I do something to improve this? Or, as a rule, is better suited for this?

This is my code for reading the configuration file and assigning corresponding properties to it.

ConfigFileHandler.cs

public void ReadConfigFile()
    {
        var cfgFile = new ConfigFile();
        var configLines = File.ReadAllLines("configfile.cfg");
        var testList = configLines.Select(line => line.Split('='))
            .Select(splitString => new Tuple<string, string>(splitString[0], splitString[1].Replace("'", "")))
            .ToList();
        foreach (var prop in typeof(ConfigFile).GetProperties())
        {
            var attrs = (ConfigFileFieldAttribute[])prop.GetCustomAttributes
                (typeof(ConfigFileFieldAttribute), false);
            foreach (var t in from attr in attrs from t in testList where t.Item1 == attr.Name select t)
            {
                prop.SetValue(cfgFile, t.Item2);
            }
        }
    }

ConfigFile.cs

 class ConfigFile
    {
        private static string _serverAddress;
        private static int _serverPort;
        private static int _serverTimeout;

        [ConfigFileField(@"serveraddress")]
        public string ServerAddress
        {
            get { return _serverAddress; }
            set { _serverAddress= value; }
        }

        [ConfigFileField(@"serverport")]
        public string ServerPort
        {
            get { return _serverPort.ToString(); }
            set { _serverPort= int.Parse(value); }
        }

        [ConfigFileField(@"servertimeout")]
        public string ServerTimeout
        {
            get { return _serverTimeout.ToString(); }
            set { _serverTimeout= int.Parse(value); }
        }
    }

any tips for writing code look better!


UPDATE: Thanks for the feedback.

Below are the final classes! https://dotnetfiddle.net/bPMnJA for a live example

Please note that this is C # 6.0

ConfigFileHandler.cs

 public class ConfigFileHandler
 {
    public void ReadConfigFile()
    {
        var configLines = File.ReadAllLines("configfile.cfg");
        var configDictionary = configLines.Select(line => line.Split('='))
        .Select(splitString => new Tuple<string, string>(splitString[0],     splitString[1].Replace("'", "")))
        .ToDictionary(kvp => kvp.Item1, kvp => kvp.Item2);
        ConfigFile.SetDictionary(configDictionary);
    }
 }

ConfigFile.cs

 public class ConfigFile
 {
    private static Dictionary<string, string> _configDictionary;

    public string ServerAddress => PullValueFromConfig<string>("serveraddress", "10.1.1.10");

    public int ServerPort => PullValueFromConfig<int>("serverport", "3306");

    public long ServerTimeout => PullValueFromConfig<long>("servertimeout", "");


    private static T PullValueFromConfig<T>(string key, string defaultValue)
    {
        string value;
        if (_configDictionary.TryGetValue(key, out value) && value.Length > 0)
            return (T) Convert.ChangeType(value, typeof (T));
        return (T) Convert.ChangeType(defaultValue, typeof (T));

    }

    public static void SetDictionary(Dictionary<string, string> configValues)
    {
        _configDictionary = configValues;
    }
 }
+4
3

, ConfigFile.

    public static void ReadConfigFile()
    {
        var configLines = File.ReadAllLines("configfile.cfg");
        var testList = configLines.Select(line => line.Split('='))
            .Select(splitString => new Tuple<string, string>(splitString[0], splitString[1].Replace("'", "")))
            .ToDictionary(kvp => kvp.Item1, kvp => kvp.Item2);

        var cfgFile = new ConfigFile(testList);
    }

ConfigFile:

class ConfigFile
{
    private Dictionary<string, string> _configDictionary;

    public ConfigFile(Dictionary<string, string> configValues)
    {
        _configDictionary = configValues;
    }

    public string ServerAddress
    {
        get { return PullValueFromConfig("serveraddress", "192.168.1.1"); }
    }

    public string ServerPort
    {
        get { return PullValueFromConfig("serverport", "80"); }
    }

    public string ServerTimeout
    {
        get { return PullValueFromConfig("servertimeout", "900"); }
    }

    private string PullValueFromConfig(string key, string defaultValue)
    {
            string value;
            if (_configDictionary.TryGetValue(key, out value))
                return value;
            return defaultValue;
    }
}
+3

" (.cfg)", .

. JSON JSON.NET - / ConfigFile. , .

ConfigFile JSON.NET -.

public class ConfigFile
{
    private readonly static string path = "somePath.json";
    public string ServerAddress { get; set; }
    public string ServerPort { get; set; }
    public string ServerTimeout { get; set; }
    public void Save()
    {
        var json = JsonConvert.SerializeObject(this, Formatting.Indented);
        File.WriteAllText(path, json) 
    }
    public static ConfigFile Load()
    {
        var json = File.ReadAllText(path); 
        return JsonConvert.DeserializeObject<ConfigFile>(json);
    }
}

, .

ConfigFile f = ConfigFile.Load();
f.ServerAddress = "0.0.0.0";
f.ServerPort = "8080";
f.ServerTimeout = "400";
f.Save();

.json . .cfg, . :

{
    "ServerAddress":"0.0.0.0",
    "ServerPort":"8080",
    "ServerTimeout":"400"
}

" ". , . .

+1

-, , , .

var configLines = File.ReadAllLines("configfile.cfg");
var testDict = configLines.Select(line => line.Split('=', 2))
                          .ToDictionary(s => s[0], s => s[1].Replace("'", ""));

LINQ:

foreach (var prop in typeof(ConfigFile).GetProperties())
{
    var attr = prop.GetCustomAttributes(false)
                   .OfType<ConfigFileFieldAttribute>()
                   .FirstOrDefault();
    string val;
    if (attr != null && testDict.TryGetValue(attr.Name, out val))
        prop.SetValue(cfgFile, val);
}

:

var attr = prop.GetCustomAttributes<ConfigFileFieldAttribute>(false).FirstOrDefault();

IDE,

+1

Source: https://habr.com/ru/post/1584594/


All Articles