Deactivate a record to any custom or system entity in Microsoft Dynamics CRM 4.0 programmatically in a plugin using dynamic entity changing state code and status code

This is a quick post to show you a function that I used recently to activate and deactivate records programmatically using CRM API/SDK. The function allows you to set the state code (statuscode field) as active or inactive and set the status code field value (status code or status reason) to any value from the values you specify in your Microsoft Dynamics CRM organization. For example, if you set statuscode Cancelled as a reason, you need to know what integer this status reason represents and pass this value to this function.

Here is the function:

// Update status function
  // Service = CRM service
  // recordid: Guid for the record that needs its active/inactive status changed
  // entityname: Name of the entity (string)
  // Statuscode: Status reason (check the value for each reason from your
  //     CRM implementation). Takes an integer
  // Statecode: Status of the record to be changed to. It takes values "active" or "inactive".
  private static bool updateRecordStatus(ICrmService service, Guid recordid, string entityname,
   int statuscode, string statecode)
   SetStateDynamicEntityRequest req = new SetStateDynamicEntityRequest();
   req.State = statecode;
   req.Status = statuscode;
   req.Entity = new Moniker();
   req.Entity.Id = recordid;
   req.Entity.Name = entityname;
   SetStateDynamicEntityResponse resp = (SetStateDynamicEntityResponse)service.Execute(req);
   return true;
// Here is an example of a call to this method:
updateRecordStatus(service, recordGuid, "new_mycustomentity", 4, "inactive");
//This will set your record to inactive with status
//  reason 4 whatever this status reason is in your impelementation

Hopefully this will help someone out there! Thanks to my colleague Rashwan for his help on this post.

Please comment or leave feedback