Modify web.config settings on feature activation in SharePoint
13 April 2011
In SharePoint 2010 there is a way to modify web.config settings file. You need to use SPWebConfigModification class which is a part of Microsoft.SharePoint.Administration namespace. This class allows us to register entities dynamically.
Adding new settings in web.config
I am going to use SPWebModification class inside “Feature Activating” method of SharePoint feature to register a custom assembly.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{ SPWebService newService = SPWebService.ContentService; SPWebConfigModification customModification = new SPWebConfigModification(); customModification.Path = "configuration/SharePoint/SafeControls"; customModification.Name = "SafeControl[@Assembly='CustomAssembly'][@Namespace='CustomNamespace'][@TypeName='*'][@Safe='True']"; customModification.Sequence = 0; customModification.Owner = "UserName"; customModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode; customModification.Value = "<SafeControl Assembly='CustomAssembly' Namespace='CustomNamespace' TypeName='*' Safe='True' />"; newService.WebConfigModifications.Add(customModification); newService.Update(); newService.ApplyWebConfigModifications(); }
Now you need to deploy and activate the feature. After that open web.config of your SharePoint web application where you deployed the feature and will find the following setting being added.J
<SafeControl Assembly="CustomAssembly" Namespace="CustomNamespace" TypeName="*" Safe="True" />