Monday 25 March 2013

Add , Modifying and Delete Web.Config Entries in SharePoint 2010 Programatically

Add, Modifying and Delete Web.Config Entries in SharePoint 2010 Programmatically.
You can use SPWebConfigModification  class of theMicrosoft.SharePoint.Administration namespace, which allow to manage web.config entries.
And other way is WebConfigurationManager class.
I am using AppSettings Group to add and Edit the values and Using Visual Webpart.

To add new entry
Where key is String AppSettings new  Key and Value is value for Key
private void newEntry(string Key,string Value)
            Configuration Newentry = WebConfigurationManager.OpenWebConfiguration("~");
            Newentry.AppSettings.Settings.Add(Key, Value);

To Edit Entry
Where key is String AppSettings Key and Value is New value for Key.

        private void ModifyExisting(string Key, string Value)
            Configuration ModifyEntry = WebConfigurationManager.OpenWebConfiguration("~");
            ModifyEntry.AppSettings.Settings[Key].Value = Value;

To Delete entry :
Where key is String AppSettings Key.
        private void DeleteKey(string key)
            Configuration DeleteEntry = WebConfigurationManager.OpenWebConfiguration("~");

Get All Entries:
In this method I am using Grid View to show all items (key Value pair) in Grid view and also excluding SharePoint Default entries.
private void LoadAllKeys()
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            if (appSettings.Count == 0)
                lblmsg.Text += "AppSettings is empty Use GetSection command first. <br>";
            gvAllRecords.DataSource = appSettings;
            foreach (GridViewRow item in gvAllRecords.Rows)
                if (item.Cells[1].Text == "FeedCacheTime" || item.Cells[1].Text == "FeedPageUrl" || item.Cells[1].Text == "FeedXsl1" || item.Cells[1].Text == "ReportViewerMessages")
                    item.Visible = false;
Get Specific Entries
Simple method where Key is Appsettings key name
private string GetSpecific(string key)
               return String Value = ConfigurationManager.AppSettings[Key];

No comments:

Post a Comment