November 1, 2012

Settings in .NET are easy

As I said 'few' days ago, today I`ll tell you about Settings files.
Settings files are designed to make our life simpler during working with application and user configuration.

A bit theory

Settings file consists of few parts in our project.
  1. Settings file (auto generated class derived from ApplicationSettingsBase).
  2. app.config (contains default values for all options).
Generated setting file derived from ApplcationSettingsBase already contains initialized static instances of all our options. We don't need to create this class manually and load any data, because it has already been created and loaded. And it is ready to work.

All settings have next properties:
  • Name (this is the name of our setting): with this name we will have automatically generated property in Settings class.
  • Type (the type of our setting): there are a lot of predefined types like string, int, etc., but you can also set your custom type.
  • Value (this is default value for setting).
  • Scope: all settings should be in one of two scopes (User or Application). It represents how our setting will be accessed at runtime.

User Scope - options in this scope belong to a user, we can read\write these options in runtime. Values for each property will be stored in user.config file in Local AppData folder for a current user.

Application Scope - options in this scope belong to application and we can only read these options. Values are always read from app.config.

Getting started with Settings

How to add settings files to your project:
By default every WindowsForms project already contains an empty Settings file. 

Settings file has a very nice UI designer in Visual Studio. Designer allows us to add\edit\remove any options. After editing options appropriate settings class will be automatically regenerated with new changes. But I prefer clicking Synchronize button for sure that settings class is really regenerated.

This is how designer looks like (I've already added few options):
This is how generated settings class looks like:
Default values in app.config:
As you can see we have 3 options: UserName, UserPassword and PathToLib.
PathToLib is in Application scope and is generated like read-only property in settings class.

How we can use settings in code:
public class Program
    public static void Main(string[] args)
            "User name: {0}, password: {1}"
            , CustomSettings.Default.UserName
            , CustomSettings.Default.UserPassword);
        //output: User name: defualtUser, password: 123

            "Path to application library: {0}"
            , CustomSettings.Default.PathToLib);
        //output: Path to application library: D:\Lib

Managing options in code
There are few useful methods in settings class which allow us to load default\save changes only by one line of code:
  • Save() - stores the current values of the application settings properties.
  • Reload() - refreshes the application settings property values from persistent storage.
  • Reset() - restore the application settings values to their corresponding default properties.

See the example of all these method usages:
public class Program
    public static void Main(string[] args)
        Console.WriteLine("User: {0}" , CustomSettings.Default.UserName);
        //output: User: defualtUser

        CustomSettings.Default.UserName = "newUser";
        Console.WriteLine("User: {0}" , CustomSettings.Default.UserName);
        //output: User: newUser

        CustomSettings.Default.UserName = "badUser";
        Console.WriteLine("User: {0}", CustomSettings.Default.UserName);
        //output: User: newUser

        CustomSettings.Default.UserName = "badUser";
        Console.WriteLine("User: {0}", CustomSettings.Default.UserName);
        //output: User: defaultUser

When we change settings values and call Save() method, after some 'magic', .NET will create user.config file with new values.
In my situation I find this file in:
c:\Users\<current user>\AppData\Local\TestConsoleApplication\TestConsoleApplication.ex_Url_0pb1j4w12xaui1md5tuq0dev0d2olihj\\user.config
*but in this file there are values that are only in user-scope. All application-scope values will get from app.config.
Manual app.config editing
As you already know that user-scope values are stored in user.config file (in user AppData folder) and aplication-scope values are stored in app.config.
If you will manually change default values in app.config (for example by ConfigurationManager class in code or by notepad) after we will get setting value we will get next results depends on setting scope:
  • If settings is in user-scope then in code we don't get our new edited values (from app.config) because we already have values in user.config. But after we call Reset() method we will get new defaults from app.config.
  • If settings is in application-scope we will get new values from app.conig.
The main idea of loading user-scope settigns is - if we have value in user.config we get it otherwise we get default value from app.config.

We can use Settings file not only in Windows Forms. Settings file is one of the easiest ways to manage application and user options. Visual Studio has a very powerful UI designer that decreases development time to minimum during options management.
As for me, I use Settings files always when I need to use options in my application. It allows me to write less code and this is very good, because less code is always good :)




No comments: