Tuesday, July 21, 2009

How to register safe control to web.config manually

Here is a little code example I found at MSDN that allows you to add a safe control to the web application web.config file throughout the SharePoint farm.

It uses the SPWebConfigModification class to add the change and will, make sure your changes gets re-applied whenever a new web application is created in the farm!

Note, you can add all sorts of modifications using this class - not only safe controls.
As Daniel Larson wrote in the comments for the MSDN article, for web controls - if possible you should use other methods of deployment and update the safe control in the manifest xml file.

taken from: msdn SPWebConfigModification

SPWebService myService = SPWebService.ContentService;

SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/SharePoint/SafeControls";
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";
myModification.Sequence = 0;
myModification.Owner = WebConfigModificationFeatureReceiver.OwnerId;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "";

myService.WebConfigModifications.Add(myModification);
myService.Update();
myService.ApplyWebConfigModifications();


I found that usefull when a customer of ours wanted to use a custom field inside a publishing page layout... the original installer did not add the safe control since you dont need it when you are inside list item form (create/edit/view), but inside a publishing page layout we got a message saying the control is not registered as safe.

Hope you do to, Shai.

No comments: