Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I followed the code example at How to: Create a Web Application-Scoped Timer Job. It creates a timer job that runs on a list in the root of the web application. However, I need to make the timer job run on a list that is located in a subsite.

I think that a way to do this is to use the [Persisted] attribute as explained in Creating Timer Jobs in SharePoint 2010 That Target Specific Web Applications (Wrox), but I have really struggled with how to get that to work.

Are there some code examples online that I haven't been able to find, that make this more clear? Or can someone write a code example that shows how to do this?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

A timer job that runs in the context of a web app (which is one of the two options (and the simplest)) has full access to the entire web app.

You you have to do to access a sub-site's list is refer to the site it is in, then find the subsite and finally the list.

Getting a site from a web app:

SPSite site = webApp.Sites[SiteName]

Setting a sub site from a site Site or subsite used to create the site object:

SPWeb web = site.OpenWeb();

Anything Else:

SPWeb web = site.OpenWeb(webUrl);

Get a site from a web (subsite):

SPList list = web.Lists[listName];

Safer:

SPList list = web.TryGetList(lsitName);
if(list != null)
{
//stuff...
}

If you need to use a list that exists in each site, then loop through the sites. If you need to access a list that exists in each subsite, loop through each site and subsite.

A timer job is simply a block of code that is registered, it can access anything the web app can access.

(Don't forget to .Dispose() your sites and webs or use using statements)

share|improve this answer
add comment

Another solution would be to directly consume SharePoint Service.

    public override void Execute(Guid targetInstanceId)
    {
           var dataContext = new TestDataContext(new Uri("http://url/sites/site/_vti_bin/listdata.svc/"));
            dataContext.Credentials = CredentialCache.DefaultNetworkCredentials;
            foreach (TaskListItem taskItem in dataContext.TaskList)
            {
                taskItem.Something = "else";
                dataContext.UpdateObject(taskItem);
            }
            dataContext.SaveChanges();
    }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.