Tuesday, March 27, 2018

Check if Case contains Note/Annotation in Dynamics CRM


            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
           
            // ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            if (context.InputParameters.Contains("IncidentResolution") && context.InputParameters["IncidentResolution"] is Entity)
            {
                
                Entity incidentResolution = (Entity)context.InputParameters["IncidentResolution"];
                Guid relatedIncidentGuid = ((EntityReference)incidentResolution.Attributes["incidentid"]).Id;

               
                QueryExpression NotesQE = new QueryExpression { EntityName = "annotation", ColumnSet = new ColumnSet(true) };
                LinkEntity incident = new LinkEntity
                {
                    LinkFromEntityName = "annotation", //annotation
                    LinkToEntityName = "incident", //Case
                    LinkFromAttributeName = "objectid", 
                    LinkToAttributeName = "incidentid"
                };
                OrderExpression orderbycreatedon = new OrderExpression("createdon", OrderType.Descending);
                incident.LinkCriteria.AddCondition("incidentid", ConditionOperator.Equal, relatedIncidentGuid);
                NotesQE.Orders.Add(orderbycreatedon);
                NotesQE.LinkEntities.Add(incident);
                EntityCollection NotesRetrieveQE = service.RetrieveMultiple(NotesQE);
                
                    if (NotesRetrieveQE != null && NotesRetrieveQE.Entities.Count > 0 && NotesRetrieveQE.Entities[0].Attributes.Contains("filename"))
                    {
                        String filename = NotesRetrieveQE.Entities[0].Attributes["filename"].ToString();
                        string[] splitfilename = filename.Split('.');
                        if (splitfilename[splitfilename.Length - 1] == "pdf")
                        { return; }
                        else
                        {
                            throw new InvalidPluginExecutionException("Notes not Found.");
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("Notes not Found.");
                    }            
            }

No comments:

Post a Comment