Custom SPJobDefinition and “Access denied” Error

October 22 2010 121 comments

I found Stef Van Hooijdonk’s post when trying to install a custom timer job and having the “Access denied” -issue. I tried Stef’s workaround by running the powershell -script he provided and got my custom timer job to install via web scoped feature’s feature receiver.

I think there are issues to consider though. Do we want to permanently set the RemoteAdministratorAccessDenied false or do we want to run one script to set RemoteAdministratorAccessDenied false before feature activation/deactivation and after that run another script to set it back true again? Installing custom timer job evidently is an operation where Farm Admin privileges are needed and if the activator is web- or site-scoped feature, the activation dialog (the Activate/Deactivate-buttons in ManageFeatures.aspx) is available also for users with inadequate privileges. After further investigation it seems that to activate a feature from content application’s feature management UI, it is necessary to have the same application pool accounts for the content application and central admin – it seems not to be enough to be logged on to your content web app with farm admin account or with the central admin’s application pool account. The behavior is a little weird but at least when I tested different scenarios, this is how it appears to be. To have same application pool account in Central Admin and content web app, however, is not recommended.

Nevertheless, I needed a custom timer job to be installed from a web scoped feature because the timer job handles information per web. Therefore the name of the installed timer job is per web and properties to determine which web should be handled when timer job ticks are also added to the timer job’s properties.

So, I took the idea from Stef’s post and used the same idea in my feature receiver and by doing so I don’t have to run the powershell-script per environment before feature activation:

public class MyFeatureReceiver : SPFeatureReceiver
{
    private const string MyCustomTimerJobName =
        "Custom Timer Job for web: {0}";

    public override void FeatureActivated(SPFeatureReceiverProperties
        properties)
    {
        using (var web = properties.Feature.Parent as SPWeb)
        {
            if (web == null) return;

            // THE ORIGINAL VALUE OF REMOTE ADMINISTRATOR
            var remoteAdministratorAccessDenied =
                SPWebService.ContentService.
                RemoteAdministratorAccessDenied;
            try
            {

                // SET THE REMOTE ADMINISTATOR ACCESS DENIED FALSE
                SPWebService.ContentService.
                    RemoteAdministratorAccessDenied = false;
                // delete the custom timer job if it exists
                var app = web.Site.WebApplication;
                foreach (var job in
                    app.JobDefinitions.Where(job =>
                        job.Name == string.Format(MyCustomTimerJobName,
                        web.Url)))
                {
                    job.Delete();
                }
                // install the custom timer job
                var schedule = new SPMinuteSchedule
                {
                    BeginSecond = 0,
                    EndSecond = 59,
                    Interval = 5
                };
                var myTimerJob =
                    new MyTimerJob(
                        string.Format(MyCustomTimerJobName,
                        web.Url), web.Site.WebApplication,
                        null, SPJobLockType.Job)
                        { Schedule = schedule };
                // add properties to determine which site and web
                // the timer job handles
                myTimerJob.Properties.Add("site-id", web.Site.ID);
                myTimerJob.Properties.Add("web-id", web.ID);
                myTimerJob.Update();

            }
            finally
            {
                // SET THE REMOTE ADMINISTATOR ACCESS DENIED BACK WHAT
                // IT WAS
                SPWebService.ContentService.
                    RemoteAdministratorAccessDenied =
                    remoteAdministratorAccessDenied;
            }
        }
    }

    public override void FeatureDeactivating(SPFeatureReceiverProperties
        properties)
    {
        using (var web = properties.Feature.Parent as SPWeb)
        {
            if (web == null) return;

            // THE ORIGINAL VALUE OF REMOTE ADMINISTRATOR
            var remoteAdministratorAccessDenied =
                SPWebService.ContentService.
                RemoteAdministratorAccessDenied;

            try
            {
                // SET THE REMOTE ADMINISTATOR ACCESS DENIED FALSE
                SPWebService.ContentService.
                    RemoteAdministratorAccessDenied = false;
                // delete the custom timer job if it exists
                var app = web.Site.WebApplication;
                foreach (var job in
                    app.JobDefinitions.Where(job =>
                        job.Name == string.Format(MyCustomTimerJobName,
                        web.Url)))
                {
                    job.Delete();
                }
            }
            finally
            {
                // SET THE REMOTE ADMINISTATOR ACCESS DENIED BACK WHAT
                // IT WAS
                SPWebService.ContentService.
                    RemoteAdministratorAccessDenied =
                    remoteAdministratorAccessDenied;
            }
        }
    }
}

The idea is that remote administration is allowed (SPWebService.ContentService.RemoteAdministratorAccessDenied = false) for the period of time the custom timer job is either installed (activated) or deleted (deactivated) and it’s set back to what it was at the end.

Below is a custom timer job stub just to make the point complete:

public class MyTimerJob : SPJobDefinition
{
    public MyTimerJob()
    {
    }

    public MyTimerJob(string name, SPService service, SPServer server,
        SPJobLockType lockType)
        : base(name, service, server, lockType){}

    public MyTimerJob(string name, SPWebApplication webApplication,
        SPServer server, SPJobLockType lockType)
        : base(name, webApplication, server, lockType){}

    public override void Execute(Guid targetInstanceId)
    {
        if (!Properties.ContainsKey("site-id") ||
            !Properties.ContainsKey("web-id"))
            return;

        var siteId = (Guid)Properties["site-id"];
        var webId = (Guid)Properties["web-id"];

        using (var site = new SPSite(siteId))
        {
            using (var web = site.OpenWeb(webId))
            {
                // do your deeds
            }
        }
    }
}

I made my feature hidden only to be activated via scripting to be sure no one would try to activate the feature from my content web application’s UI.

The sample about creating custom timer jobs in msdn (also linked in Stef’s post) article installs the custom timer job via WebApplication-scoped feature. I think timer jobs are only meant to be installed in Central Admin’s context but then how could you fluently develop timer jobs that handle something in your content applications if you can’t install timer jobs per site or web.

The workaround is however something I would’t have wanted to find out, nor use, so use it with your own risk.

Popularity: 7% [?]

121 comments to “Custom SPJobDefinition and “Access denied” Error”

  1. Levana Baby says:

    I believe what you said was very logical. However, what about this?

    suppose you were to create a awesome headline? I ain’t suggesting your information is not good, however what if you added
    something to maybe grab folk’s attention? I mean Custom SPJobDefinition and “Access
    denied” Error | SharePoint Blues is kinda boring. You might peek at
    Yahoo’s home page and see how they create post titles to get people to click.

    You might try adding a video or a pic or two to grab people excited about what
    you’ve written. In my opinion, it might bring your posts a little bit more interesting.

  2. I don’t even knoѡ how I ended uρ Һere, but Ӏ assumed tһiѕ рut սр ѡaѕ once ɡreat.
    Ⅰ ԁο not understand ԝҺօ үߋu’гᥱ but definitely уߋu’ге ǥoing
    tto а famous bloogger should үߋu arе not already.
    Cheers!

    Ⅿү blog post … Clickbank University Review

  3. xmas xxx says:

    each time i used to read smaller posts which as well clear their
    motive, and that is also happening with this post which I am reading now.

  4. Always remember, though, when it comes to this blog, that right
    now there isn’t really one right path or plan. Don’t think that you have to
    continue seeking a certain method of accomplishing things when you aren’t getting the outcomes you want.
    Who else can easily determine just what is best suited for
    you aside from you? Don’t, on the other hand, disregard an idea that looks like it’s weird or maybe challenging to find out.
    When you have the daring to test anything fresh, whether or not it’s really a problem, you might benefit when you are qualified to
    have a nearer look at your fundamental thinking and chronic actions.
    That’s the key reason why it is beneficial to look over a
    variety of sources any time trying to get assistance.
    When what you are doing your exploration, here are two web sites that you might find
    useful, us and us. You will find it less difficult to locate responses that happen to be best for
    you if you take into account the numerous points of view of others.

  5. nipples says:

    Pretty! This was an incredibly wonderful article. Thank you for supplying this information.

  6. Hey there! I could have sworn I’ve been to this website before but after reading through some of the post I
    realized it’s new to me. Anyways, I’m definitely delighted I found it and I’ll be book-marking and
    checking back often!

  7. You actually maкe it seem sо eаѕу ᴡіth үօսr ρгᥱsentаtiⲟn but Ι fіnd tһіѕ toріc tߋ
    Ƅе гeallʏ sοmetҺіng
    tһat Ӏ tɦіnk I ᴡοᥙⅼԀ
    neѵeг սndeгѕtɑnd.
    Ӏt ѕеemѕ tօо
    cоmρⅼicɑtеɗ аnd еxtrеmеⅼу broad fοr mе.

    ӏ’m loокіng fοгԝarԁ fоr
    уоᥙг neҳt рoѕt, І ѡіⅼl tгʏ tߋ get tһe ɦang of іt!

    mу աеƄ ⲣaǥе – astrology & spirituality

  8. leasa biil scania
    leasa bil privat voilvo xc60

    The agent makes particular the rent is collected
    regularly as well issues receipts on your behalf.

    A car is referred to as one of the most expensive investments that one could make
    associated with or hher lifetime.

    leasa bil trots betalningsanmärkning
    leasa bil jeepleasa ut bil

  9. This article provides clear idea in favor
    of the new users of blogging, that inn fact howw to do
    blogging.

  10. It’s in fact very difficult in this active life to listen news on Television, therefore I just use internet for that purpose, and take the most up-to-date news.

  11. make money says:

    I tһink tһe admin օf thіs website іs аctually ᴡorking ɦard іn support
    оf һіѕ web site, beccause hhere еᴠery stuiff іs quality based data.

    Ꭲake a ⅼoⲟk ɑt mү web site:
    make money

  12. I get pleasure from, lead to I discovered just what I
    used to be having a look for. You have ended my four
    day lengthy hunt! God Bless you man. Have a nice day.
    Bye

  13. TҺank you a bunch for sharing tҺіs աith all people үοu гeally ҝnoա
    ѡɦat yоu аге speaking approximately!
    Bookmarked. Kindly additiobally discuss wikth my site =).
    Wе աill ɦave a link trade contract among ᥙѕ

    Also visit mmy webpage: everstryke matches

  14. In the kitchen, several urgers weге ѕent baack fοr
    imoroper cooking. ᗷut ѡhen уօu usе ɑ
    Tactical approach tο ǥet girls, іt Ьecomes surprisingly easy tо make tһеm feel attraction and pick tһеm սр.
    TҺiѕ iis because suchh bar code labels Һave Ƅoth
    machine- аnd human-readable identifiers.

    Аlso visit mʏ web site; 54th street bar and grill irving texas

  15. The skills and experience levels of the developers are not that important.
    At the event, which is open to the public, the limited-edition “This Is Not
    A Shirt” T-shirt will go on sale for $20 — with 100% of the sales
    price going to local high schools and Haiti rebuilding efforts.
    The royal couple were in the area taking in some sites when they chose to
    stop in to catch a game at the Barclays Center.

  16. It is self contained and is equipped with cold annd hot watdr ɑѕ peer thᥱ neeԀ ⲟf thе uѕᥱr.
    When people try tο absorb too much information all ɑt οnce,
    their brains саn Ьecome overwhelmed.

    Ԝhen tҺе redo waas completed, Jon met tɦе staff оutside tο unveil
    thᥱ neѡ namе, аnd
    it ԝɑѕ noԝ Pacific Coast Wine Barr
    and inside thhe wine disolay աɑs breathtaking.

    Αlso visit mү blog: lipstick alley tea les twins

  17. My brоthег геcоmmеndеԀ Ι ԝοulɗ ρоssiЬly lікᥱ tɦіs ѡebѕіtе.
    Ꮋᥱ աаѕ tⲟtaⅼⅼү rіɡҺt.

    Ꭲһіѕ ⲣuЬlіѕɦ actսaⅼⅼу maɗе mү
    ɗаʏ. Үⲟս ϲann’t сօnsiԁег ϳuѕt ɦow mսcɦ
    tіmе Ӏ Һаԁ ѕρеnt fοг tһіs іnfⲟrmɑtіοn!
    Ꭲһanks!

  18. Porn Videos says:

    Ꮋi there, I enjoy reading alll off your article.
    Ι ⅼike tߋ ѡrite а little comment
    tߋ support yоu.

    Takee a ⅼοοk at mʏ web site:
    Porn Videos

  19. obviously like your web-site however you need to test the spelling on several
    of your posts. Many of them are rife with spelling
    issues and I to find it very troublesome to inform the
    reality nevertheless I will surely come back again.

  20. What about sales? If you http://www.purpleweddinginvitations.org/cart/invitation/256737664192067200 sold something for 1 dollar, does that exempt it?

  21. Dwight Lelis says:

    Hi, regarding click-bank – do you have ideas about improving sales on a varied webpage? I have a file sharing webpage and as such it is very to match offers to the visitor. Best wishes

Leave a Reply