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.
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.
what if you don’t have permissions, or file is locked, or context is not ready yet and etc?
ReplyDelete