Code Snippet – Change Calendar Start Date

Recently I created a Customer Service Schedule Calendar where I had to calculate durations for work hours including those prior to the date I created the Calendar

To my dismay I discovered the TimeBlocks returned by the ExpandCalendarRequest only started at the time the Calendar was created and no earlier. This meant calculations for work hours prior to the date were not counted

Upon investigation turns out a field Start date within the Calendar Rules for the calendar are what restrict this period for the calendar. The C# script below updated this to earlier in the Calendar Rules and fixed my problem

//replace this with your calendar id
var calendarId = new Guid("5CD816C1-FB2D-EB11-A813-000D3A569254");

var startDate = new DateTime(1910, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var calendar = xrmService.Retrieve("calendar", calendarId);
var calendarRules = calendar["calendarrules"] as EntityCollection;
foreach (var calendarRule in calendarRules.Entities)
{
    calendarRule["starttime"] = startDate;
}
xrmService.Update(calendar);

Leave a comment