Solution: Accessing SharePoint Site or WebApp via Code Returns Null
A colleague of mine recently developed a timer job for SharePoint. The job worked fine on his developer and test machines but when he tried to activate it in the pre-production environment things went downhill.
An exception was thrown as soon as the timer job attempted to access the web application to add the timer job, ie. in this line of code:
The exception thrown was the good old “Object reference not set to an instance of an object” and further investigation showed that SPContext returned Null. Accessing the web application by referencing it directly (eg. SPWebApplication wA = SPWebApplication.Lookup(new Uri(http://site)); ) did not make a difference.
Coincidentally, the following error showed up in the event log: “Error in the site data web service”. This error mostly surfaces when SharePoint search chokes in a 32 bit environment due to large lists or inefficient use of memory capacity (heap fragmentation).
Restarting the below-mentioned services (net start/stop) fixed the problems for us:
net stop "Office SharePoint Server Search"
net start "Office SharePoint Server Search"
net stop "Windows SharePoint Services Search"
net start "Windows SharePoint Services Search"
net stop "Windows SharePoint Services Administration"
net start "Windows SharePoint Services Administration"
net stop "Windows SharePoint Services Timer"
net start "Windows SharePoint Services Timer"