Set a job variable to the last business day of the prior month

Language: C#

View on GitHub to download or comment.

See the User script help topic for additional information.

Samples index

This script can be run by an adTempus script task to set a Job Variable to the last business day of the month prior to when the script is run.

It sets the job variable "LastBusinessDayOfPriorMonth" to this date in yyyy-MM-dd format.

The script excludes Saturdays, Sundays, and holidays when looking for the last business day.

There are three versions:

  • Sample 1 uses the holiday set configured for the calling job. It does this by looking at the enabled schedule triggers for the calling job and taking the first holiday set it finds.
  • Sample 2 always uses a specified holiday set. In the example it's "Standard U.S. Holidays"; change the name if you use a different set.
  • Sample 3 ignores holidays. This version will work for you if you never have a holiday in the last 3 days of the month.
sample 1.cs
/*
This script finds the last business day (excludes weekends and holidays) of the month prior to the month when the script runs.
It sets the job variable "LastBusinessDayOfPriorMonth" to this date in yyyy-MM-dd format.

The script determines which holidays to use by looking at the enabled schedule triggers for the calling job and taking the first holiday set it finds.
If the calling job is not configured with a holiday set, holidays are ignored.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using ArcanaDevelopment.adTempus.ApplicationIntegration;
using ArcanaDevelopment.adTempus.Client;
using ArcanaDevelopment.adTempus.Shared;


namespace UserScript
{
    public class UserScript : ArcanaDevelopment.adTempus.ApplicationIntegration.UserScriptBase
    {
        public override Object Run()
        {
            //get the last business day of the prior
            var lastBusinessDayOfPriorMonth = GetLastBusinessDayOfPriorMonth();

            adTempus.JobVariables.Add("LastBusinessDayOfPriorMonth", lastBusinessDayOfPriorMonth.ToString("yyyy-MM-dd"));
            adTempus.LogMessage(MessageTypeEnum.Informational, 0, $"Set last business day to {lastBusinessDayOfPriorMonth:yyyy-MM-dd}");
            return 0;
        }

        private DateTime GetLastBusinessDayOfPriorMonth()
        {
            using (var connection = Scheduler.Connect(adTempus.JobVariables["ServerAndInstanceName"], LoginAuthenticationType.Windows, "", "")) //connect to the adTempus server. Use ServerAndInstanceName in case the script is being run on a named instance
            {
                //Create a DataContext to work in. All object operations take place within this context.
                //Use a Using block so the context is disposed when we finish with it
                using (var context = connection.NewDataContext())
                {
			              //get the last day of the previous month (1 day before first day of current month)
                    var lastOfPriorMonth = ArcanaDevelopment.adTempus.Shared.DateTimeHandling.FirstDayOfMonth(DateTime.Today).AddDays(-1);

                    //Get the holiday set used by the calling job
                    var holidaySet = GetHolidaySetForCallingJob(context);

                    DateTime[] holidayDates;

                    if (holidaySet == null)
                    {
                        //throw an exception here, or ignore holidays
                        //throw new Exception("No holiday set defined for job");

                        holidayDates = new DateTime[] { };
                    }
                    else
                    {
                        //get all holidays in the last 7 days, up to the end of the previous month
                        holidayDates = holidaySet.GetMatchingDates(lastOfPriorMonth.AddDays(-7), lastOfPriorMonth).Select(x => x.MatchingDate).ToArray();
                    }

                    var testDate = lastOfPriorMonth;
                    while (true)
                    {
                        if (testDate.DayOfWeek != DayOfWeek.Saturday && testDate.DayOfWeek != DayOfWeek.Sunday && !holidayDates.Contains(testDate))
                        {
                            return testDate;
                        }
                        testDate = testDate.AddDays(-1);
                    }
                }
            }
        }

        private SharedSchedule GetHolidaySetForCallingJob(ArcanaDevelopment.adTempus.Client.DataContext context)
        {
            var job = context.GetObject(new OID(ClassID.Job, Parameters.JobOID.GetValueOrDefault())) as Job;
            return GetHolidaySetForJob(job);
        }

        private SharedSchedule GetHolidaySetForJob(Job job)
        {
            var triggers = job.Triggers.Where(x => x.ClassID == ClassID.ScheduleTrigger).Cast();
            foreach (var trigger in triggers)
            {
                if (trigger.Enabled && trigger.Holidays != null)
                {
                    return trigger.Holidays;
                }
            }

            return null;
        }
    }
}
sample 2.cs
/*
This script finds the last business day (excludes weekends and holidays) of the month prior to the month when the script runs.
It sets the job variable "LastBusinessDayOfPriorMonth" to this date in yyyy-MM-dd format.

The script uses a fixed holiday set. Replace the name below if you don't use "Standard U.S. Holidays".

*/
using System;
using System.Linq;
using System.Collections.Generic;
using ArcanaDevelopment.adTempus.ApplicationIntegration;
using ArcanaDevelopment.adTempus.Client;
using ArcanaDevelopment.adTempus.Shared;


namespace UserScript
{
    public class UserScript : ArcanaDevelopment.adTempus.ApplicationIntegration.UserScriptBase
    {
        public override Object Run()
        {
            //get the last business day of that month
            var lastBusinessDayOfPriorMonth = GetLastBusinessDayOfPriorMonth();

            adTempus.JobVariables.Add("LastBusinessDayOfPriorMonth", lastBusinessDayOfPriorMonth.ToString("yyyy-MM-dd"));
            adTempus.LogMessage(MessageTypeEnum.Informational, 0, $"Set last business day to {lastBusinessDayOfPriorMonth:yyyy-MM-dd}");
            return 0;
        }

        private DateTime GetLastBusinessDayOfPriorMonth()
        {
            using (var connection = Scheduler.Connect(adTempus.JobVariables["ServerAndInstanceName"], LoginAuthenticationType.Windows, "", "")) //connect to the adTempus server. Use ServerAndInstanceName in case the script is being run on a named instance
            {
                //Create a DataContext to work in. All object operations take place within this context.
                //Use a Using block so the context is disposed when we finish with it
                using (var context = connection.NewDataContext())
                {
			              //get the last day of the previous month (1 day before first day of current month)
                    var lastOfPriorMonth = ArcanaDevelopment.adTempus.Shared.DateTimeHandling.FirstDayOfMonth(DateTime.Today).AddDays(-1);


                    var holidaySet = context.GetHolidaySet("Standard U.S. Holidays");
                    if (holidaySet == null)
                    {
                        throw new Exception("Holiday set not found");
                    }

                    //get all holidays in the last 7 days, up to the end of the previous month
                    var holidayDates = holidaySet.GetMatchingDates(lastOfPriorMonth.AddDays(-7), lastOfPriorMonth).Select(x => x.MatchingDate).ToArray();

                    var testDate = lastOfPriorMonth;
                    while (true)
                    {
                        if (testDate.DayOfWeek != DayOfWeek.Saturday && testDate.DayOfWeek != DayOfWeek.Sunday && !holidayDates.Contains(testDate))
                        {
                            return testDate;
                        }
                        testDate = testDate.AddDays(-1);
                    }
                }
            }
        }
    }
}
sample 3.cs
/*
This script finds the last business day (excludes weekends but not holidays) of the month prior to the month when the script runs.
It sets the job variable "LastBusinessDayOfPriorMonth" to this date in yyyy-MM-dd format.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using ArcanaDevelopment.adTempus.ApplicationIntegration;
using ArcanaDevelopment.adTempus.Client;
using ArcanaDevelopment.adTempus.Shared;


namespace UserScript
{
    public class UserScript : ArcanaDevelopment.adTempus.ApplicationIntegration.UserScriptBase
    {
        public override Object Run()
        {
          var lastBusinessDayOfPriorMonth = GetLastBusinessDayOfPriorMonth();

          adTempus.JobVariables.Add("LastBusinessDayOfPriorMonth",lastBusinessDayOfPriorMonth.ToString("yyyy-MM-dd"));
          adTempus.LogMessage(MessageTypeEnum.Informational,0, $"Set last business day to {lastBusinessDayOfPriorMonth:yyyy-MM-dd}");
                return 0;
        }
		private DateTime GetLastBusinessDayOfPriorMonth()
		{
			//get the last day of the previous month (1 day before first day of current month)
			var lastOfPriorMonth = ArcanaDevelopment.adTempus.Shared.DateTimeHandling.FirstDayOfMonth(DateTime.Today).AddDays(-1);
			var testDate = lastOfPriorMonth;
			while (true)
			{
				if (testDate.DayOfWeek != DayOfWeek.Saturday && testDate.DayOfWeek != DayOfWeek.Sunday)
				{
					return testDate;
				}
				testDate = testDate.AddDays(-1);
			}

		}
		
  }
}

Comments

View on GitHub to comment.