Objective C # Principle 37: using standard configuration mechanisms)

Source: Internet
Author: User
Tags configuration settings net serialization

Proactive C # Principle 37: using standard configuration mechanisms
Item 37: use the standard configuration Mechanism

We need to find a way to avoid writing directly.CodeApplicationProgramConfiguration and information setting methods, we have created a variety of different policies to store configuration information. While we are looking for a correct method, we need to constantly improve and change our ideas about where to place such information. INI file? This is what windows3.1 does. The structure of configuration information is restricted, and the file name may conflict with other programs. Registry? Yes, it is the correct idea, but it also has its limitations. Messy programs may severely damage computers by writing some error messages in the registry. Because it is dangerous to write a registry, an application must have the administrator privilege to write a portion of the Registry. Are all your users running as administrators who have the right to modify the registry? Hopefully no. If you use the registry and your users are not running as administrators, an exception or error will occur when you try to read and write the registry.

Thank God, there are still many better ways to store setup information, so that your program can adapt to different behaviors, 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 designated by the application, and can work only when the user on the machine where the program is executed is limited by the permission.

The read-only information belongs to the configuration file. The XML file controls different types of behaviors in the application. The defined structure table specifies all elements and attributes, all of which are.. Net FCL is analyzed from the configuration file. These elements control some settings, such as the Framework version being used, the supported debugging levels (see principle 36), and the search path of the Assembly. There is a node you must understand, that is, the appsettings part, which can be applied to both web applications and desktop applications. The running program reads the information of this node at startup. It loads all the keywords and values to a namevaluecollection that belongs to the application. This is part of your own program. You can add values required by any program to control program behavior. When the configuration file is modified, the program behavior is modified.

For configuration files, ASP. NET applications are slightly more flexible than desktop applications. Each virtual directory can have its own configuration file, which is read by each virtual directory in sequence, and each virtual directory corresponds to a part of a URL. The most local wins. For example, the URL: http: // localhost/myapplication/subdir1/subdir2/file. aspx may be controlled by four different configuration files. Machine. config is first read, followed by the web. config file in myapplication, followed by the web. config file in subdir1 and subdir2. Each of them can modify the values set in the previous configuration file or add their own key/value pairs. You can configure parameter selection for a global application using this configuration Inheritance Method, and 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 .. When the net runtime loads each executable file, it creates a default application domain for it, and then reads a pre-defined configuration file to this application domain. The default configuration file is in the same directory as when the application is running, and is named after <Application name>. <extension>. config. For example, myapp.execan have a configuration file named myapp.exe. config. The deleetaskpart can be used to create your own key/value pairs in the application.

Configuration files are the best place to store information that controls program behavior. However, you may soon find that the application does not have an API to write configuration file information. The configuration file is not used to store any ordered settings. Do not rush to write the registry, or write it yourself. There is a better way for you to configure the desktop application.

You may need to define the configuration file format and put the configuration file in the correct place. By defining some configuration structures and adding public read/write attributes in global settings, you can easily 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, parsed, and debugged. If necessary, you can encrypt and store these user settings. This is just an example of using XML serialization, not object persistent serialization (see Principle 25 ). The XML serialized storage file is not the entire object tree. Configuration settings and user settings generally do not contain mesh objects, and XML serialization is a simple file format.

The last question is where to store the information. You should place the configuration information file in three different places. Which one should be selected based on the configuration usage: Global, single user, or single user and single machine. These three locations can be obtained by calling system. environment. getfolderpath. You should add the detailed directory of the application after the path returned by getfolderpath. Be extremely careful when entering information across all users or machines. In doing so, we need to gain some privileges on the target machine.

Environment. specialfolder. commonapplicationdata returns the directory for storing information, which is shared by all users on the machine. If the default installation is used on a machine, getfolderpath (specialfolder. commonapplicationdata) returns c: \ Documents ents 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, let the installer do it for you or in administrator mode. Users should not be written here .) Program Data. By chance, your application may not have sufficient permissions to access it on the user's machine.

Environment. specialfolders. applicationdata returns the path of the current user, which is shared by all machines on the network. In the default installation, getfolderpath (specialfolders. applicationdata) returns c: \ Documents and Settings \ <username> \ Application Data. Each user has his/her own application data directory. When a user logs on to a domain, the list is used to enter the shared network, and the network contains the global settings of the user. The data stored here is only used by the current user, no matter which machine on the network is logged on.

Environment. specialfolders. localapplicationdata returns a special directory, which is a private directory of the user except for the storage settings. It only belongs to the user logging on from this machine. Generally, getfolderpath (specialfolders. localapplicationdata) returns: C: \ Documents and Settings \ <username> \ Local Settings \ Application Data

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

There should be a special directory that stores all users of all applications and describes the top-level directory structure. Here, you need to create a subdirectory under the top-level directory structure .. The system. Windows. Application class of the Net Framework defines some attributes, which can create some common configuration paths for you. The application. localappdatapath attribute returns the path of getfolderpath (specialfolders. commonapplicationdata) + "\ companyName \ productname \ productversion. Similarly, application. userdatapath and application. localuserdatapath generate the path name in the user data and local data directory, which includes the company, application, and version number. If you combine these locations, you can create a configuration information for all your applications, or all the versions of a program, or special versions.

Note that I have not mentioned the application directory in these directories, that is, the directory under program files. You should never write data in program files or Windows directories or subdirectories. These directories require higher privileges, so you cannot expect your users to write the data.
Where to store the setup data of applications becomes a very important issue, just like the Machine security issues that every enterprise-level user or home user is worried about, putting the information in the correct position means there is no compromise between users who use your application. You still need to provide users with private feelings, and combine the correct positions in the. NET sequence. This will easily give each user a private feeling without compromising security.
====================================

Item 37: use the standard configuration Mechanism
In our quest to avoid hard-coding configuration and settings information, we have created divide different strategies for storing configuration information. in our quest to get it right, we kept improving and changing our minds about where to put such information. INI files? That was so Windows 3.1. You were limited in the structure of your configuration information, and you had to contend with filename collisions with other applications. The Registry? Yes, this was a step in the right direction, but it had its limitations as well. malicious programs cocould do serious damage to a machine writing the wrong things to the Registry. because of the dangers inherent in writing to the registry, a program must have administrative rights to write in parts of the Registry. are all your users running as admins with the capability to edit the registry? You hope not. If you use the registry, users running as nonadmins will get exceptions and errors when they attempt to save or read their settings.

thankfully, there are much better ways to store settings so that your program can adapt its behavior to your users' preferences, the install parameters, the machine settings, or just about anything else. the. net Framework provides a standard set of locations that your application can use to store configuration information. these locations are specific to your application and will work when the user has limited privileges on the machine where the code executes.

Read-Only information belongs in configuration files, XML files that control varous types of behavior in the application. defined schemas dictate all the elements and attributes that. net FCL parses from config files. these elements control settings such as the version of the framework being used, the level of debugging support (see item 36), and the search path for assemblies. one section you must understand is the same ettings section, which applies to both web and desktop applications. the runtime reads this section when your application starts. it loads all the keys and values into a namevaluecollection owned by your application. this is your section. you add any values that your application needs to control its behavior. if you modify the config file, you modify the application's behavior.

Asp. NET applications have a little more flexibility than desktop applications do with respect to config files. each virtual directory can have its own config file. the files are read in order for each virtual directory that is part of the URL. the most local wins. for example, the URL http: // localhost/myapplication/subdir1/subdir2/file. aspx cocould be controlled by four different config files. the machine. config file gets read first. second is the Web. config file in the myapplication directory. following is the Web. config files in subdir1 and subdir2, in that order. each can change values set by a previous config file or add its own key/value pairs. you can use this configuration inheritance to set up global application preferences and limit access to some private resources. web applications can have different deployments for different virtual directories.

On the desktop, there is only one application configuration file for each app domain. the. net runtime creates a default application domain for each executable that it loads, and reads one predefined config file into that domain. this default configuration file is located in the same directory as the executable and is called <applicationname>. <ext>. config. for example, myapp.exe wowould have a config file named myapp.exe. config. the specified ettings section can be used to create your own key/value pairs for your application.

Config files are great to store information that controls the behavior of your application at runtime. but you will quickly notice that there are no APIs to write configuration information from your application. configuration files are not the place for user settings of any sort. don't go running for the Registry yet. don't write your own from scratch. there is a better way for your. net desktop applications.

You need to define the format for your configuration information and put that configuration information in the right location. you can easily store and retrieve these settings by defining a settings structure and adding public read/write properties for the global settings:

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

 

Use the XML serializer to save 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 will be easy to read, easy to parse, and easy to debug. you can use encrypted storage for these user settings, if necessary for your application. this example uses the XML serializer, not the object serializer for persistence (see item 25 ). the XML serializer stores parameters, not entire object trees. configuration settings and user settings typically do not contain webs of objects, and the XML serializer is a simpler file format.

the only question remaining is where to store the information. you shoshould put settings information in three different locations. which you choose depends on when it shoshould be used: globally, per user, or per user and machine. all three locations are returned by different callto by the system. environment. getfolderpath () method. you shoshould append your application-specific directories on the end of the path returned by getfolderpath (). be extremely careful about writing information in the all-user or machine-wide directories. doing so requires more privileges on the target machine.

environment. specialfolder. commonapplicationdata returns the directory for storing information that is shared by all users on all machines. on a machine with a default installation, getfolderpath (specialfolder. commonapplicationdata) returns c: \ events and Settings \ All Users \ Application Data. settings stored under this location shocould be used by all users, on all machines. when you create information that shoshould go here, write it with the installer or an admin module. avoid writing data here in your user programs. chances are, your application does not have the necessary access rights on users 'machines.

Environment. specialfolders. applicationdata returns the directory for this user, shared by all machines in the network. on a default installation, getfolderpath (specialfolders. applicationdata) gives you c: \ Documents ents and Settings \ <username> \ Application Data. each user has his or her own application data directory. when the user logs into a domain, using this enumeration points to the network share that contains the user's global settings. settings stored under this location are used by the current user, No matter what machine in the network he has logged in from.

Environment. specialfolders. localapplicationdata returns the directory for storing information that is personal for this userand only when logged in on this machine. A typical value returned by getfolderpath (specialfolders. localapplicationdata) is c: \ Documents ents and Settings \ <username> \ Local Settings \ Application Data.

these three different locations let you store settings that shoshould apply to everyone, the given user, or the given user on the given machine. exactly which you use depends on the application. but consider some obvious examples: the database connection is a global setting. it shoshould be stored in the common application data directory. A user's working context shoshould be stored in the Application Data Directory because it depends only on the user. window locations shoshould be in the local application data directory because they depend on the user and properties of the machine (different machines might have different screen resolutions ).

these special folders describe the top-level directory structure for user settings stored by all applications. in all cases, you shoshould create subdirectories underneath these top-level structures. the. net Framework's system. windows. application class defines properties that build common configuration paths for you. the application. localappdatapath property returns the path for getfolderpath (specialfolders. commonapplicationdata) + "\ companyName \ productname \ productversion ". similarly, application. userdatapath and application. localuserdatapath produce pathnames underneath the user's data and local data directories for this company, application, and version. if you combine these locations, you can create configuration information for all your company's applications, for this application requires SS all versions, and for this specific version.

Note that nowhere in those directories did I mention the application directory, under program files. you shoshould not ever write data in any directory under program files or in the Windows System directory. those locations require more security privileges, So you shocould not perform CT your users to have permission to write in them.

Where you store your application's settings has become more important as everyone from enterprise users to home users worries about the security of machines. putting the information in the right location means that it is easier for your users to work with your application without compromising security. you can still provide your users with a personalized experience. combine the right location. net serialization, and it's easy to have your application provide a personalized appearance for each user without compromising security.

 

Related Article

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.