Home Categories ASP Tutorials Tutorial

Storing of web application settings

"How can I store the settings of my web .NET application?" - this is the one of the most often problems, which .NET developers face.

2.3/5.0 (3 votes total)
Rate:

Serge Turin
January 08, 2007


Serge Turin

Serge Turin is the CEO of Components 4U.

Serge Turin has more than 15 years of experience in software development and project management.

Serge Turin has written 1 articles for WebKnowHow.
View all articles by Serge Turin...

 

 

 

 

 

Storing of web application settings

1. Introduction

"How can I store the settings of my web .NET application?" - this is the one of the most often problems, which .NET developers face.

.NET platform provides several solutions for this problem. In this article we will consider each of the most popular solutions, advantages and disadvantages for each of them and try to explain how to choose one, which will be the best for your certain ASP.NET application.

There are the following options can be considered as the most convenient and covering almost all cases:

  • Storing settings in Global.asax file
  • Storing settings in Web.config file
  • Storing settings in database
  •  

    2. Storing settings in Global.asax

    Storing the settings of your ASP.NET application in the Global.asax file is the easiest way. This solution is based on using the Application_Start method and global property Application.

    The Application property of HttpContext class returns HttpApplicationState object for the current HTTP request. HttpApplicationState object allows sharing of global parameters between multiple sessions and requests with you ASP.NET application.

    A single instance of an HttpApplicationState class is created the first time a client requests any URL resource from within a particular ASP.NET application virtual directory. A separate single instance is created for each ASP.NET application on a Web server. A reference to each instance is then exposed via the intrinsic HttpContext.Application object.

    Method Application_Start occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request.

     

    Review the following example:

    Global.asax.cs

    protected void Application_Start(Object sender, EventArgs e)
    {
    Application["DbUser"]="dbUser";
    Application["DbUserPass"]="myPass";
    Application["DbName"]="coolDB";
    Application["DbServer"]="my.office.db.server";

    string myConnString = "Data Source=" +
    Application["DbServer"] + ";Initial Catalog=" +
    Application["DbName"] + ";User ID=" +
    Application["DbUser"] + ";Password=" +
    Application["DbUserPass"];
    Application["ConnString"] = myConnString;
    }

    Thus when your web application starts the Application object will contain the values of your parameters and you can access them on page within your application.

    SomePage.asax.cs

    private void Page_Load(object sender, System.EventArgs e)
    {
    SqlConnection myCnn;
    SqlCommand myCmd;
    SqlDataReader myReader;
    myCnn = new SqlConnection((string)Application["ConnString"]);
    myCmd = new SqlCommand("select * from countries", myCnn);
    myCnn.Open();
    myReader = myCmd.ExecuteReader();
    // :
    // Do something
    // :
    myCnn.Close();
    }

     

    Let's consider the advantages and disadvantages of using Global.asax as storage for web application parameters.

    Advantages:

    1. Simplicity of realization
    2. You can store the critical parameters, which you don't want to be changed without your confirmation (Developer Name, License Information). The changing of any parameter within Global.asax file requires recompilation of whole application. So it will be impossible to do without an access to source code

    Disadvantages:

    1. To change the value of any parameter it is required to recompile whole application. Therefore this method is not good for parameters, which have to be changed frequently.
    2. Uploading of recompiled version will cause restart of whole application.

    3. Storing settings in Web.config

    The more flexible variant of the storing web application settings is the using of Web.config file.

    Configuration information for ASP.NET resources is contained in a collection of configuration files, each named Web.config. Each configuration file contains a nested hierarchy of XML tags and subtags with attributes that specify the configuration settings. Because the tags must be well-formed XML, the tags, subtags, and attributes are case-sensitive. Tag names and attribute names are camel-cased, which means that the first character of a tag name is lowercase and the first letter of any subsequent concatenated words is uppercase. Attribute values are Pascal-case, which means that the first character is uppercase and the first letter of any subsequent concatenated words is uppercase. Exceptions are true and false, which are always lowercase.

    All configuration information resides between the <configuration> and </configuration> root XML tags.

    There is a special <appSettings> Element in Web.config, which can be used for storing custom application settings. This is a predefined configuration section provided by the .NET Framework.

    The <appSettings> element stores custom application configuration information such as database connection strings, file paths, XML Web service URLs, or any information stored in an application's .ini file. The key/value pairs specified in the <appSettings> element can be accessed in code using the System.Configuration.ConfigurationSettings or System.Configuration.AppSettingsReader classes.

    Review the following example:

    Web.config

    <configuration>

    <appSettings>
    <!-- SQL Server Settings-->
    <add key="SQL_SERVER_NAME" value="localhost" />
    <add key="SQL_DB_NAME" value="mydb" />
    <add key="SQL_DB_USERID" value="sa" />
    <add key="SQL_DB_PASSWORD" value="" />
    <!-- Following template can be used for tuning of SQL connection only
    Use SQL_... parameters above to specify standard connection parameters
    -->
    <add key="SQL_CONNECTION_STRING_TEMPLATE" value="data source={SERVER_NAME};initial catalog={DB_NAME};user id={USER_ID};password={PASSWORD};workstation id={WORKSTATION_ID};packet size=4096;persist security info=True" />
    </appSettings>


    myConfigurator.cs

    protected const String C_SQL_CONNSTR_TEMPLATE_KEY = "SQL_CONNECTION_STRING_TEMPLATE";
    protected const String C_SQL_SERVER_KEY = "SQL_SERVER_NAME";
    protected const String C_SQL_DB_NAME_KEY = "SQL_DB_NAME";
    protected const String C_SQL_DB_USERID_KEY = "SQL_DB_USERID";
    protected const String C_SQL_DB_PASSWORD_KEY = "SQL_DB_PASSWORD";

    // return SQL connection string
    public static void GetSQLConnectionParams(out String sqlServer,out String dbName, out String dbUserId, out String dbPassword, out String connStrTemplate)
    {
    AppSettingsReader ar = new AppSettingsReader();
    try
    {
    //obtain connection string template from config file
    connStrTemplate = ar.GetValue(C_SQL_CONNSTR_TEMPLATE_KEY, typeof(String)).ToString();
    }
    catch
    {
    //return empty string if error
    connStrTemplate = "";
    }

    // obtain SQL connection parameters
    sqlServer = ar.GetValue(C_SQL_SERVER_KEY, typeof(String)).ToString();
    dbName = ar.GetValue(C_SQL_DB_NAME_KEY, typeof(String)).ToString();
    dbUserId = ar.GetValue(C_SQL_DB_USERID_KEY, typeof(String)).ToString();
    dbPassword = ar.GetValue(C_SQL_DB_PASSWORD_KEY, typeof(String)).ToString();
    }



    public static String GetSQLConnectionString()
    {
    const String C_SERVER_NAME_TEMPLATE = "{SERVER_NAME}";
    const String C_DB_NAME_TEMPLATE = "{DB_NAME}";
    const String C_USER_ID_TEMPLATE = "{USER_ID}";
    const String C_PASSWORD_TEMPLATE = "{PASSWORD}";
    const String C_WORKSTATION_ID_TEMPLATE = "{WORKSTATION_ID}";

    //default template for building connection string
    const String sConnStrTemplateDefault = "data source=" + C_SERVER_NAME_TEMPLATE + ";" + "initial catalog=" + C_DB_NAME_TEMPLATE + ";" + "user id=" + C_USER_ID_TEMPLATE + ";" + "password=" + C_PASSWORD_TEMPLATE + ";" + "persist security info=True;" + "workstation id=" + C_WORKSTATION_ID_TEMPLATE + ";" + "packet size=4096";
    String sConnStr = "";
    String sConnStrTemplate = "";
    String sql_server = "";
    String db_name = "";
    String user_id = "";
    String password = "";

    GetSQLConnectionParams(out sql_server, out db_name, out user_id, out password, out sConnStrTemplate);

    //use default template for connection string if it not present
    if(sConnStrTemplate == null || sConnStrTemplate.Equals(""))
    {
    sConnStrTemplate = sConnStrTemplateDefault;
    }
    //build connection string
    sConnStr = sConnStrTemplate.Replace(C_SERVER_NAME_TEMPLATE, sql_server);
    sConnStr = sConnStr.Replace(C_DB_NAME_TEMPLATE, db_name);
    sConnStr = sConnStr.Replace(C_USER_ID_TEMPLATE, user_id);
    sConnStr = sConnStr.Replace(C_PASSWORD_TEMPLATE, password);
    sConnStr = sConnStr.Replace(C_WORKSTATION_ID_TEMPLATE, System.Net.Dns.GetHostName());

    return sConnStr;
    }


    Thus we can retrieve the values of our parameters by using the static methods of myConfigurator class and use these parameters in all places of our application.

    SomePage.asax.cs

    private void Page_Load(object sender, System.EventArgs e)
    {
    SqlConnection myCnn;
    SqlCommand myCmd;
    SqlDataReader myReader;
    myCnn = new SqlConnection(myConfigurator.GetSQLConnectionString());
    myCmd = new SqlCommand("select * from countries", myCnn);
    myCnn.Open();
    myReader = myCmd.ExecuteReader();
    // :
    // Do something
    // :
    myCnn.Close();
    }

     

    Let's consider the advantages and disadvantages of using Web.config as a storage for web application parameters.

    Advantages:

    1. Settings can be operatively changed
    2. No need to recompile whole application

    Disadvantages:

    1. After changing of settings application restart occurs
    2. Additional system resources for file-based operations
    3. Anyone, who has access to Web.config file, can change settings

    Storing settings in database

    The following method is based on storing application settings in database.
    This method is most flexible and independent from .NET infrastructure, however it requires additional system resources for the performing of database operations.

    Review the following example:
    SQL Script

    /*==============================================================*/
    /* Table: Settings */
    /*==============================================================*/

    create table t_settings (
    id int not null,
    description nvarchar(255) not null,
    value nvarchar(255) not null
    )
    on PRIMARY
    go

    insert into t_settings values(1, "Site administrator name", "admin")
    insert into t_settings values(2, "Site administrator password", "adminPWD")
    insert into t_settings values(3, "Images directory", "img")



    Configurator.cs

    public enum Settings
    {
    AdminName = 1,
    AdminPassword = 2,
    ImagesDir = 3
    }

    public string GetConfigurationValue(Settings setting)
    {
    SqlConnection myCnn;
    SqlCommand myCmd;
    SqlDataReader myReader;

    String sSQL = "select * from t_settings where id=" + setting;
    myCnn = new SqlConnection(sSQLConnectionString);
    myCmd = new SqlCommand(sSQL, myCnn);
    myCnn.Open();
    myReader = myCmd.ExecuteReader();
    myReader.Read();
    sSQL = myReader["value"];
    myCnn.Close();
    return sSQL;
    }



    SomePage.asax.cs

    private void Page_Load(object sender, System.EventArgs e)
    {
    Configuration conf = new Configuration();
    sImagePath = conf.GetConfigurationValue(Settings.ImagesDir);
    // :
    // Do something
    // :
    }

     

    An of course let's consider the advantages and disadvantages of using database as a storage for web application parameters.

    Advantages:

    1. Centralized storage of all application settings
    2. Settings can be operatively changed
    3. No need in recompilation of whole application
    4. Application restart doesn't occur after the changing of settings

    Disadvantages:

    1. Database engine is required
    2. Additional system resources for database operations
    3. General reliability of application decreases
    4. Anyone, who has an access to database, can change application settings
    Resume
    Thus after review of all these methods we can see that you may need to use each of these methods in your application and real choice will depend on the specific of your application.

    The following table will help you to choose method, which will most appropriate for your certain ASP.NET application.


     
    Condition
     
    Appropriate method
     
    You need to store the internal application settings and you don't need anyone except you to change these settings (for example, developer name, copyright, critical system setting)
     
    You should choose storing of settings in Global asax file (Method 1).

     Application settings, which don't need to be frequently changed. Application users can't change these setting, however you need to allow application administrator changing these settings.

    Any changeable application settings if you don't have database installed.
     
    You should choose the storing of your setting in Web.config file (Method 2).

    To reduce system resources related to file-based operation you can combine this method with using Application and Session objects.

     
    Application settings, which changes very often, and application settings, which have to be changeable by application users.
     
    You should choose the storing application settings in database.

    To reduce the number of requests to database you can combine this method with using Cache and Session objects.

     

    Source: www.components4u.net

     


    Add commentAdd comment (Comments: 0)  

    Advertisement

    Other Resources