Question

I am investigating the below code to make sure if its quality is as per Microsoft standards. Actually Comments came from Microsoft code reviewer that we need to create new SPSite Object within the elevated code in delegate. //ExtranetManager is my custom class

I Investigated and have tried to fix but i don't believe that anything wrong with this code. I want to take help from experts in this forum if any body can give good comment about that code or if there is something wrong within elevated privileges. Any comment can help me that may be i am missing.

public class MyTimerJob : SPJobDefinition
        {
           public override void Execute(Guid targetInstanceId)
            {
                SPWebApplication wa = null;

                  wa = (SPWebApplication)base.Parent;
                    SPSecurity.RunWithElevatedPrivileges(delegate
                    {
                        ExtranetManager extranetManager =
                          new ExtranetManager(wa);
                        extranetManager.StartSynchronization();
                    });
               }
        }
Was it helpful?

Solution

RunWithElevatedPrivileges only works if the current thread is using impersonation, i.e. IIS. Used in other code (timer jobs, console applications, workflow, etc.) it will have no effect. Colin is correct that by default the timer service runs as the farm service account specified in the Configuration Wizard. You can verify this in Windows Services.

Source

OTHER TIPS

The actual point is: there's no need at all to use SPSecurity.RunWithElevatedPrivileges in a job.
A job runs in OWSTIMER.exe, which uses the "SPFarm" account. "SPFarm" account has all privileges against all content DBs; it's seen as "system account" everywhere. So there's really no need to elevate its privileges at all.

However, as a side note, code inside SPSecurity.RunWithElevatedPrivileges must use new fresh SharePoint objects (i.e. new SPSite):

  • A new SPSite must be explicitely open from the elevated section, so its flagged with the elevated identity.
  • All SharePoint objects used inside the elevated section must come from that new SPSite, while it's kept open.
  • This new SPSite must be built and closed from the elevated section.
  • After it's closed, you can't use any of the "child" object anymore.

In the case of your code, and assuming it really needs an elevation context (i.e. let's assume it's not in a job as it actually is): the following code must open and close SPSite objects with respect to previous rules:

ExtranetManager extranetManager = new ExtranetManager(wa);
extranetManager.StartSynchronization();
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top