I am working on a little app to run some timer jobs in SharePoint.
Instead of just using a foreach to loop through all the jobs and pick the ones I want, I am attempting to select them by Guid via Linq statements. However, I am not having much luck.
Here is what I have so far:
foreach (SPService service in centralAdmin.Farm.Services)
{
var traceJob =
from jobDefinition in service.JobDefinitions
where jobDefinition.Id == traceGuid
select jobDefinition;
SPJobDefinition jobInfo = traceJob as SPJobDefinition
Console.WriteLine(jobInfo.DisplayName);
}
EDIT The error I am receiving is a “NullReferenceException” at Console.WriteLine(jobInfo.DisplayName)
I am sure I have just missed something since this is my first time using LINQ statements, but I have not been able to figure out what I did wrong. I cast traceJob as SPJobDefinition because otherwise I cannot access any of the SPJobDefinition properties off of traceJob. Any tips or pointers would be very much appreciated!
EDIT
the enumeration yields no results when searching for the Guid.
However, if I do the following code:
foreach (SPJobDefinition jobDefinition in service.JobDefinitions)
{
if (jobDefinition.Id == traceGuid)
{
jobDefinition.RunNow();
Console.WriteLine(jobDefinition.DisplayName);
}
}
It will pull back exactly what I expect to see- the Job Definition’s display name. This would seem indicate that the issue is not with a faulty Guid or non-existent job.
The exception you’re getting is because your
asoperation will always fail, and when anasfails it doesn’t throw an exception, it just returns null. The exception comes from using that null value.traceJobshouldn’t need to be cast at all. Usingvardoesn’t mean it’s actually of a variable type, or even unknown at all. It simply means that the compiler will look at the expression to the right of the=and use that (statically, at compile time) to determine the type of that variable. In this case, hovering overvarwill show you that it is actually anIEnumerable<SPJobDefinition>. What you have is a sequence of job definitions, not just a single one. You can easily get the first item in the sequence throughFirst,FirstOrDefault,Single, orSingleOrDefault. After doing that you’ll have just one item, and you won’t need to cast it at all.