Friday, August 1, 2008

SPWebConfigModification Class - Editing Sharepoint Web.Config

I have seen some of the code where in if a "SafeControl" entry is need to be done in the web.config, through code, then we use
"XMLDocument" class to load the web.config and make changes . there is trouble in doing so as you need to manually get the path of the web.config and all.

But Sharepoint object model provides a class called "SPWebConfigModification" which can be used to play around with the web.config of the site.

Sample Code where in --Safe Control Entry is Made for the Webparts in the feature activation



public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = (SPSite)properties.Feature.Parent;

if (site != null)
{
SPWebApplication webApp = site.WebApplication;

SPWebConfigModification ModDesc = new SPWebConfigModification();
ModDesc.Path = "configuration/SharePoint/SafeControls";
ModDesc.Name = "SafeControl[@Assembly='Description'][@Namespace='Description'][@TypeName='*'][@Safe='True'] [@AllowRemoteDesigner='True']";
ModDesc.Sequence = 0;
ModDesc.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
ModDesc.Value = "";


webApp.WebConfigModifications.Add(ModDesc);

webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
webApp.Update();

}