-
Notifications
You must be signed in to change notification settings - Fork 1
Attribute usage examples
tparvi edited this page Sep 4, 2011
·
1 revision
Instead of reading and writing setting manually you can use the ReadFrom and WriteInto methods. Those methods read and write from public properties of your class.
public class MyApplicationSettings
{
/// <summary>
/// Basic case. Setting named StringValue is uesd for
/// this property and setting must exist.
/// </summary>
public string StringValue { get; set; }
}
In order to read the settings into the class above you would use the following code
settings = AppSettings.CreateForAssembly(Assembly.GetEntryAssembly(), FileOption.FileMustExist);
var mySettings = new MyApplicationSettings();
// Write all the settings into our own object
settings.WriteInto(mySettings);
mySettings.StringValue = "updated";
// Update the values from the our object and save
settings.ReadFrom(mySettings);
settings.Save();
If you want to control what is being read/write you can use the IgnorePropertyAttribute and SettingPropertyAttributes like in the example below
public class MyApplicationSettings
{
/// <summary>
/// Basic case. Setting named StringValue is used for
/// this property and setting must exist.
/// </summary>
public string StringValue { get; set; }
/// <summary>
/// Setting named DoubleValue is used for this property.
/// </summary>
[SettingProperty(SettingName = "DoubleValue")]
public double Double { get; private set; }
/// <summary>
/// Uses fi-FI culture to convert the value.
/// </summary>
[SettingProperty(SettingName = "DoubleWithFinnishLocale", CultureName = "fi-FI")]
public double LocalizedValue { get; private set; }
/// <summary>
/// This is just a property which we don't care when reading or
/// writing settings.
/// </summary>
[IgnoreProperty]
public string ValueWeDontCareAbout { get; private set; }
/// <summary>
/// This value might or might not exist. If it does not exist
/// then default value abc is used when reading configuration settings.
/// </summary>
[SettingProperty(IsOptional = true, DefaultValue = "A")]
public string OptionalSetting { get; private set; }
/// <summary>
/// Connection strings can be handled by specifying that the property
/// is actually ConnectionString.
/// </summary>
[SettingProperty(IsConnectionString = true, SettingName = "MyDatabase")]
public string ConnectionString { get; set; }
}
In the source code the Examples folder contains runnable example which demonstrates attribute usage.