woensdag 3 december 2008

Sharepoint: Add or delete you configuration settings on feature activate / deactivated

When activating a feature you can add some settings to the web.config for example. Below you will see some code to add configuration settings.



Insert the next Code into the event FeatureActivated of your event receiver of your feature.

ConnectionString

SPSite site = (SPSite)properties.Feature.Parent;
SPWebApplication webApp = site.WebApplication;
SPWebConfigModification modConfig = new SPWebConfigModification("add[@name=\"name of connectionstring\"]", "configuration/connectionStrings");
modConfig.Owner = strOwner;
modConfig.Sequence = 0;
modConfig.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modConfig.Value = String.Format("<add name=\"{0}\" connectionString=\"{1}\" providerName=\"{2}\" />", " name of connectionstring ", "connectionstring", ProviderInfo");
webApp.WebConfigModifications.Add(modConfig);
webApp.Farm.Services.GetValue<SPWebService>().WebConfigModifications.Clear();
webApp.Update();
webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

Section

SPSite site = (SPSite)properties.Feature.Parent;
SPWebApplication webApp = site.WebApplication;
SPWebConfigModification modsec = new SPWebConfigModification("section[@name=\"name of section\"]", "configuration/configSections");
modsec.Owner = strOwner;
modsec.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modsec.Value = String.Format("<section name=\"{0}\" type=\"{1}\" />", "name of section", "Type");
webApp.WebConfigModifications.Add(modsec);
webApp.Farm.Services.GetValue<SPWebService>().WebConfigModifications.Clear();
webApp.Update();
webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();



Insert the folowing code in the FeatureDeactivating of your event receiver of your feature.

When you deactivate the feature all the entries which was made by the owner will be deleted.

Remove setting

SPWebApplication webApp = SPWebApplication.Lookup(new Uri(AbsoluteUrl));
if (webApp != null)
{
Collection<SPWebConfigModification> collection = webApp.WebConfigModifications;
int iStartCount = collection.Count;
// Remove any modifications that were originally created by the owner.
for (int c = iStartCount - 1; c >= 0; c--)
{
SPWebConfigModification configMod = collection[c];

if (configMod.Owner == strOwner)
collection.Remove(configMod);
}


// Apply changes only if any items were removed.
if (iStartCount > collection.Count)
{
webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApp.Update();
}
}

Geen opmerkingen: