Custom SPJobDefinition and “Access denied” Error

October 22 2010 157 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: 10% [?]

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

  1. Il en de meme pour les differents accessoires pour au lave vaisselle that is regulierement to babycook comme spatules, bols et petits:
    mieux vaudra laver a la utilisant savonneuse plutot que de les trop qui aurait pour de les abimer plus rapidement.

  2. Hi! I know this is somewhat offf topic but I was wondering if
    you kne where I could fiond a captcha plugin for my comment form?
    I’m using the samee blog platform as yours and I’m having problems finding one?
    Thanks a lot!

  3. This post will assist the internet people for setting up new blog or even a blog from start
    to end.

  4. Hurrah, that’s what I was searching for, what a material!
    existing here at this website, thanks admin of this website.

  5. I constantly spent my half an hour too read this website’s posts all the time along with a cup of coffee.

  6. san choi says:

    Hi outstanding blog! Does running a blog like this take a great deal of work?
    I’ve no expertise in programming however I had been hoping to start
    my own blog soon. Anyhow, should you have any suggestions or techniques for new blog
    owners please share. I understand this is off subject however I simply wanted to ask.
    Thanks!

  7. Truly no matter if someone doesn’t understand after that
    its up to other users that they will assist, so here it happens.

  8. magnificent publish, very informative. I wonder why the opposite specialists of this sector do not understand
    this. You must continue your writing. I am confident, you have a great readers’ base already!

  9. It’s awesome in favor of me to have a web page, which is beneficial for my knowledge.
    thanks admin

  10. Sadie says:

    Slowly pll your knees into your chest, maintaining them bent at 90 degrees, till your buttocks flat
    stomach diet and workout plan (Sadie) tailbone come off the floor.

  11. pinkly says:

    You play a special force combatant, the sole survivor
    who has to survive and kill all zombies and escape the streets.
    Tickets for the taping are already sold out, so fans will have to
    tune in to ABC to watch the performance. The online
    point-and-click scary games online are truly creepy, because you never know what will happen when you reach
    the end phase.

  12. tarot says:

    The Emperor prefers the traditional relationship, one
    that has strong foundations in traditional values and conventional structures.
    Before I bought my first deck I decided that I would only be
    able to afford one, so I was going to get the prettiest one I could
    find. And as time elapsed, it has become a tool for predicting the future including the
    different aspects in one’s life like love, career, and relationships.

  13. Within the Cpa Affiliate Marketing Training Commission Machine program, you may be taught by
    Andy Anand and his accomplice Bilpy Darr.

  14. Producers familiarize their products and services according to the requirements of various economies
    thereby tapping the untapped markets.

  15. It’s amazing in favor of me to have a website, which is useful designed for my knowledge.
    thanks admin

  16. Good way of describing, and pleasant piece of writing to
    take information about my presentation subject matter, which i
    am going to deliver in university.

  17. Alexander says:

    Currently it looks like Expression Engine is the best blogging platform
    out there right now. (from what I’ve read) Is that what you’re using on your
    blog?

  18. It’s genuinely very difficult in this full of activity life
    to listen news on Television, thus I only use world wide
    web for that reason, and take the most up-to-date news.

  19. Earl says:

    Hi my loved one! I wish to say that this post is amazing,
    great written and come with almost all vital infos.
    I’d like to see extra posts like this .

  20. The Ancient mom had experienced the Bless..

  21. Hi, everything is going well here and ofcourse every one is
    sharing facts, that’s in fact excellent, keep up writing.

    my blog – Despicable Me Minion Rush Cheats

  22. If you are going for best contents like myself, only visit this website all the
    time since it offers quality contents, thanks

  23. I think this is among the most vital info for me.
    And i’m glad reading your article. But should
    remark on few general things, The website style is ideal, the articles is really great :
    D. Good job, cheers

    My homepage Asktheexpats.movehub.Com

  24. If they are, you’re in normal ketosis – identical
    to the ketosis of wholesome people who keep on with a strict low carb weight loss
    program.

  25. Wate is one oof the most necessary elements in our life.
    It was still a tremendous undertaking to return their homes to their former state.
    Whether it is after a fire, burst pipes, or the result of a flood, your home must bee restored from
    all the destruction caused by moisture.

  26. obviously like youyr website however you have to
    check the spelling on quite a few of your posts. A number of them
    are rife ith spelling problems and I find it very bothersome
    to tell the truth nevertheless I’ll surely come back again.

  27. unitfx says:

    S, was one of the biggest fraudsters on the individual as
    well as institution basis in our history. Numismatic coins are more rare and highly collected coins.
    You do not have to go to the country in order to invest in their currency as well as their commemorative coins.

  28. Clinical experience and scientific studies are confirming that
    these therapies are successful and safe when facilitated by trained, experienced,
    professional practitioners. The above mentioned avenues for study material will help you out in every question and
    answer all your doubts. Google intends to market a self-driving car to the public within 5 years.

  29. Odell says:

    I obtained my reading several minutes later and a message from my uncle about
    a certain occasion that took place to me at age 8.

    My blog Odell

  30. my site says:

    I’d like to thank you for the efforts you have put in penning this site.
    I am hoping to view the same high-grade blog posts from you
    later on as well. In fact, your creative writing abilities has inspired me
    to get my own, personal blog now ;) by Facebook

  31. Hurrah! Finally I got a web site from where I be able to actually get useful
    data concerning my study and knowledge.

  32. Thank you for sharing!

  33. I am not positive the place you’re getting your information, but good topic.
    I must spend a while finding out more or figuring out more.
    Thanks for great information I was on the lookout for this information for my mission.

  34. energy rates says:

    This will save them a lot of money which they can usse for their other expenses.
    People now have the power to select which practices they can do to save energy.
    We can soon get caughtt in a vicious cycle when it comes to bills,
    earning just enough money to pay them off each month.

  35. hemos abierto un comparador de precios de salvaescaleras y ascensores,
    Si lo probais nos haceis un favor, calcula muy bien el precio o el presupuesto basado en diferentes compañías de elevacion

  36. Installing When installing a wireless network card, ensure that you read the documentation prior to
    installing, most cards need to hae the software installed before
    the card is connected or plugged in, otherwise
    the software drivers may fail to lopad properly or
    Windows will attempt to locate a driver from
    elsewhere, giving configuration issues. Nowadays, it is difficult
    to carry heavy caah everywhere, so pople believe in makikng credit
    card payments. This special account will cconfer professional merchant status and allow you to
    collect credit payments inn a timely manner instead of working
    through a time-consuming billing process that
    may render less fruitful results.

  37. As soon as you are done growing the title, logo, biography, and internal product,
    you’ll need tto create different graphics to advertise your company.

    Feel free to syrf to my web blog :: information Products Income (http://www.sleepy.tw)

  38. Charmain says:

    excellent Blog I am a massive bet365.com fan from Sweden

  39. There are companies that offer pool services including pool cleaning, pool opening and winter closing service,
    equipment installation aand even repairs for malfuncftioning equipment and other damages.

    Thus, it is vital that convert the combined chlorine back to free chlorine
    once 7 days. Aesthetic Looks ‘ They have an amazing
    appearance that attracts the onlookers.

  40. skybet says:

    I am regular visitor, how are you everybody? This paragraph posted at this web page
    is in fact nice.

  41. Finger Steps could probably serve as the stress tool for
    most stressed sales managers. For any new skill set you
    are learning, you need a basic foundation. The driving force
    behind the company is the desire to constantly develop
    more versatile opportunities for outdoor fitness for everyone to get the most out of the experience.

  42. When some one searches for his necessary thing, thus he/she desires to be available that in detail,
    thus that thing is maintained over here.

  43. Tandy says:

    Party pills are kniwn as “natural power”, “herbal highs”, and “dance pills”.

    Backbone aand other bones begin to form. Magnesium
    carbonae used to bbe used, but it has mostly been rdplaced with sodiumferrocyanide as
    another anti caking agent.

  44. voyance sms says:

    Hello, yeah this piece of writing is genuinely pleasant
    and I havve learned lot of things feom it on the topic of blogging.

    thanks.

  45. Fine way of explaining, and nice article tο
    ɡеt data concerning my presentation focus,
    &#7457hich i аm ɡoing tߋ
    deliver іn institution ߋf ɦigher education.

    &#5047ү ρage … online jewellery shopping

  46. I am sure tɦіѕ piece oof writing
    &#1211as touched ɑll thе internet viewers,іtѕ гeally гeally nice post οn building ս&#11427 nnew website.

    Check &#11423ut my web site: online dress shopping

  47. Hmm iѕ anyone else experiencing &#1088roblems
    wjth tɦe pitures &#1086n thijs blog loading?
    ӏ’m trying tߋ find οut
    іf its ɑ ρroblem oon mү
    еnd օr іf іt’sthe blog. Αny feedback would ƅе ǥreatly appreciated.

    Feel free tߋ visit mу site:
    make money fast

  48. Pretty component tο content. I justt stumbled սpon ʏօur web sitee and
    in accession capital tо claim tҺat
    I acquire іn fɑct loved account үour blog posts.
    Anyway Ӏ &#7457ill b&#6513 subscribing fοr yߋur feeds οr eѵеn І achievemeent ʏօu ցеt admission t&#11423
    persistently fast.

    Feel free tο surf tо mу web site :: everstryke match instructions

  49. This is a great scary movie to watch with your main squeeze.

    The little notes with each exercise add a different twist since
    they are personal to Sly, such as him telling us that Carl Weathers,
    aka Apollo Creed, taught him the hammer curl. When choosing an online movie rental site to
    join its important to do a certain amount of research first.

  50. web page says:

    It’s awesome to pay a visit this site and reading the views of
    all mates regarding this piece of writing, while
    I am also eager of getting know-how.

Leave a Reply