Pages

Thursday 7 February 2013

How to Deploy changes to the web.config file as a feature for a SharePoint web application

I am currently working for a SharePoint hosting provider and as part of the general guidence, direct web.config changes are not allowed. Any change should be incorporated as a SharePoint feature, if you think about it, this is a good practice to get into.

Pros for deploying as features:
  • A solution repository can be maintained, which will make migration easy
     
  • Any future upgrades can lead to missing manual config changes
  • Fuctionality can be targeted to a web application or a sitec collection etc

Anyways, the post is about how to deploy changes to a web config via a feature.

*** Warning - Programatically modifying web.config changes are not very clean, so

Web config changes are specific to a web app, hence we will write and deploy a feature targetting a web app.

  1. Open visual studio and create a empty SharePoint project
  2. Add a new feature and set the Target to " Web Application"  (Make sure you name your Feature with an appropriate name)
  3. Double click on the Feature and in the Properties window, set the "Activate on Default" to false - We want to manually activate the feature per web application
     
  4. Add a Feature Receiver
  5. in the feature activated event, add the following code:


     public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                try
                {
                   SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://mywebapp"));

                    SPWebConfigModification moduleModification = new SPWebConfigModification();
                    moduleModification.Path = "configuration/system.webServer/modules runAllManagedModulesForAllRequests=\"true\"";
                    moduleModification.Name = "add[@name=\"myHttpModule\"][@type=\"myHttpModule.myHttpModuleClassLib, myHttpModule\"]";
                    moduleModification.Sequence = 0;
                    moduleModification.Owner = "admin";
                    moduleModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                    moduleModification.Value = "<add name=\"
    myHttpModule\" type=\"myHttpModule.myHttpModule, myHttpModule\" />";
                    webApp.WebConfigModifications.Add(moduleModification);

                    webApp.Update();
                    //service.ApplyWebConfigModifications();
                    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                }
                catch (Exception ex)
                {
                    //Log exceptions in the Event Log
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = "myHttpModule";
                        eventLog.WriteEntry(string.Format("{0}: - {1} Error: \"{2}\" ", EventLogEntryType.Error, "myHttpModule- Feature Activating", ex.ToString() + Environment.NewLine + ex.StackTrace.ToString()), EventLogEntryType.Error);
                    }
                   
                    //Throw the exception for the admin
                    throw ex;
                }

            }
  6.   Add the following code to feature deactivating


     public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
            {
                try
                {
                    SPWebConfigModification configModFound = null;
                    SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://mywebapp"));
                    Collection<SPWebConfigModification> modsCollection = webApp.WebConfigModifications;
                    for (int i = 0; i < modsCollection.Count; i++)
                    {
                        if (modsCollection[i].Owner == "fu1adm" && modsCollection[i].Name == "add[@name=\"
    myHttpModule\"]")
                            configModFound = modsCollection[i];
                    }
                    if (configModFound != null)
                    {
                        modsCollection.Remove(configModFound);
                        webApp.Update();
                        webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    }
                }
                catch (Exception ex)
                {
                    //Log exceptions in the Event Log
                    EventLog eventLog = new EventLog("Application");
                    eventLog.WriteEntry(string.Format("{0}: - {1} Error: \"{2}\" ", EventLogEntryType.Error, "myHttpModule- Feature Deactivate", ex.ToString() + Environment.NewLine + ex.StackTrace.ToString()), EventLogEntryType.Error);
                    throw ex;
                }


            }
  7.  Build the solution and add it to the solution store
  8. Deploy the solution to the web app or globally
  9. In Central Admin > Click on the Application management > Manage web applications > Select the appropriate web application and click on Manage Features > Click on activate.
  10.  Make sure the web.config has been modified.

There are numerous reasons why web.config changes should be avoided via code. Microsoft has limited documentation on this

References:
http://msdn.microsoft.com/en-au/library/bb861909%28v=office.14%29.aspx  

No comments:

Post a Comment