Introduce DataBase,Asp.net,JavaScript,Xml,Html,Css,Sql,Php,ASP.NET Controls,AJAX,Tools,HTML,CSS,JavaScript,Open Source Project,WPF,.Net Framework,Linq
Top Recommended Hosting

Use the Standard Configuration Mechanism

by the3factory 5/5/2008 8:20:00 AM

In our quest to avoid hard-coding configuration and settings information, we have created many 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 could 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 various types of behavior in the application. Defined schemas dictate all the elements and attributes that the .NET FCL parses from config files. These elements control settings such as the version of the framework being used, the level of debugging support , and the search path for assemblies. One section you must understand is the appSettings 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 could 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 configurations 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 would have a config file named MyApp.exe.config. The appsettings 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 . The XML serializer stores documents, 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 should put settings information in three different locations. Which you choose depends on when it should be used: Globally, per user, or per user and machine. All three locations are returned by different calls to by the System.Environment.GetFolderPath() method. You should 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:\Documents and Settings\All Users\Application Data. Settings stored under this location should be used by all users, on all machines. When you create information that should 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 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 and Settings\<username>\Local Settings\Application Data.

These three different locations let you store settings that should 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 should be stored in the Common Application Data directory. A user's working context should be stored in the Application Data directory because it depends only on the user. Window locations should 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 should 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 across all versions, and for this specific version.

Note that nowhere in those directories did I mention the application directory, under Program Files. You should not ever write data in any directory under Program Files or in the Windows system directory. Those locations require more security privileges, so you should not expect 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 with .NET serialization, and it's easy to have your application provide a personalized appearance for each user without compromising security.

Related posts

Sign up for PayPal and start accepting credit card payments instantly.


Powered by BlogEngine.NET 1.2.0.0