Delete or delete the calendar rule "Time Disabling Rule" through a plugin or simple console application in C # for CRM 2015

I have the following problem:

I need to remove or remove the “disconnect rule” from the calendar rules of a specific calendar belonging to the “Equipment”. This must be done so that the equipment is available for planning in Service Calendar.

Somehow I can’t figure out how to do this.

I can get the calendar rule object that needs to be deleted, but the next step eludes me.

Please be so kind as to tell me:

  • Is it possible to do this using C # (SDK)

  • Any web resource or piece of code that does something similar.

The following code gives me an 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); } } 
+5
source share
1 answer

You are almost there. You must delete the calendarrules collection and update the calendar object.

 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); } } } 

a source

0
source

All Articles