Thursday, October 2, 2008

Add new element in the web.config file using sharepoint

If you can add new element the web.config file using sharepoint administration SPWebConfigModification Object that have open web.config file and find the appropriate element tag in the web.config file and add new element in the web.config.

You can use this code in the feature actived.


try

{

SPWebApplication app = null;

SPWeb web = null;

SPSiteCollection site = properties.Feature.Parent as SPSiteCollection;

if (site == null)

{

web = properties.Feature.Parent as SPWeb;

if (web != null)

app = web.Site.WebApplication;

}

else

app = site.WebApplication;

SPWebConfigModification modification = new SPWebConfigModification();

modification.Name = "add [@Assembly='System.DirectoryServices'] [@Version='2.0.0.0'][@Culture='neutral'][@PublicKeyToken='B03F5F7F11D50A3A']";

modification.Path = "configuration/system.web/compilation/assemblies";

modification.Value = @"DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A'/> ";

modification.Owner = Assembly.GetExecutingAssembly().FullName;

modification.Sequence = 0;

modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

app.WebConfigModifications.Add(modification);

SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

}

catch (Exception ex)

{


}


The example code could be changed easily to remove the configuration change, as in the following example:

app.WebConfigModifications.Remove(modification);