Search This Blog

Thursday, September 18, 2014

SharePoint web.config modification programmatically using c#

Here is the sample code to customize the web.config file for the SharePoint site programmatically
spSite = new SPSite(http://intranet.demo.com);
SPWeb spWeb = spSite.OpenWeb();
SPWebService service = SPWebService.ContentService;
SPWebApplication webApp = new SPSite("http://intranet.demo.com").WebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name);
XmlDocument doc = new XmlDocument();
doc.Load(configFilePath);
AppSettingsSection appSettings = config.AppSettings;
if (appSettings.ElementInformation.IsPresent)
{
XmlNode nodekey = doc.SelectSingleNode("configuration/appSettings/add[@key='key']");
if(nodekey == null)
{
SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/appSettings";
myModification.Name ="add[@key='userName']";
myModification.Sequence = 0;
myModification.Owner = "User Name";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value =
";
service.WebConfigModifications.Add(myModification);
}
}
/*Call Update and ApplyWebConfigModifications to save changes*/
service.Update();
service.ApplyWebConfigModifications();
As you can see, it is pretty simple and if you want to apply to the sitespWeb.Site.WebApplication.WebConfigModifications.Add(MyModification)
If you want to apply to the whole farm
webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
wenApp.Update();


c# programmatically check the "<appSettings>" tag in web.config file of sharepoint sites


To check programmatically weather the appSettings tag is present in the web.config file of SharePoint sites, here is the code

using (SPSite site = new SPSite("http://servername:portnumber"))
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", mySite.WebApplication.Name);
AppSettingsSection appSettings = config.AppSettings;
bool isAppSettingsTagPresent = appSettings.ElementInformation.IsPresent;
}


No comments:

Post a Comment