Archive

Archive for the ‘SharePoint 2007’ Category

Automating SharePoint web.config Changes

January 20th, 2009 Michael Bell No comments

Here is my take on automating web.config changes in SharePoint 2007. In this example I make some changes so that I see detailed errors and stack traces on exceptions that are thrown within SharePoint. A few things I learned while playing around with this the first few times:

  • If you have mods going in in several places, or have lots of mods, complete them all and then do your Update() and ApplyWebConfigModifications(). If you do several saves, you will run into some strange looking problems during your deploys. It acts like there’s another package that didn’t get finished deploying and stop you.
  • Be mindful of the “Owner” property. It keeps track of who owns what modifications. It’s easy to wind up with orphans while you’re just learning how to do this, and you can hack up the web.config pretty good like that. If you end up fouling up your config settings like I did (Hey, I’m not an XPath guy!), check out Vincent Rothwell’s post on cleaning it up.
  • Brush up on XPath before you start executing this stuff.

Keep in mind that in this example I put the Update and Apply in the end just for the purpose of providing a complete example. In a real world scenario, you could use this method while you’re adding other modifications, but you wouldn’t want to save those mods until they are all added to the collection. 1 save per activation.

internal static void setErrorDetailSettings(SPWebApplication WebApp, string Owner, bool ShowErrors)
{

    SPWebApplication WebApp = siteCollection.WebApplication;
    SPServiceCollection services = WebApp.Farm.Services;
    SPWebApplicationCollection WebApps = services.GetValue<SPWebService>().WebApplications;

    string callStackValue = (ShowErrors) ? “true” : “false”;
    string customErroresValue = (ShowErrors) ? “Off” : “On”;

    SPWebConfigModification stackTraceModification =
        new SPWebConfigModification(“CallStack”, “configuration/SharePoint/SafeMode”);
    stackTraceModification.Value = callStackValue;
    stackTraceModification.Sequence = 1;
    stackTraceModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
    WebApp.WebConfigModifications.Add(stackTraceModification);

    SPWebConfigModification customErrorsModification =
        new SPWebConfigModification(“mode”, “configuration/system.web/customErrors”);
    customErrorsModification.Value = customErroresValue;
    customErrorsModification.Sequence = 1;
    customErrorsModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
    WebApp.WebConfigModifications.Add(customErrorsModification);

    WebApp.Update();
    WebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}

Categories: ASP.NET, MOSS, SharePoint 2007, c# Tags: