Effective C # Principle 37: Using the standard configuration mechanism

Source: Internet
Author: User

We're looking for an application configuration and information provisioning approach that avoids writing code directly, and we've created a number of different policies to store configuration information. And we're looking for the right way, and we're going to keep improving and changing our minds about where it's a good place to put this information. INI file? This is what Windows3.1 does, the configuration information is limited in structure and may also conflict with other programs on the file name. Registration form? Yes, that's the right idea, but it also has its limitations. A messy program might seriously damage a computer by writing some error message in the registry. Because of the danger of writing the registry, an application must have administrator privileges to write a portion of the registry. Will all of your users be running as an administrator with the right to modify the registry? Hopefully not, if you use the registry and your user is not running as an administrator, you will get an exception and error when you try to read and write to the registry.

Thankfully, there are many better ways to store settings information, so your program can adapt to different behaviors depending on the user's choice, such as installation parameters, machine settings, or anything else. NET Framework provides a standard setting location so that your program can use it to store configuration information. These storage locations are specifically specified by the application and can work as effectively when the user on the machine on which the program executes is restricted permissions.

The read-only information belongs to the configuration file, and the XML file controls the different types of behavior in the application; The defined structure table indicates all the elements and attributes that the. NET FCL from the configuration file. These elements control settings such as the version of the frame that is being used, the level of debugging supported (see principle 36), and the search path for the assembly. One of the nodes that you have to understand is the appsettings part, which can be applied simultaneously with both Web applications and desktop applications. The runtime reads the information for this node at startup, loading all the keywords and values into a collection of name values belonging to the application (NameValueCollection). This is part of your own program, and you can add any program-required values to control the behavior. When the configuration file is modified, the program behavior is also modified.

For use with configuration files, ASP. NET applications are a little more flexible than desktop applications. Each virtual directory can have its own profile, which is read sequentially by each virtual directory, and each virtual directory corresponds to a portion of the URL. The most local WINS. For example, this url:http://localhost/myapplication/subdir1/subdir2/file.aspx may be controlled by 4 different configuration files. Machine.config is first read, followed by web.config files in MyApplication, and then SubDir2 files in SubDir1 and web.config. Each of them can modify the value set by the previous profile, or add their own key/value pairs. You can configure the parameter selection of a global application through this configuration inheritance, and you can restrict access to some private resources. Web applications have different configurations in different virtual directories.

In a desktop application, there is only one application configuration file for each application domain ... NET runtime to load each executable file, create a default application domain for it, and then read an advance army-defined configuration file into this application domain. The default profile is in the same directory as the application is running, and is named with the < application name >.< extension >.config. For example, MyApp.exe might have a configuration file named MyApp.exe.config. The appsettings part can be used to create your own key/value pairs into the application.

A configuration file is the best place to store information about the behavior of a control program. But you may soon find that applications do not have APIs to write profile information. A configuration file is not a place to store any ordered settings. Don't rush to write the registration form and don't write it yourself. Here's a better way to configure your desktop application.

You may need to define the format of the configuration file and put the configuration file in the correct place. By defining some settings on the global settings and adding common read and Write properties, you can simply store and retrieve these settings:

[ Serializable( ) ]
public struct GlobalSettings
{
 // Add public properties to store.
}

XML serialization to store your settings:

XmlSerializer ser = new XmlSerializer(
 typeof( GlobalSettings ));
TextWriter wr = new StreamWriter( "data.xml" );
ser.Serialize( wr, myGlobalSettings );
wr.Close( );

Using XML format means that your settings can be easily read, easily parsed, and easily debugged. If necessary, you can encrypt and store these user settings. This is just an example of using XML serialization, not object persistence serialization (see Principle 25). XML serializes the storage file, not the entire object tree. Configuration settings and user settings generally do not include mesh objects, and XML serialization is a simple file format.

The final question is where the information should be stored. You should place the configuration information file in three different places. Choose which to use according to the configuration: Global, single user, or single user and single machine. These three locations can be obtained by invoking System.Environment.GetFolderPath (). You should add the application's detailed directory after the path returned by GetFolderPath (). Please be careful to fill out the information on all user or machine scope. Doing so is to get some privileges on the target machine.

Environment.SpecialFolder.CommonApplicationData returns the directory where the information is stored, which is shared by all users on the machine. If the default installation is used on a single machine, GetFolderPath (specialfolder.commonapplicationdata) returns C:\Documents and Settings\All Users\ Application Data. The settings stored in this directory should be used by all users on the machine. When you want to create information here, have the installer do it for you or in admin mode. You should not write some user-level here. The users level is a user group in Windows, and the rights are smaller than the administrator. ) Program data. By chance, your application may not have sufficient permissions on the user's computer to access it.

Environment.SpecialFolders.ApplicationData returns the path of the current user and is shared by all machines on the network. In the default installation, GetFolderPath (specialfolders.applicationdata) returns the C:\Documents and settings\< user name >\application Data. Each user has his or her own application Data directory. When a user logs on to a domain, this enumeration is used to access the shared network, and the user's global settings are included on the network. The data stored here is used only by the current user, regardless of which machine is logged on from the network.

Environment.SpecialFolders.LocalApplicationData returns a special directory that stores settings information and is also a user's private directory, which only belongs to users who log on from this machine. General GetFolderPath (Specialfolders.localapplicationdata) return: C:\Documents and settings\< user name >\local Settings\ Application Data

These three different locations allow you to store information about each person's settings, a given user's information, or a given user and a given machine. Which of the specific uses depends on the application. But consider some obvious examples: the database link string is a global setting and should exist in the generic application data (Common application) directory. The content of a user's work should exist in the application data (application) directory because it depends only on the user. The location information for the window should be in the local Application Data directory (application). Because they depend on the properties of the user on the machine (no machine may have different resolutions).

There should be a special directory that sets up storage for all users of all applications, describing the top-level directory structure. Here, you need to create subdirectories under the top-level directory structure. NET Framework's System.Windows.Application class defines properties that allow you to create generic configuration paths for you. The Application.localappdatapath property returns GetFolderPath (Specialfolders.commonapplicationdata) + \\CompanyName\\ Productname\\productversion "path. Similarly, Application.userdatapath and Application.localuserdatapath generate pathname in user data and local data directories, including companies, applications, and version numbers. If you combine these positions, you can create a configuration information for all applications in your own company, or for all versions of a program, or for a special version.

Notice that I have not mentioned the application directory in these directories, which is the directory under Program files. You should never write data in program files or in Windows directory and subdirectories. These directories have higher privileges, so you can't expect your users to have the right to write the data.

When storing the settings data for an application becomes an important issue, just as every enterprise user is concerned with the machine security concerns of a home user, putting the information in the right place means there is no compromise for users who use your application. You still have to give users a personal sense of how to combine the correct locations in the order of. NET, which makes it easy to give each user a sense of privacy without compromising security issues.

Back to the Tutorial directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.