0
votes

I am new to SharePoint so I am following some Microsoft Learning Guides. One exercise is to create a feature reciever to modify the Web.Config file. I detect the feature being activated or deactivated and call the following routine with the appropriate flag.

void setProliferationFlag(bool status)
{
    SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://SharePoint"));
try
{
    SPWebConfigModification mySetting = null;
    if (status)
    {
    mySetting = new SPWebConfigModification();
    mySetting.Path = "configuration/appSettings";
    mySetting.Name = "add [@key='preventProliferation'] [@value='1']";
    mySetting.Sequence = 0;
    mySetting.Owner = "Lab05Owner";
    mySetting.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    mySetting.Value = "<add key='preventProliferation' value='1' />";
    webApp.WebConfigModifications.Add(mySetting);
}
else
{
    foreach (SPWebConfigModification modification in 
        webApp.WebConfigModifications)
    {
        if (modification.Owner == "Lab05Owner")
        {
            modification.Value = "<add key='preventProliferation' value='0' />";
        }
    }
}
    webApp.Update();
    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
catch
{ 
}

The event receivers work fine. When I activate the feature this code is run, but when it reaches the "webApp.Update()" line it fails with an "Access Denied" error. No other detils on the error. I am not sure to what the access is denied. I am running in my development environment on my laptop. This is a Sharepoint Server 2010 installation on Window 7.

Regards Tim

1
first of all: get a decent stacktrace --> change the web.config by setting customerrors to ` <customErrors mode="RemoteOnly" />` en callstack to CallStack="true". From which account are you activating the feature? More important; which rights does this account have..Tjassens

1 Answers

1
votes

Most likely you will need administrative access. Look at the SPSecurity.RunWithElevatedPrivileges method which allows you to execute such actions within the system account's security context.

You will have to run the whole code elevated, that is including opening the SPWebApplication object. You method will then look like this:

void SetProliferationFlag(…)
{
    SPSecurity.RunWithElevatedPrivileges(() =>
    {
        // … your code goes here …
    });
}

Please also note, it's a very bad practice to have empty catch clauses in your code. Do always handle all exceptions, at least by logging them and rethrowing.