Thursday, September 27, 2012

How to add and remove entries from Web.Config using SPWebConfigModification



One of requirement in my project was to edit the web.config of the current SharePoint web application.There are many other articles and posts discussing the same topic, however many people had the same issue that I was faced during modifying web.config file
1.      It adds multiple entries into web.config file where it should only add one single entry.
2.      It does not delete entries from web.config file.
After the doing some R&D on that part, I got the solution to add/remove entries from particular site.
The requirement was to add the following line into providers section of web.config file on Activating feature and delete from same on deactivating feature.




 

Then here are the steps to create a Feature that will add entries to the web.config for the SharePoint Web Application

               1.    Open Visual Studio 2010. 
           2.  Select New -- Project -- Empty SharePoint Project 
           3.  Provide a local site and Select “Deploy as a farm solution” option.
           4.  Right Click on the “Features” and Select “Add Feature”


     5.  Double click on feature and provide the Unique Title Name and Description and also Set Feature scope is “Site”
       
      6.    Right Click on Feature1.Feature and Click on “Add Event Receiver”


   7.   Register following namespace on “Feature1.EventReceiver.cs” file


         using Microsoft.SharePoint.Security;
         using Microsoft.SharePoint.Administration;
         using System.Collections.Generic;
         using System.Reflection;
 


 
  8.   Add following common variables and method before FeatureActivated Method

         string providerName = "ITCollabTopNavProvider";
         string proviDerdescription = "Custom ITCollab provider for top navigation in Portal          Usage pages";
         string providerType = "WebConfigModificationTesting.ITCollabTopNavProvider,                   WebConfigModificationTesting, Version=1.0.0.0, Culture=neutral,                            PublicKeyToken=0840b76c1e94278b";
         string providerNavType = "Current";
         string providerEncodeOutput = "true";
         string Owner = "Pravin";
         privatestring psSiteUrl = "";



private void __getSiteURL(SPFeatureReceiverProperties properties)
        {
         SPSite site = null;
         // Get a reference to the site collection of the feature
         if (properties.Feature.ParentisSPWeb)
            {
                  site = ((SPWeb)properties.Feature.Parent).Site;
            }
         elseif (properties.Feature.ParentisSPSite)
            {
                  site = properties.Feature.ParentasSPSite;
            }
         if (site != null)
            {
                  psSiteUrl = site.Url;
            }
        }

       
     9.   Add the following Code in FeatureActivated Method

      public override void FeatureActivated(SPFeatureReceiverProperties properties)
      {
__getSiteURL(properties);
SPWebApplicationwebApp = SPWebApplication.Lookup(newUri(psSiteUrl));
SPWebService service = SPWebService.ContentService;

//Add Provider URL
SPWebConfigModificationproConfigMod = newSPWebConfigModification();
proConfigMod.Owner = Owner;
proConfigMod.Path = "configuration/system.web/siteMap/providers";
proConfigMod.Name = String.Format("add [@name='" + providerName + "'] [@description='" + proviDerdescription + "'] [@type='" + providerType + "'] [@NavigationType='" + providerNavType + "'] [@EncodeOutput='" + providerEncodeOutput + "']");
proConfigMod.Value = String.Format(""
, providerName, proviDerdescription, providerType, providerNavType, providerEncodeOutput);
proConfigMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
webApp.WebConfigModifications.Add(proConfigMod);
webApp.Update();
service.ApplyWebConfigModifications();

      }



    10.   You also need to add code to remove the entry when the Feature is deactivated.



      public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

      {
      __getSiteURL(properties);
      SPWebApplicationwebApp = SPWebApplication.Lookup(newUri(psSiteUrl));
      try
      {
RemoveEntries(webApp);
webApp.Update();                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApp.WebConfigModifications.Clear();
      }
      catch (Exception ex)
      {
throw ex;
      }
      }

//Remove Entries made to web.config by Owner name “Smartrider”                               private void RemoveEntries(SPWebApplicationwebApp)
      {
       try
            {
List<SPWebConfigModification>entriesToRemove = newList<SPWebConfigModification>();
foreach (SPWebConfigModificationconfigModinwebApp.WebConfigModifications)
{
if (configMod.Owner == "Pravin")
{
entriesToRemove.Add(configMod);
}
       }
if (entriesToRemove.Count> 0)
{
for (inti = entriesToRemove.Count - 1; i>= 0; i--)
{
webApp.WebConfigModifications.Remove(entriesToRemove[i]);
}
       }
     }
      catch
      {
throw;
      }
    }


   11.  Deploy the code and check the web.config file to verify your entries.Deactivating the feature will remove that line and leave the web.config clean of our site web.config 

1 comment:

  1. Why not use the Assembly.GetExecutingAssembly rather than maintaining a "magic string"?? (providerType).

    ReplyDelete