Cogwheel (formerly Tyrrrz.Settings) is a simple library for storing and retrieving settings in desktop applications.
It serves as a replacement for the built-in System.Configuration.SettingsBase
class, and offers more customization and flexibility.
By using this project or its source code, for any purpose and in any shape or form, you grant your implicit agreement to all the following statements:
To learn more about the war and how you can help, click here. Glory to Ukraine! πΊπ¦
dotnet add package Cogwheel
To define your own application settings, create a class that inherits from SettingsBase
:
using Cogwheel;
public class MySettings() : SettingsBase("path/to/settings.json")
{
public string StringSetting { get; set; } = "foo";
public int IntSetting { get; set; } = 42;
}
Using an instance of this class, you can load, modify, and save settings:
var settings = new MySettings();
settings.Load();
settings.StringSetting = "bar";
settings.IntSetting = 1337;
settings.Save();
You can also restore settings to their default values:
var settings = new MySettings();
settings.StringSetting = "bar";
settings.IntSetting = 1337;
settings.Reset();
// settings.StringSetting == "foo"
// settings.IntSetting == 42
Under the hood, Cogwheel uses System.Text.Json
to serialize and deserialize settings.
You can use various attributes defined in that namespace to customize the serialization behavior:
using Cogwheel;
using System.Text.Json.Serialization;
public class MySettings() : SettingsBase("path/to/settings.json")
{
[JsonPropertyName("string_setting")]
public string StringSetting { get; set; } = "foo";
[JsonIgnore]
public int IntSetting { get; set; } = 42;
}
You can also provide a custom JsonSerializerOptions
instance to further customize the serialization process:
using Cogwheel;
using System.Text.Json;
public class MySettings() : SettingsBase(
"path/to/settings.json",
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }
)
{
public string StringSetting { get; set; } = "foo";
public int IntSetting { get; set; } = 42;
}
If you want to use compile-time serialization as opposed to relying on reflection, you need to provide a valid IJsonTypeInfoResolver
instance.
You can provide it either directly or as part of a JsonSerializerOptions
instance:
using Cogwheel;
using System.Text.Json.Serialization;
public class MySettings() : SettingsBase(
"path/to/settings.json",
MyJsonSerializerContext.Default
// Or:
// new JsonSerializationOptions { TypeInfoResolver = MyJsonSerializerContext.Default }
)
{
public string StringSetting { get; set; } = "foo";
public int IntSetting { get; set; } = 42;
}
// Define a custom JSON serialization context for auto-generated code
[JsonSerializable(typeof(MySettings))]
internal partial class MyJsonSerializerContext : JsonSerializerContext;
Note: To learn more about compile-time serialization in
System.Text.Json
, see the official documentation.