ASP.NET 2.0 Read/Write Web.config File

Recently I have a requirement from a customer to modify the web.config [AppSettings] keys value at runtime in grid like format using asp.net 2.0

Here is the way I have implemented.

 1) Create  a class in App_Code and copy & paste the below code

public class AppSettingsOperations
    {

//get all the keys    

    public AppSettingsKeysList getAllAppSettingsKeys()
        {
            AppSettingsKeys appSettingsKey =null;
            AppSettingsKeysList appSettingsKeysList = new AppSettingsKeysList();
            int idCount =0;

            Configuration configuration = WebConfigurationManager.OpenWebConfiguration(“~”);

            AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(“appSettings”);

            if (appSettingsSection != null)
            {

                foreach (string key in appSettingsSection.Settings.AllKeys)
                {
                    idCount++;

                    appSettingsKey = new AppSettingsKeys();
                    appSettingsKey.ConfigID = idCount;
                    appSettingsKey.ConfigName = key;
                    appSettingsKey.ConfigValue = appSettingsSection.Settings[key].Value;

                    appSettingsKeysList.Add(appSettingsKey);
                       
                }
            }

            return appSettingsKeysList;
        }

//Modify the key

        public bool ModifyKey(AppSettingsKeys appSettingsKeys)
        {
            try
            {
                Configuration configuration = WebConfigurationManager.OpenWebConfiguration(“~”);

                AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection(“appSettings”);

                if (appSettingsSection != null)
                {

                    appSettingsSection.Settings[appSettingsKeys.ConfigName].Value = appSettingsKeys.ConfigValue;

                    configuration.Save();

                }

               
            }
            catch (Exception ex)
            {
                return false;

            }
            return true;

        }

    }

2) Create an entity to store the config key and value
 public class AppSettingsKeys
    {
        private int _configID;
        private string _configName;
        private string _configValue;
       

        public int ConfigID
        {
            get { return _configID; }
            set { _configID = value; }
        }
        public string ConfigName
        {
            get { return _configName; }
            set { _configName = value; }
        }
        public string ConfigValue
        {
            get { return _configValue; }
            set { _configValue = value; }
        }

        public AppSettingsKeys()
        {

            _configID = 0;
            _configName = string.Empty;
            _configValue = string.Empty;
        
        }

        public void SetInfo(int id, string configName, string configValue)
        {
            this._configID = id;
            this._configName = configName;
            this._configValue = configValue;
        }
    }

3) Create a collection class like the below

public class AppSettingsKeysList : List<AppSettingsKeys>
    {

    }

4) Create an aspx page and paste the below code

<table  cellspacing=”8″ cellpadding=”1″ id=”table1″ align=”center” class=”loginTable” style=”width: 580px;” valign=”top”>
           <tr>
               
                <td colspan=”4″ class=”topText” align=”center” >
                    <asp:Label ID=”lblHeader” runat=”server” Text=”Web.Config [AppSettings] Keys”></asp:Label>&nbsp;</td>
               
            </tr>
          
     <tr align=”center” >
       <td   >
                    <asp:GridView ID=”GVAppConfig” Width=”560″ DataKeyNames=”ConfigID” 
                        runat=”server” AutoGenerateColumns=”False”  AutoGenerateEditButton=”True” 
                        CssClass=”labelText” TabIndex=”1″ OnRowEditing=”GVAppConfig_RowEditing”
                        CellPadding=”4″ OnRowCancelingEdit=”GVAppConfig_RowCancelingEdit”
                        OnRowUpdating=”GVAppConfig_RowUpdating” BackColor=”White”
                        BorderColor=”#000000″ BorderStyle=”Inset” BorderWidth=”1px”
                        ToolTip=”Edit AppSettings Key values in web.config” AllowPaging=”True”
                        onpageindexchanging=”GVAppConfig_PageIndexChanging”     >
                     <Columns>
                     <asp:BoundField DataField=”AppConfigID” HeaderText=”Config ID”  Visible=”False”   /> 
                      <asp:TemplateField HeaderText=”Config Name” >
                        <ItemTemplate>
                            <asp:Label ID=”lblconfigname” runat=”server” Text='<%# Bind(“ConfigName”) %>’></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    
                      <asp:TemplateField HeaderText=”Config Value” >
                      <EditItemTemplate>
                            <asp:TextBox  ID=”txtConfigValue” runat=”server” Text='<%# Bind(“ConfigValue”) %>’></asp:TextBox>
                            <asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ControlToValidate=”txtConfigValue”
                                ErrorMessage=”Please enter a value” SetFocusOnError=”True”
                                >*</asp:RequiredFieldValidator>
                        </EditItemTemplate>
                       
                        <ItemTemplate>
                            <asp:Label ID=”lblconfigvalue” runat=”server” Text='<%# Bind(“ConfigValue”) %>’></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                       
                     </Columns>
                      <AlternatingRowStyle BorderWidth=”1px” BackColor=”#cccccc”  ForeColor=”#000000″ />
                    <FooterStyle BackColor=”#cccccc” ForeColor=”#000000″ />
                    <RowStyle BackColor=”White” ForeColor=”#000000″ />
                    <SelectedRowStyle BackColor=”#009999″ ForeColor=”#CCFF99″ />
                    <PagerStyle BackColor=”#99CCCC” ForeColor=”#003399″ HorizontalAlign=”Left” />
                    <HeaderStyle BackColor=”#CC9900″ Font-Bold=”True” ForeColor=”#000000″ />
                    </asp:GridView>
      
       </td>
     
      </tr>
    
     </table><br /><br />
     <asp:Label ID=”lblMsg” runat=”server” CssClass=”requiredText” ></asp:Label>

5)In the code behind paste the below code

public partial class Admin_AppConfig : System.Web.UI.Page
{
   
    #region PageLoad Event
    protected void Page_Load(object sender, EventArgs e)
    {

           lblMsg.Text = String.Empty;

        if (!IsPostBack)
        {
            //calling the method to populate all the appSettings keys
            try
            {
                GetAppSettingsKeys();
            }
            catch (Exception ex)
            {
                exceptionMethod(ex);
               
            }
        }
    }

  
 #endregion

    #region Userdefined methods

    #region exceptionMethod Method
    private void exceptionMethod(Exception ex)
    {
               lblMsg.Text = ex.Message.ToString();
        lblMsg.ForeColor = System.Drawing.Color.Red;
    }
    #endregion

    #endregion

    #region GetAppSettingsKeys Method
    private void GetAppSettingsKeys()
    {
        AppSettingsOperations appSettingsOperations = new AppSettingsOperations();
        AppSettingsKeysList appSettingsKeysList = new AppSettingsKeysList();

        try
        {
            appSettingsKeysList = appSettingsOperations.getAllAppSettingsKeys();

            if (appSettingsKeysList.Count > 0)
            {
                //calling the bindgridview method
                BindGridView(appSettingsKeysList);
            }
            else
            {
                lblMsg.Text = “>>No Keys available”;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
#endregion

    #region Bindgridview Method

    private void BindGridView(AppSettingsKeysList allKeysList)
    {
        try
        {
            GVAppConfig.DataSource = allKeysList;
            GVAppConfig.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion

   
    #region Gridview events
    #region Gridview Rowedditing Event
    protected void GVAppConfig_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GVAppConfig.EditIndex = e.NewEditIndex;
            GetAppSettingsKeys();
           
        }
        catch (Exception ex)
        {
            exceptionMethod(ex);
    
        }
    }
    #endregion
   
    #region gridview rowcanceling event
    protected void GVAppConfig_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            GVAppConfig.EditIndex = -1;
            GetAppSettingsKeys();
           
        }
        catch (Exception ex)
        {
            exceptionMethod(ex);    
        }
 
    }
    #endregion

    #region gridview rowupdating event
    protected void GVAppConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        AppSettingsKeys appSettingsKeys = new AppSettingsKeys();
        AppSettingsOperations appSettingsOperations = new AppSettingsOperations();

        try
        {
            Label  lblKey = (Label)GVAppConfig.Rows[e.RowIndex].Cells[2].Controls[1];
            TextBox txtValue = (TextBox)GVAppConfig.Rows[e.RowIndex].FindControl(“txtConfigValue”);
            string keyValue = txtValue.Text;
            string keyName = lblKey.Text;
            int configID = Convert.ToInt32(GVAppConfig.DataKeys[e.RowIndex].Value);

            appSettingsKeys.ConfigID    = configID;
            appSettingsKeys.ConfigName  = keyName;
            appSettingsKeys.ConfigValue = keyValue;

            //Update the key with the user entered value
            if (appSettingsOperations.ModifyKey(appSettingsKeys))
            {
                lblMsg.ForeColor = System.Drawing.Color.Green;
                lblMsg.Text = “>>Key has been updated successfully”;
            }
            else
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = “>>There is some problem in updating the key ,try later”;

            }
    
            GVAppConfig.EditIndex = -1;
            GetAppSettingsKeys();
           
        }
        catch (Exception ex)
        {
            exceptionMethod(ex);    
        }
   }
    #endregion
    protected void GVAppConfig_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GVAppConfig.PageIndex = e.NewPageIndex;
        GetAppSettingsKeys();
    }

   

   
    #endregion

  
}

Compile and view  the page

Happy Programming !!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s