1
votes

Which is the best way to reference current site/web in sharepoint specially for Timer Jobs from the examples given below and why?

Example1:

SPWebApplication webApp = this.Parent as SPWebApplication; SPWeb oWeb = webApp.Sites[0].RootWeb;

OR

Example2:

using(SPSite site=new SPSite(SPCOntext.Current.Web.Url)){ using(SPWeb web=site.OpenWeb()){

} }
1
Please mark my answer if this helped youAndreas

1 Answers

2
votes

there is no SPContext.Current available inside a TimerJob so that isn't an option. Your example 1 would be an option, however I've been working with an other workaround.

When you deploy your timerjob by code and activate them with a specific schedule, you can set TimerJob properties which than can be read when the "Execute" method is called.

Here is the code I'm using in one of our solutions inside a SPWebApplication feature:

var webApplication = (SPWebApplication) properties.Feature.Parent;
var newTimerJob = new new MyTimerJob("Timerjobname", webApplication);
newTimerJob.Properties.Add("key", "url");
newTimerJob.Schedule = schedule;
newTimerJob.Update();

The Execute Method than can contain something like this:

if (Properties["key"] != null && Properties["key"].ToString() != string.Empty)
        { var mySite = new SPSite(Properties["key"].ToString()); }