5

I have the following problem:

I need to delete or remove "Time Off Rule" from Calendar Rules of a particular calendar belonging to an "Equipment". This needs to be done so that the equipment is available for scheduling on Service Calendar.

Somehow I cannot understand how to do it.

I am able to retrieve the Calendar rule object which needs to be deleted but the next step eludes me.

Please be kind enough to let me know:

  1. Can it be done through C#(SDK)

  2. Any web resource or portion of code which does something similar.

The following code gives me the error

The object you tried to delete is associated with another object and cannot be deleted.

//equip is of Equipment type and is already initialized 
CrmEarlyBound.Calendar cal = (CrmEarlyBound.Calendar)svc.Retrieve("calendar", equip.CalendarId.Id, new ColumnSet(true));
Console.WriteLine("Got the user calendar");
List<CalendarRule> calendarRules = cal.CalendarRules.ToList();
Console.WriteLine("Got the calendar rules " +  cal.CalendarRules.ToList().Count);
foreach (CalendarRule cr in cal.CalendarRules)
{
   if (cr.Description == "Time Off Rule" && cr.StartTime.Value>=DateTime.Now)
   {
       Console.WriteLine(cr.StartTime);
       Calendar calI = (Calendar)svc.Retrieve(cr.InnerCalendarId.LogicalName, cr.InnerCalendarId.Id, new ColumnSet(true));
       //svc.Delete(cr.InnerCalendarId.LogicalName, cr.InnerCalendarId.Id);
    }
 }
jasonscript
  • 6,039
  • 3
  • 28
  • 43
Sudeep
  • 343
  • 5
  • 12

1 Answers1

0

You are almost there. Have to remove the calendarrules collection & update the calendar entity.

public static void ClearCalenderRules(IOrganizationService service, Guid bookableResourceId, DateTime startDate, DateTime endDate)
{
    using (var context = new CrmServiceContext(service))
    {
        var bookableResource = context.BookableResourceSet.Where(b => b.Id == bookableResourceId).FirstOrDefault();

        if (bookableResource?.CalendarId != null)
        {

            Entity entity = service.Retrieve("calendar", bookableResource.CalendarId.Id, new ColumnSet(true));
            EntityCollection entityCollection = (EntityCollection)entity.Attributes["calendarrules"];

            int num = 0;
            List<int> list = new List<int>();
            foreach (Entity current in entityCollection.Entities)
            {
                DateTime dateTime2 = Convert.ToDateTime(current["starttime"]);
                if (dateTime2 >= startDate && dateTime2 <= endDate)
                {
                    list.Add(num);
                }

                num++;
            }

            list.Sort();
            list.Reverse();

            for (int i = 0; i < list.Count; i++)
            {
                entityCollection.Entities.Remove(entityCollection.Entities[list[i]]);
            }

            entity.Attributes["calendarrules"] = entityCollection;
            service.Update(entity);
        }
    }
} 

source