Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

how to access SharePoint web config Programmatically

how to access SharePoint web config Programmatically
In SharePoint 2010, you can easily access SharePoint's Web.Config file using SPWebConfigModification class of the Microsoft.SharePoint.Administration namespace.
It can be used in the situations where you might need to write an assembly to SafeControls element in your web config file using object model or may be something else.Well, the cool thing is these modifications are written to the web.config files on every front-end web server when the SPWebService.ApplyWebConfigModifications method is called.

Below is an example shows how to use the SPWebConfigModification class to register a custom assembly.

SPWebService service = 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 = "User Name";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "";
service.WebConfigModifications.Add(myModification);

/*Call Update and ApplyWebConfigModifications to save changes*/
service.Update();
service.ApplyWebConfigModifications();

Calling the ApplyWebConfigModifications method schedules a timer job to deploy the changes throughout the server farm. To apply a web.config modification to a specific Web application, add the modification to the collection of web.config modifications for the Web application (WebConfigModifications). For example, you can use oWebSite.Site.WebApplication.WebConfigModifications.Add(MyModification) to add a web.config modification to the parent Web application of a specific Web site. You must still call ApplyWebConfigModifications even if you add a web.config modification to a single Web application.

No comments:

Post a Comment