Create response to send notification email on job failure
This example uses the adTempus API to add a Notification Action to a job to send an email message when the job fails.
It also demonstrates how to create a Notification Recipient for an email recipient.
public void Main()
{
// if the adTempus server is on a different computer, replace "." with the server name
using (var session = Scheduler.Connect(".", LoginAuthenticationType.Windows, "", ""))
{
using (var context = session.NewDataContext())
{
// In this example we fetch a sample job.
var job = context.GetJob("Sample Job");
if (job == null)
throw new Exception("Job not found");
// create the Response
var response = (Response)context.CreateObject(ClassID.Response);
// Create the Event to trigger on job failed
var responseEvent = (ResponseEvent)context.CreateObject(ClassID.ResponseEvent);
responseEvent.Event = JobEvent.JobFailed;
response.Events.Add(responseEvent);
// find or create the recipient
var recipient = GetOrCreateNotificationRecipient(context, "[email protected]", "Someone");
// create a Notification Action
var action = (NotificationAction)context.CreateObject(ClassID.NotificationAction);
action.Recipients.Add(recipient);
// If you don't set a subject or message, the defaults are used.
// If you set them explicitly, use Job Variables to insert job name, computer name, etc., rather than
// hard-coding them. See the list of predefined variables
// action.NotificationSubject="Job %ADTJobName% failed on %ServerName%"
// action.NotificationMessage="The job failed"
// include Captured Console output
action.SendConsoleOutput = true;
response.Actions.Add(action);
job.Responses.Add(response);
job.Save();
}
}
}
// returns the existing NotificationRecipient for an email address, or creates a new one if none is found
public void GetOrCreateNotificationRecipient(ArcanaDevelopment.adTempus.Client.DataContext context, string emailAddress, string name)
{
var recipient = context.GetNotificationRecipientsForAddress(NotificationAddressType.SMTP, emailAddress).FirstOrDefault();
if (recipient != null)
// there's already a NotificationRecipient that uses this address
return recipient;
// otherwise create it
// recipient not found; create it
recipient = (NotificationIndividual)context.CreateObject(ClassID.NotificationIndividual);
recipient.Name = name;
var address = (NotificationAddress)context.CreateObject(ClassID.NotificationAddress);
address.AddressType = NotificationAddressType.SMTP;
address.RecipientAddress = emailAddress;
recipient.Addresses.Add(address);
recipient.Save();
return recipient;
}