When you work with Sharepoint 2010, sometimes you need to store data like connection strings or sometimes you just need to modify the security or you just need to add a safe control entry… who knows. Basically, I understand that the web.config it is the brain of Sharepoint 2010. This text file is so powerful that by having one character wrong will stop the whole farm, that is why Microsoft designed the SPWebConfigModification class.
This class allows you to modify/add anything in the web.config programmatically specifying the section, type, values etc.
The best way to see how this class works it is with a simple example. We are going to add a safe control entry into the web.config, the section is called <SafeControls>, I attach an image with the location so you can have an idea of what we are going to add.
We are going to add a new <SafeControl> section under <SafeControls> with the following code (thanks MSDN):
//## WEBSERVICE MANAGER CONTROLS THE WEB.CONFIG ENTRIESSPWebService _spWebService= SPWebService.ContentService;//## PROPERTIESSPWebConfigModification _spWebModification = new SPWebConfigModification();_spWebModification.Path = "configuration/SharePoint/SafeControls";_spWebModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";_spWebModification.Sequence = 0;_spWebModification.Owner = WebConfigModificationFeatureReceiver.OwnerId;_spWebModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;_spWebModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />";//## ADDING THE DATA IN THE WEB.CONFIG_spWebService.WebConfigModifications.Add(_spWebModification);//## UPDATING THE WEB.CONFIG_spWebService.Update();_spWebService.ApplyWebConfigModifications();
Probably the best place where to apply this code will be in one of the events in the Feature Receiver, but that is always up to you.
Conclusion: SPWebConfigModification will automatise and make the life easier for Sharepoint Administrators, leaving the messy old school web.config apart. I am sorry but I have never liked the concept of web.config.
No comments:
Post a Comment