aloneguid / config

⚙ Config.Net - the easiest configuration framework for .NET developers. No BS.
MIT License
641 stars 85 forks source link

Create default config file at engine/software start #83

Closed berge2007 closed 4 years ago

berge2007 commented 5 years ago

Hello,

Is there any way to trigger Config.NET engine to save all the properties into INI/JSON/etc. config file if the config file doesn't exist at software start?

Other words, create a "default" config file when config file doesn't exist at program start.

sobotkami commented 5 years ago

Not sure if it's the right way for you or the right way with this library, but there is one possible way:

public static TSettings GetSettings<TSettings>(string path) where TSettings : class
{
    var settings = new ConfigurationBuilder<ISettings>()
        .UseJsonFile(path)
        .Build();

    if (!File.Exists(path))
        Log.Logger.Warning("There is no file {path} - a new one will be created", path);

    // TODO simple interface run, but if you have interface as a typ of the variable, its broken
    WriteDefaultSettings(settings);

    return settings;
}

public static void WriteDefaultSettings(object obj)
{
    foreach (var prop in obj.GetType().GetProperties())
        if (IsSimpleOrSettable(prop.PropertyType))
            prop.SetValue(obj, prop.GetValue(obj));
        else
            WriteDefaultSettings(prop.GetValue(obj));
}

public static bool IsSimpleOrSettable(Type type)
{
    return type.IsPrimitive
           || type == typeof(string)
           || type == typeof(NetworkCredential);
}
aloneguid commented 5 years ago

It's a possible workaround, however I'm not sure this will create keys at all as default behaviour for stores is to delete the key from destination if it has default value in order to save space. We probably need an overload somewhere which forces store implementations to create empty keys with default values.