I’ve been working with some code that someone handed to me for a timer job. He hadn’t provided the actual feature activation code so I had to write it, of course. I took advantage of Andrew Connell’s famous blog post on the subject.
I’m using Visual Studio 2010 and deployment kept failing with an error “Error occurred in deployment step ‘Add Solution’: Object reference not set to an instance of an object.”
I was taking his code too literally. I was scoping the feature to the web application level, as shown:
As a result, the properties that are sent to the receiver are from the web application, not a site collection. In the end, the code looks like this:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{// Don’t do the following with web app scoped features, it leads to despair
// SPSite site = properties.Feature.Parent as SPSite;SPWebApplication wa = properties.Feature.Parent as SPWebApplication;
if (wa == null) throw new Exception("webapp2 is null.");
foreach (SPJobDefinition job in wa.JobDefinitions)
{try
{
if (job.Name == List_JOB_NAME)job.Delete();
}
catch (Exception e)
{
throw new Exception("marker 2");
} // catch exception e
}// install the job
WeatherForecastTimerJob weatherForecastTimerJob =
new WeatherForecastTimerJob(List_JOB_NAME, wa);SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 5;
weatherForecastTimerJob.Schedule = schedule;
weatherForecastTimerJob.Update();}
The key take-away is that when the feature is scoped to a web app, the SPFeatureReceiverProperties that SharePoint passes to your feature receiver has web app level parameters. Andrew’s old blog entry assumes it’s scoped to the site collection.
</end>
Follow me on Twitter at http://www.twitter.com/pagalvin