Sample Code to Cancel All the Open Activities for a particular record in CRM 2011.


Just sharing a sample code that could be used to cancel all the open activities for a particular record.

 private void CancelChildActivities(Guid entityRecordGuid, IOrganizationService service)
 QueryExpression qe = new QueryExpression();
 qe.ColumnSet = new ColumnSet(new string[] { "activityid", "activitytypecode" });
 qe.EntityName = "activitypointer";

FilterExpression filterStateCode = new FilterExpression();
 filterStateCode.FilterOperator = LogicalOperator.Or;
 filterStateCode.AddCondition("statecode", ConditionOperator.Equal, "Open");
 filterStateCode.AddCondition("statecode", ConditionOperator.Equal, "Scheduled");

FilterExpression filter = new FilterExpression();
 filter.FilterOperator = LogicalOperator.And;
 filter.AddCondition("regardingobjectid", ConditionOperator.Equal, entityRecordGuid);

qe.Criteria = filter;

RetrieveMultipleRequest request = new RetrieveMultipleRequest();
 request.Query = qe;
 RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(request);

foreach (Entity activity in response.EntityCollection.Entities)
 CancelActivity(activity, service);


 private void CancelActivity(Entity entity, IOrganizationService service)
 EntityReference moniker = new EntityReference();

if (entity.LogicalName == "activitypointer")
 if (entity.Attributes.Contains("activityid") & entity.Attributes.Contains("activitytypecode"))
 moniker.LogicalName = entity.Attributes["activitytypecode"].ToString();
 moniker.Id = (Guid)entity.Attributes["activityid"];

SetStateRequest request = new SetStateRequest();
 request.EntityMoniker = moniker;
 request.State = new OptionSetValue(2);
 request.Status = new OptionSetValue(-1);
 SetStateResponse response = (SetStateResponse)service.Execute(request);




Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

One thought on “Sample Code to Cancel All the Open Activities for a particular record in CRM 2011.”

  1. Does it work with email or phone call activities where the ‘to’ property is set to the contact record, but the regarding is not?


Please share your thoughts

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

You are commenting using your 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.