Programmatically add safe control entry in sharepoint 2010

You write some code in Feature Receiver of your sharePoint solution to add a safe control entry in SharePoint application's web.config. Following example shows you how to do that

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(@"SafeControl[@Assembly="MyAssembly"][@Namespace="My.Namespace"]" + @"[@TypeName="*"][@Safe="True"][@AllowRemoteDesigner="True"]"
, "/configuration/SharePoint/SafeControls");

// Add the modification to the collection of modifications
webApp.WebConfigModifications.Add(mod);
// Apply the modification
webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
}
}
This code shows how to modify web.config using the appropriate classes called from a feature event receiver. If the Web Part is part of a feature and the feature is activated, the event is fired and the code executed.

1 comments:

  1. what if you don’t have permissions, or file is locked, or context is not ready yet and etc?

    ReplyDelete

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com