Application Settings Made Easy with My and Visual Basic 2005

Published on: Author: Rob Windsor Leave a comment

Most applications require some configuration settings that could change over time. Classic examples would be a connection string to a database, the URL to your company web site, or the path to a log file. These settings could be stored in the application itself but this would mean that, should the setting change, the application would have to be modified, recompiled, and redeployed. A better approach would be to store the values of these settings in some external data store; traditionally this has been an INI file, a “plain” XML file, or the Windows registry.

When .NET was introduced it included built in support for configuration files which, amongst other things, could store application settings. To store settings you have to add specific XML tags and values into the configuration file so that associated classes in the Framework will be able to access them. For example, if you wanted to add a setting called AppBackColor you would include the following in your configuration file:

<configuration>
  <appSettings>
    <add key=”AppBackColor” value=”AntiqueWhite” />
  </appSettings>
</configuration>

You would then be able to access the setting using:

Imports System.Configuration
Private Sub Form1_Load(…) Handles MyBase.Load
    Dim backColor As String
    backColor = ConfigurationSettings.AppSettings(“AppBackColor”)
    Me.BackColor = Color.FromName(backColor)
End Sub

There are three main issues with this procedure. First, you need to know the format of XML that’s needed in the configuration file. Second, you access the individual settings by passing their name as a string to the AppSettings object. And third, the setting value comes back to you as a string.

This means you have three potential points of failure that will all rear their ugly heads at runtime. You could potentially put improperly formatted XML in the configuration file, you could type the name of the setting incorrectly when trying to access it, and you could give the setting an invalid value (in the example above that would be something that is not a know color to .NET).

In Visual Basic 2005 you have another option. Microsoft has added both Visual Studio designers and new .NET Framework classes to make management and use of settings much, much easier. To add a new setting or to change an existing one, open your project properties, select the Settings tab, and you will be presented with the settings editor grid (see Figure 1).

Settings Grid with an application setting

Figure 1 – Settings Grid with an application setting

Each setting now has four properties instead of just the two used previously. The Name and Value are there as before but now you also have a Type and a Scope. The Type property allows us to strongly type the setting, meaning that you cannot set an initial Value that is not of the correct type and when you use the setting in code you will not have to cast or convert it from a string. The final property is Scope which can be set to Application or User. Application scoped settings are read-only and serve the same function as settings in previous versions of Visual Basic while user scoped settings are specific to an individual user and can be modified in code. User scoped settings will be discussed later in this article.

The data you’ve entered in the settings grid is saved in the configuration file as before, it’s just done for us by the designer. You don’t have to know which tags are required and what their attributes are nor do you have to worry about spelling or capitalization mistakes. Entering the settings shown in Figure 1 will result in this being added to the configuration file:

<configuration>
  <!– other stuff not related to settings –>
  <applicationSettings>
    <SettingsDemo.My.MySettings>
      <setting name=”AppBackColor” serializeAs=”String”>
        <value>AntiqueWhite</value>
      </setting>
    </SettingsDemo.My.MySettings>
  </applicationSettings>
</configuration>

Now that the new setting has been configured, it can be used in your code. In this case you could use it to initialize the background color of the main form. The setting is accessed using the My namespace (which is a major addition to Visual Basic 2005) and is much cleaner than our previous example.

Private Sub Form1_Load(…) Handles MyBase.Load
    Me.BackColor = My.Settings.AppBackColor
End Sub

It’s important to note that AppBackColor has become a property of the Settings class. When your application starts, Visual Basic reads the settings from the configuration file and builds these properties dynamically. Because your setting is now a property you don’t have to worry about typing the name incorrectly (you’ll get a compiler error if you do) and you get the benefits of strong typing. That is the value of the AppBackColor property is a Color, not a string that needs to be converted to a Color.

You can see that these new features address the issues found in the older settings architecture and greatly ease the process of managing and using application settings. But wait, there’s more! There’s still user scoped settings to cover.

Designer and .NET Framework support for user scoped settings, or per-user settings, is wholly new to Visual Basic 2005 (For information on how to accomplish this in previous versions of Visual Basic.NET, see Rocky Lhotka’s article entitled Storing User Configurations which can be found at http://shrinkster.com/c3x). User settings are used in much the same way as application settings but the effect is quite different.

You add a user setting in exactly the same way as an application setting but you set the Scope to User. Figure 2 shows a user setting called UserFont with an initial value of Microsoft Sans Serif, 8.25pt.

Settings Grid with an application and a user setting

Figure 2 – Settings Grid with an application and a user setting

This new setting will update the configuration file to look like this:

<configuration>
  <!– other stuff not related to settings –>
  <userSettings>
    <SettingsDemo.My.MySettings>
      <setting name=”UserFont” serializeAs=”String”>
        <value>Microsoft Sans Serif, 8.25pt</value>
      </setting>
    </SettingsDemo.My.MySettings>
  </userSettings>
  <applicationSettings>
    <SettingsDemo.My.MySettings>
      <setting name=”AppBackColor” serializeAs=”String”>
        <value>AntiqueWhite</value>
      </setting>
    </SettingsDemo.My.MySettings>
  </applicationSettings>
</configuration>

And, as before, the new setting can now be used in code.

Private Sub Form1_Load(…) Handles MyBase.Load
    Me.BackColor = My.Settings.AppBackColor
    Me.Font = My.Settings.UserFont
End Sub

This, however, is where the similarities end. As mentioned previously, user settings are specific to a user and can be modified at runtime. So what happens when you change a setting for a user? Let’s assume you have a menu option that lets the user change the font for the main form of our application. If the user does change the font, you’ll likely want to save their choice so that you can restore it the next time the application runs. To do this you will use the UserFont setting.

When the application closes you will set UserFont to the font of the main form and then save the setting.

Private Sub Form1_FormClosed(…) Handles Me.FormClosed
    My.Settings.UserFont = Me.Font
    My.Settings.Save()
End Sub

When you do this a user specific configuration file called user.config will be created in a folder under the Documents and Settings for the person currently logged in to Windows. This file will store the setting data specific to that user.

Nice? It gets even better. You can actually achieve the same result without any code. The Windows Forms designer supports binding user settings to properties of forms or controls. For example, you could bind the UserFont setting to the Font property of our application’s main form (Form1). In the Properties Window for Form1 find (ApplicationSettings) and expand it. Then select (PropertyBinding) and click the button with the ellipses to open the binding editor form (see Figure 3). Finally, select the Font property, click the dropdown, and select UserFont from the list.

Binding a user setting to a property

Figure 3 – Binding a user setting to a property

With this done you no longer need to set the Font property in the Form’s Load event and you don’t need to set UserFont in the FornClosed event either. The data binding handles this for us.

The last thing to mention is the call to My.Settings.Save which you saw in the FormClosed event. This actually wasn’t necessary, it was added it for completeness. If you look in the Application tab of your Project Properties you’ll see a CheckBox with the caption “Save My.Settings on Shutdown” (see Figure 4). If this is checked (and it is by default) then Visual Basic will automatically save user settings just before the application terminates. The combination of this option and the visual tools to bind settings to form and control properties give you a no-code solution for implementing user settings.

Enabling the automatic saving if user settings

Figure 4 – Enabling the automatic saving if user settings.

As you’ve seen, the addition of My to Visual Basic 2005, new classes to the .NET Framework 2.0 and new designers to Visual Studio 2005 vastly improves our ability to manage and use application and user specific settings in our applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>