Dynamics 365 Finance and supply chain – X++ code to fetch open calendar days

One thing I like about coding in X++ is that we can reuse API’s and standard classes to perform a complex task. We do not need to reinvent the wheel and best way to do is to find any standard process and reuse the existing methods.

One such example is to find number of open days in a calendar setup between a date range. So you have a start date and end date and a calendar ID and you want to find which days are open in the calendar setup lines.

Instead of writing your own X++ SQL statement to understand table relations and loop through work calendar setup lines, there is a standard class which has this method built in and we can call it to find if a particular day is open in calendar or not.

This method also uses a global cache to lookup the setup and can be fast then writing SQL statements and pulling data directly from the database.

One example of using this method is shown below : Here we have a fromDate, toDate and Calendar ID. All we need to do is loop through the dates and call this method and we can then insert it into a map which can then be used in further logic.

   protected Days findOpenDates(
        TransDate   _fromDate,
        TransDate   _toDate)
    {
        CalendarId          calendarId;
        TransDate           calendarValidTo;

        TransDate           loopDate;

        Days                numOfOpenDays;

        WorkCalendarSched workCalendarSched = new WorkCalendarSched(true);

        for (loopDate = _fromDate; loopDate <= _toDate; loopDate++)
        {
            if ( ! calendarId
                || calendarValidTo < loopDate)
            {
                [calendarId, calendarValidTo] = this.calendar(loopDate);
            }

            if (workCalendarSched.isDateOpen(calendarId,loopDate))
            {
                if (mapAllDemand)
                {
                    mapAllDemand.insert(loopDate,0);
                }
                numOfOpenDays++;
            }
        }

        return numOfOpenDays;
    }

As X++ developers we should leverage standard API’s instead of reinventing the whole wheel. Thanks for reading the blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.
%d bloggers like this: