Let's say we want to implement a business scenario for a member entity in our library management system. When any CRM admin tries to delete the member entity record, we will be validating whether a book has been issued to this member or not; if yes, we won't allow them to delete the record.
We need to register our plug-in on the pre delete event and we will be using a pre image to get the attribute of the entity. Perform the following steps to implement our requirement:
First, we need to get context from the service provider and the organization service object. Since we are going to register the pre image, we will get our entity object from the pre image as follows:
public void Execute(IServiceProvider serviceProvider) { try { //get context IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); //create service factory object IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService( typeof(IOrganizationServiceFactory)); //get service object from service factory IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); if (context.PreEntityImages.Contains("preImage")) { Entity prememberEntity = (Entity)context.PreEntityImages["preImage"]; if (BookIssueValidation(prememberEntity.Id,service)) { throw new InvalidPluginExecutionException("This is book issued for this Member, so it can't be deleted"); } } } catch (FaultException<OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException("An error occurred in the validtion plug-in.", ex); } }
After that, we need to pass the member ID and service object to another function to validate if there are any books issued to this user; it use return true
else return false
:
private bool BookIssueValidation(Guid MemberId, IOrganizationService service) { //query bookissue entity based on member id QueryExpression query = new QueryExpression { EntityName = "him_bookissue", ColumnSet = new ColumnSet(true), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "him_issuedto", Operator = ConditionOperator.Equal, Values = { MemberId } }, new ConditionExpression { AttributeName = "him_status", Operator = ConditionOperator.Equal, Values = { 1 } } } } }; return (service.RetrieveMultiple(query).Entities.Count > 0 ? true : false); }
3.145.179.193