Working with Windows Forms Configuration Files in .NET 2.0 and Visual Studio 2005

Working with Windows Forms Configuration Files in .NET 2.0 and Visual Studio 2005

mong the many new features in the forthcoming .NET 2.0 are the revamped System.Configuration namespace and the Visual Studio 2005 configuration editor. The new classes raise configuration for both desktop and Web applications to a new level of sophistication compared to prior implementations. The sheer size of the changes could fill a small reference text, so this article focuses on a very simple desktop application whose only purpose is to display and modify content from its own configuration file. To run the sample application you need to download the Visual Studio 2005 public beta. I used the February 2005 Professional Edition for all the screenshots and code builds.

Some New Features
Two of the most important new configuration file features are strong data typing for type safety and a separate and editable scope for user settings.

Type Safety
The previous version of the .NET Framework only allowed for string settings. This could create problems when reading settings directly into non-string variables, as seen in the code fragment below:

   int maxConnections =       ApplicationSettings.AppSettings.Key      ["MaxConnections"];

If the configuration content wasn’t a string, but instead represented some other data type, such as a Boolean, integer, or more complex data type, you had to write custom code to cast the string value or create and populate the appropriate object. In contrast, the new API has specific classes that handle all the basic data types and interfaces for implementing custom serializers. In addition the framework has built-in handlers for some of the more commonly used programmatic constructs such as data source connection strings and URLs.

Scopes
The new API delineates separate application and user settings using a concept called scopes. You use the Application scope for settings specific to the application such as connection strings and other values that drive the application itself, and are not prone to change. The User scope is for storing user-configurable application values such as the last screen position and the most recently used documents. Most importantly, the User scope stores default values for each setting. When the user changes these default values by using the application, the configuration file stores these updated values in a separate location. This is important because it protects the integrity of the application’s configuration file and keeps user-specific data with the user’s system profile. The configuration framework loads user-specific settings automatically in the background without any additional developer effort.

The ThisConfigEditor Application
The downloadable code for the sample application presented here, ThisConfigEditor (see Figure 1), is a simple tool that displays settings from its own configuration file. While simplistic, this application serves as an excellent jumping off point for the needs of most applications.

Visual Studio generates most of the files in this project automatically (see Figure 2).

?
Figure 1. The Sample Configuration Editor: This tool displays settings from the sample project’s configuration file.
?
Figure 2. Project Files: The figure shows the files generated by Visual Studio for the sample project, with the added “ThisConfigEditor.cs” file.

The only file that needs direct work in a code editor is the ThisConfigEditor.cs file. This application does not require any special assembly manifest or resources and all the configuration settings are handled by Visual Studio’s new Properties Editor. When Visual Studio creates a new project it automatically generates a Properties folder and populates it with classes that wrap the configuration settings you generate with the Properties Editor. The Properties Editor updates the app.config file and the Settings.cs class file (the class wrapper around the generated properties) automatically, so you don’t need to work with either of these files manually; in fact, you should only do so after you have a thorough understanding of the underpinnings of the new configuration file markup. You can find a full explanation for the configuration file markup tags at Microsoft’s MSDN site.

?
Figure 3. The Properties Editor: You reach the configuration (settings) editor by double-clicking on the “Settings.settings” entry in the Solution Explorer.

The Property Editor
Double clicking on the “Settings.settings” entry in the Solution Explorer launches the Properties Editor.

Figure 3 shows two configuration properties created for demonstration purposes; FilesDirectory and Connection. The Properties Editor grid lets you specify the name, the datatype, the scope (by default there are only two scopes: User and Application) and the value. The most interesting property here is the Connection setting. Selecting (Connection string) from the Type dropdown launches a series of dialogs (though interestingly enough not a wizard) for creating the connection string (shown in Figure 4 and Figure 5).

?
Figure 4. Choosing a Data Source: When you select the connection string setting type from the Type dropdown, Visual Studio launches a series of dialogs for defining the connection properties.
?
Figure 5. The Connection Properties Dialog: This standard connection properties dialog appears after you select a connection string type.

What Gets Generated?
All this work in the Properties Editor generates configuration settings and a great deal of code automatically. While it is beyond the scope of this article to dig into the content in detail, it is useful to take a look. If you open the app.config file in the downloadable code that accompanies this article, you can see what Visual Studio creates as the ThisConfigEditor.exe.config file when you build the project. Even more interesting is the Settings.Designer.cs source (available in the downloadable code). This class provides easy and direct access to each setting by name in a namespace subordinate to the application’s main namespace, in this case, Example.Properties, in a class called Settings. Notice that the properties relate to each configuration setting. An attribute decorating each property defines the scope in which the property resides and its default value. Because the Settings class inherits from the ApplicationSettingsBase class (a new collection class in the System.Configuration API), you can access the properties directly by name or you can enumerate all the configuration settings, which is what the ThisConfigEditor example does.

Enumerating Configuration Properties
The heart of the ThisConfigEditor’s display is the private PopulateListView method in the ThisConfigEditor.cs code file.

   private void PopulateListView()   {      ListViewItem item = null;         this.buttonUpdateSetting.Enabled = false;      this.textBoxSettingValue.Enabled = false;      this.listViewSettings.Items.Clear();         Properties.Settings settings =          Properties.Settings.Default;         foreach (SettingsProperty property in          settings.Properties)      {         bool match = false;            switch (_dt)         {            case DisplayType.All:               match = true;               break;               case DisplayType.Application:               foreach (System.Collections.DictionaryEntry                  attribute in property.Attributes)               {                  if (attribute.Value is                     System.Configuration.                    ApplicationScopedSettingAttribute)                  {                     match = true;                     break;                  }               }               break;               case DisplayType.User:               foreach (System.Collections.DictionaryEntry                  attribute in property.Attributes)               {                  if (attribute.Value is                     System.Configuration.                    UserScopedSettingAttribute)                  {                     match = true;                     break;                  }               }               break;         }            if (match)         {            item = new ListViewItem(property.Name);            item.SubItems.Add(new               ListViewItem.ListViewSubItem(item,               property.PropertyType.ToString()));            item.SubItems.Add(new               ListViewItem.ListViewSubItem(item,               settings[item.Text] as string));            item.Tag = property;            this.listViewSettings.Items.Add(item);         }      }   }

Switching the private enum field _dt (which relates to the selection in the form’s combo box determining which configuration properties to display: All, Application, or User) the code enumerates through the configuration properties. Each member of the collection is a SettingProperty instance (another new class in the System.Configuration API representing an individual configuration property) which in turn contains a collection of DictionaryEntry instances representing their various attributes. By iterating over this collection of attributes the code searches for matches to the appropriate scope-designating attribute to reflect the selection made in the combo box. After making a match, the code displays the configuration property by creating a new ListViewItem and adding it to the ListView on the form.

Author’s Note: The ponderous nature of this method reflects certain instabilities in the current .NET beta 1 as much as a desire for readability.

Where Does It All Go?
So, after skimming over the code and running the application you can see the various configuration settings in the ThisConfigEditor.exe.config file. To understand what the configuration framework does, it’s worth exploring what happens when you change a User scoped setting (see Figure 6).

?
Figure 6. Changing the User Scoped Setting: The figure shows the process of changing a setting in the ThisConfigEditor sample application.

The changed setting isn’t saved into the application’s configuration file; instead, the API creates a new directory for the application (if it doesn’t already exist) in the user’s profile where it adds a file called user.config (see Figure 7).

Separating the data by scope in this manner protects the integrity of the applications configuration file by keeping user-specific data with the user. Again, the .NET framework automatically loads user-specific content without requiring any intervention from developers. Notice that the last subdirectory corresponds to the version number of the application. This ensures that successive versions of the application will maintain their individual integrity and not interfere with each other if a property’s datatype changes.

Author’s Note: Be mindful of your application’s version stamp because any changes (such as auto-incrementing build numbers) will cause the framework to create a new directory with new User-scoped settings?the values won’t carry over from previous versions. This is undoubtedly behavior that testers as well as developers should be aware of.
?
Figure 7. The New User Configuration File: The figure shows where the .NET framework saves the user’s configuration file for the sample application.

Compact Framework Gets Short Shrift?Again
The Compact Framework implementation on the Pocket PC sometimes seems to be the unwanted stepchild of the .NET world. Its 1.0 implementation made no provision for the System.Configuration namespace or the registry. The beta documentation for 2.0 flags the Compact Framework for each of the class entries in the System.Configuration namespace, as it does for numerous of the classes in all the namespaces in the beta documentation, but the currently available bits do not support this.

One can only hope that this is merely a passing condition during the development phase of the new .NET platform, and that the release version will support the same configuration capabilities as the desktop version.

devx-admin

devx-admin

Share the Post:
Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations.

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI,

Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency tokens have seen a substantial

GlobalFoundries Titan

GlobalFoundries: Semiconductor Industry Titan

GlobalFoundries, a company that might not be a household name but has managed to make enormous strides in its relatively short 14-year history. As the third-largest semiconductor foundry in the

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security in the sector remains strong.

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations. However, the United States’ stance

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are now contemplating constructing domestic manufacturing

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI, ChatGPT is known for its

Future of Cybersecurity

Cybersecurity Battles: Lapsus$ Era Unfolds

In 2023, the cybersecurity field faces significant challenges due to the continuous transformation of threats and the increasing abilities of hackers. A prime example of this is the group of

Apple's AI Future

Inside Apple’s AI Expansion Plans

Rather than following the widespread pattern of job cuts in the tech sector, Apple’s CEO Tim Cook disclosed plans to increase the company’s UK workforce. The main area of focus

AI Finance

AI Stocks to Watch

As investor interest in artificial intelligence (AI) grows, many companies are highlighting their AI product plans. However, discovering AI stocks that already generate revenue from generative AI, such as OpenAI,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its