Use Windows Forms Application Settings to Personalize Your Applications

ne way to improve the usability of your application is to allow personalization?where different users of the same application have their own set of personalized settings. To do this, you need a way to store user-specific data, such as the size of the Window, the background color, etc. And while some data should be user-specific, some data applies across the board?things like database connection strings, Web services URLs, etc.

In Windows Forms 2.0, a new feature known as Application Settings provides a good solution to the personalization problem, by allowing you to maintain both user-specific and application-specific data (known as settings). This article takes you on a tour of this new feature and how you can implemented it in C#.

Creating the Sample Project
Using Visual Studio 2005, create a new C# Windows application and name it AppSettingsInCS. Right-click on the project name in Solution Explorer and select Properties. In the project designer page, click on the Settings tab.

Figure 1. Settings: Defining the three settings of different types.

User Scope
The first few settings you will create are of user scope. You will see what this means shortly. In the grid on the Settings page, first add the FormBackgroundColor setting and set its Type to System.Drawing.Color. For the Scope property, set it to User. You will notice that the default color is actually white (represented by the square box); you can change its value by selecting the drop down list. Figure 1 shows the other two settings (and their corresponding types, scope, and values) that you will create?FormSize and FormPosition. Remember that it’s important to initialize the settings with a default value. If not, accessing them during runtime will result in errors.

To see how these settings are used, add a Button control to the default Form1 (see Figure 2).

Double-click on the Button control to switch to its code-behind. For the Click event, code the following:

Figure 2. Add a Control: Adding a Button control to the form.

private void button1_Click(object sender, EventArgs e)        {            ColorDialog cd = new ColorDialog();            DialogResult result = cd.ShowDialog();            if (result == DialogResult.OK)            {                this.BackColor = cd.Color;                Properties.Settings.Default.FormBackgroundColor =                    this.BackColor;                Properties.Settings.Default.Save();            }        }

Essentially, when the user clicks on the button, it prompts a Color dialog window to let them choose a color (see Figure 3). After that, the background color of the form is changed to the selected color. At the same time, the selected color is also saved in the FormBackgroundColor setting. You access the settings through the Properties.Settings.Default class. Finally, remember to persist the application setting value using the Save() method.

When the form is resized, save its new size to the FormSize setting:

        private void Form1_Resize(object sender, EventArgs e)        {            Properties.Settings.Default.FormSize = this.Size;            Properties.Settings.Default.Save();        }

Finally, when the form is closed, save its new location to the FormPosition setting:

Figure 3. Display a Dialog: Displaying the Color dialog to allow users to select a color.

        private void Form1_FormClosed(           object sender, FormClosedEventArgs e)        {            Properties.Settings.Default.FormPosition = this.Location;            Properties.Settings.Default.Save();        }

When the form is loaded, you will retrieve the values from the settings and assign them to their respective properties:

        private void Form1_Load(object sender, EventArgs e)        {            this.BackColor =                Properties.Settings.Default.FormBackgroundColor;            this.Size = Properties.Settings.Default.FormSize;            this.Location = Properties.Settings.Default.FormPosition;        }

You can now press F5 to test the application. Click on the Button control to change the background color of the form. Then resize it and move the form to a new location on the form. Click the close (?x?) button of the form to close the application. When you press F5 to run the application again, you will realize that the form will now display the color you have selected previously and it will also retain its previous size and location.

What Just Happened?
Let’s examine the project a little closer to understand how the settings work. Figure 4 shows the three files in Solution Explorer that are used to maintain your application settings.

Figure 4. Maintain Your Settings: These three files can be found in Solution Explorer.

The Settings.settings file refers to the Settings page that you have been using to add the settings.

The app.config file is an XML File containing the details of your settings. See Listing 1 for the content of app.config.

Note the code in bold showing the settings that you have added earlier and their default values (they are all defined under the app.config file will be renamed .exe.config. In this example, the filename is AppSettingsInCS.exe.config. You can verify this in the binDebug (or binRelease) folder of your project.

For the Settings.Designer.cs file, it contains the data types of the various settings that you have defined. The definition for the FormBackgroundColor setting is shown below:

[global::System.Configuration.UserScopedSettingAttribute()]        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]        public global::System.Drawing.Color FormBackgroundColor {            get {                return ((global::System.Drawing.Color)                   (this["FormBackgroundColor"]));            }            set {                this["FormBackgroundColor"] = value;            }        }

During runtime, each individual user (of your computer) will maintain his/her own copy of the app.config file, which will be named user.config. This file can be found within the following directory:

C:Documents and SettingsLocal SettingsApplication Data

In my case, it is:

C:Documents and SettingsWei-Meng LeeLocal SettingsApplication DataAppSettingsInCS

Within this folder, you will find another folder, named something like:

AppSettingsInCS.vshost.ex_Url_dcjtbf3vhoeael5lvzjkefwbzccd3hbz

And within this folder, you will find a folder based on the version number of the application (in my case it is 1.0.0.0).

Here, you will find the user.config file:

                                        255, 255, 128                                        186, 241                                        1817, 330                        

As you can see, this file contains the values stored during runtime. As you change the color of the form, resize the form, or move the form, the updated values will be saved into this file. If you delete the user.config file, the application will revert to the default values found in AppSettingsInCS.exe.config.

Figure 5. The Settings Page: Adding the two new application-scope settings.

Application Scope
So far, you?ve been defining user-scope settings. Another scope you can use is Application scope. Unlike user-scope settings, which are used to store values specific to each individual users, application-scope settings are used for all users. A good example of how to use application-scope settings is to use them to store database connection strings.

To start, add two new settings to the grid in the Settings page (see Figure 5). The first connstr, is of type “(Connection string)” and it has Application scope (notice that the scope for a connection string can only be Application, not User). For its value, you can either type in the connection string, or click on the “?” button to bring up the dialog window to help you create the connection string. The second application setting?About, is of type string and also of Application scope.

Examine the app.config file (Listing 2), you will see that they are now added.

Interestingly, a connection string-type of setting is stored in its own section of the file (under the element). Other application-scope settings are stored under the element.

The definitions for the two application-scope settings are shown in Listing 3.

To see how these two application settings are used, add a second Button control to the form (see Figure 6).

Figure 6. Using the Application Settings: Add a second button to the form.

Double-click on the Button control to reveal its Click event handler and code (Listing 4).

As usual, access the connstr and About settings using the Properties.Settings.Default class.

For the connstr setting, you can also access it using the ConnectionStrings collection from the ConfigurationManager class (you need to add a reference to System.Configuration.dll):

   string connStr =      ConfigurationManager.ConnectionStrings[      "AppSettingsInCS.Properties.Settings.connstr"].ToString();

One important point to note is that application-scope settings are read-only during runtime, and can only be modified by an administrator once the application has been deployed. User-scoped settings, on the other hand, can be modified during runtime.

Adding Collections
The previous examples showed how to add settings of relatively simple types. One of the improvements in .NET 2.0 is the ability to add settings of complex types, such as adding a collection of strings. For example, suppose you want to store a collection of strings into a setting. Here’s how you can do it.

Add the MyItems setting. In the Type dropdown list, select Browse?

The Select a Type dialog will appear. Type the following in the textbox:

System.Collections.Specialized.StringCollection 

Then click OK. Next, click the ??? button on the Value field. Enter the strings collection and click OK.

The MyItems application settings will now be represented in the app.config file as follows:

        Item 1      Item 2      Item 3      Item 4      Item 5      

To access the string collections programmatically, use the following code snippet:

    foreach (string str in Properties.Settings.Default.MyItems)    {        Console.WriteLine(str);    }

Separating Application Settings
If you have a large number of application settings to add to your project, it is a good idea to store them separately in different files instead of storing them all in the default Settings.settings file. This also makes it easier to delete a related group of settings without affecting the others.

To add a settings file to your project, right-click on the project name in Solution Explorer and select Add | New Item?. Select the Settings File template and name it as, say, UI.Settings. Click Add.

The UI.settings file will now be added to your project. Double-click to open it. As usual, add an application setting. In this case, I have added a Title setting (see Figure 7).


Figure 7. The Title Setting: Defining a new setting.
?
Figure 8. The Properties Folder: Moving the settings file.

The next step is to move the UI.settings file to the Properties folder of the project (see Figure 8) so that you can access it programmatically under the Properties class.

You can now access the Title setting using the code:

this.Text = Properties.UI.Default.Title;

Note that all the settings from the different settings files are still stored in the same app.config file (design time). Also remember that, during runtime, all the application settings values are stored in the same user.config file.

vs.
In .NET 1.x, you can add application settings to your app.config file, like this:

         

So how does this differ from .NET 2.0? Well, the major advantage of the application settings feature in .NET 2.0 is that all the application settings are strongly typed, while those defined using the element are not. And this greatly improves on your code safety.

And in .NET 1.x, you use the ConfigurationSettings class to access the settings stored under the element:

using System.Configuration;...ConfigurationSettings.AppSettings.Get("FileName").ToString();
Figure 9. Warning Message: This alerts you to the obsolete ConfigurationSettings class.

While the ConfigurationSettings class is still supported in .NET 2.0, it is obsolete. You will get the warning message shown in Figure 9 if you use it in Visual Studio 2005.

The “System.Configuration!” indicates that you need to add a reference to the System.Configuration.dll library.

In .NET 2.0, use the ConfigurationManager class to access the setting, like this:

using System.Configuration;...ConfigurationManager.AppSettings.Get("FileName").ToString();

Improved Usability
Now you know how settings are created and used, and you should also have a good idea of the differences between application-scope and user-scope settings. Using settings to personalize your applications can really improve their usability, so it’s in your interest to make full use of them.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: