Thursday, April 21, 2011

Programmatically add/remove SharePoint Changes in web.config

New entries can be added to Sharepoint web.config programmatically. Also the changes can be tracked by owner or tagged. So later all the changes can be removed also.
This can be done using class:
SPWebConfigModification modification
It has properties such as:
modification.Value
modification.Owner
modification.Sequence
modification.Type
and for adding/removing:
pWeb.Site.WebApplication.WebConfigModifications.Add(modification);
pWeb.Site.WebApplication.WebConfigModifications.Remove(modification);

Remove config entries by owner:
protected static void RemoveConfigEntries(SPWebApplication webApplication, string owner)
{
            Collection<SPWebConfigModification> oCollection = webApplication.WebConfigModifications;
            int iStartCount = oCollection.Count;
            for (int c = iStartCount - 1; c >= 0; c--)
            {
                //get all config changes in a collection
                SPWebConfigModification oModification = oCollection[c];

                if (oModification.Owner.Contains(owner))
                    oCollection.Remove(oModification);

            }

            //update only when we actually remove some entries
            if (iStartCount > oCollection.Count)
            {
                webApplication.Update();
                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
}

Or On Feature Deactivation: (From book Pro Sharepoint 2010 Solution Dev_Office pp. 254)
public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
SPWebApplication currentWebApp = (SPWebApplication)properties.Feature.Parent;
Collection<SPWebConfigModification> modificationCollection = currentWebApp.WebConfigModifications;
Collection<SPWebConfigModification> removeCollection = new Collection<SPWebConfigModification>();
int count = modificationCollection.Count;
for (int i = 0; i < count; i++)
{
SPWebConfigModification modification = modificationCollection[i];
if (modification.Owner == "SiteProvisionFeature")
{
  // collect modifications to delete
  removeCollection.Add(modification);
}
}
// now delete the modifications from the web application
if (removeCollection.Count > 0)
{
foreach (SPWebConfigModification modificationItem in removeCollection)
{
  currentWebApp.WebConfigModifications.Remove(modificationItem);
}
// Commit modification removals to the specified web application
currentWebApp.Update();
// Push modifications through the farm
currentWebApp.WebService.ApplyWebConfigModifications();
}
}


No comments:

Post a Comment