About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Thursday, 27 October 2011

Manipulating web.config to Add Safe Controls Programmatically

Directly editing the web.config file is not recommended. Doing so could result in an invalid file, and the application could stop working. Even worse, it could become insecure in some way without noticing. To avoid this, the process of Web Part deployment and registering the assembly or its parts as safe should be closely followed, as shown in the next code snippet.
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
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. The code first checks the parent object the receiver refers to (i.e., the context object it’s installed in). From that object, the SPWebApplication object is pulled to get the web.config file that contains the site’s configuration. An XPath expression that contains the complete token and the path where it has to be added is used to get the configuration. A farm service is used finally to apply the modifications.
Happy programming......

No comments:

Post a Comment