2.4. Use Strongly Typed Configuration Settings
Applications commonly need configuration settings to nail down details like file locations, database connection strings, and user preferences. Rather than hardcoding these settings (or inventing your own mechanism to store them), .NET lets you add them to an application-specific configuration file. This allows you to adjust values on a whim by editing a text file without recompiling your application.
Note: Use error-proof configuration settings by the application designer.
In Visual Studio 2005, configuration settings are even easier to use. That's because they're automatically compiled into a custom class that provides strongly typed access to them. That means you can retrieve settings using properties, with the help of IntelliSense, instead of relying on string-based lookups. Even better, .NET enhances this model with the ability to use updatable, user-specific settings to track preferences and other information. You'll see both of these techniques at work in this lab.
2.4.1. How do I do that?
Every custom configuration setting is defined with a unique string name. In previous versions of .NET, you could retrieve the value of a configuration setting by looking up the value by its string name in a collection. However, if you use the wrong name, you wouldn't realize your error until you run the code and it fails with a runtime exception.
In Visual Studio 2005, the story is much improved. To add a new configuration setting, double-click the My Project node in the Solution Explorer. This opens up the application designer where you can configure a host of application-related settings. Next, click the Settings tab, which shows a list of custom configuration settings where you can define new settings and their values.
To add a custom configuration setting to your application, enter a new setting name at the bottom of the list. Then specify the data type, scope, and the actual content of the setting. For example, to add a setting with a file path, you might use the name UserDataFilePath, the type String, the scope Application (you'll learn more about this shortly), and the value c:\MyFiles. Figure 2-3 shows this setting.
Figure 2-3. Defining a strongly typed application setting
Note: In a web application, configuration settings are placed in the web.config file. In other applications, application settings are recorded to a configuration file that takes the name of the application, plus the extension .config, as in MyApp.exe.config.
When you add the setting, Visual Studio .NET inserts the following information into the application configuration file:
<configuration> <!-- Other settings are defined here. --> <applicationSettings> <WindowsApplication1.MySettings> <setting name="UserDataFilePath" serializeAs="String"> <value>c:\MyFiles</value> </setting> </WindowsApplication1.MySettings> </applicationSettings> </configuration>
At the same time behind the scenes, Visual Studio compiles a class that includes information about your custom configuration setting. Then, you can access the setting by name anywhere in your code through the My.Settings object. For example, here's code that retrieves the setting named UserDataFilePath:
Dim path As String path = My.Settings.UserDataFilePath
In .NET 2.0, configuration settings don't need to be strings. You can also use other serializable data types, including integers, decimals, dates, and times (just choose the appropriate data type from the Types drop-down list). These data types are serialized to text in the configuration file, but you can retrieve them through My.Settings as their native data type, with no parsing required!
Note: The application settings class is added in the My Project directory and is named Settings.Designer.vb. To see it, select Project Show All Files.
2.4.2. What about...
...updating settings? The UserDataFilePath example uses an application-scoped setting, which can be read at runtime but can't be modified. If you need to change an application-scoped setting, you have to modify the configuration file by hand (or use the settings list in Visual Studio).
Your other choice is to create user-scoped settings. To do this, just choose User from the Scope drop-down list in the settings list. With a user-scoped setting, the value you set in Visual Studio is stored as the default in the configuration file in the application directory. However, when you change these settings, a new user.config file is created for the current user and saved in a user-specific directory (with a name in the form c:\Documents and Settings\[UserName]\Local Settings\Application Data\[ApplicationName]\[UniqueDirectory]).
The only trick pertaining to user-specific settings is that you must call My.Settings.Save( ) to store your changes. Otherwise, changes will only persist until the application is closed. Typically, you'll call My.Settings.Save( ) when your application ends.
To try out a user-scoped setting, change the scope of the UserDataFilePath setting from Application to User. Then, create a form that has a text box (named txtFilePath) and two buttons, one for retrieving the user data (cmdRefresh) and one for changing it (cmdUpdate). Here are the event handlers you'll use:
Private Sub cmdRefresh_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdRefresh.Click txtFilePath.Text = My.Settings.UserDataFilePath End Sub Private Sub cmdUpdate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdUpdate.Click My.Settings.UserDataFilePath = txtFilePath.Text End Sub
Finally, to make sure your changes are there the next time you run the application, tell .NET to create or update the user.config file when the form closes with this code:
Private Sub Form1_FormClosed(ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosedEventArgs) _ Handles Me.FormClosed My.Settings.Save( ) End Sub
This rounds out a simple test form. You can run this application and try alternately retrieving the current setting and storing a new one. If you're interested, you can then track down the user.config file that has the changed settings for the current user.