Add safe controls programmatically in SharePoint 2010

This SharePoint tutorial explains, how to add safe control entries in web.config file programmatically in SharePoint 2010.

It is not a recommended approach to change directly in the web.config file in SharePoint, because sometimes it might stop working.

To overcome the above issue, we can modify the web.config file in the FeatureActivated event like below. Here we have created a feature using visual studio 2010 in SharePoint.

Add safe controls programmatically in SharePoint 2010

Below is the code to add safe controls programmatically using visual studio in SharePoint 2010.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
// A reference to the features site collection
SPSite site = null;
// Get a reference to the site collection of the feature
if (properties.Feature.Parent is SPWeb)
site = ((SPWeb)properties.Feature.Parent).Site;
else if (properties.Feature.Parent is SPSite)
site = properties.Feature.Parent as SPSite;
if (site != null)
SPWebApplication webApp = site.WebApplication;

// Create a modification
SPWebConfigModification mod = new SPWebConfigModification(
+ @”[@TypeName=”*”][@Safe=”True”][@AllowRemoteDesigner=”True”]”
, “/configuration/SharePoint/SafeControls”

// Add the modification to the collection of modifications

// Apply the modification

Below are the attributes defined:
@Assembly: Assembly attribute to define the fully qualified name of the assembly.

@Namespace and @TypeName: NameSpace and TypeName used to restrict which controls are permitted. For TypeName, the asterisk signifies “all controls”.

@Safe: Safe attribute set to true to make the control safe.

You may like following SharePoint visual studio tutorials:

Hope this SharePoint tutorial explains how to add safe controls programmatically in SharePoint 2010 using visual studio 2010.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.