Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)
Under review by Community Managers

Under review

Thank you for your post! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

BPF Stage Move to Next Stage based on field Value in CRM 365 9.0 Programatically

Posted on by 2,665

Hi All,

I have written the below code for stage movement to next stage based on field value here  an option set field Action if it is Approved then it should go to next stage.Sometimes its moving for existing record,But getting error now Index out of range errormust be non negative & less than the size of the collection.Parameter name : Index.

public void Execute(IServiceProvider serviceProvider)
        {
            //get the execution context
            IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
 
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
 
            //get the organization service factory that creates the organization service
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            organizationService = serviceFactory.CreateOrganizationService(executionContext.UserId);
 
            //Create the organization service context that gives the ability of querying
            organizationServiceContext = new OrganizationServiceContext(organizationService);
 
            Entity incident = null;
            if (executionContext.InputParameters.Contains("Target") && (executionContext.InputParameters["Target"] is Entity))
                incident = (Entity)executionContext.InputParameters["Target"];
 
            //EntityReference categoryType = null;
 
            //Entity createPostImage = (Entity)executionContext.PostEntityImages["ConflictofInterestPostImage"];
 
            //if (createPostImage.Contains("mdc_interactiontype"))
            //    categoryType = (EntityReference)createPostImage["mdc_interactiontype"];
 
            try
            {
                tracingService.Trace("TriggerIn...");
                organizationServiceContext.ClearChanges();
 
               //get the values of the case
                var incidentDetails = (from tra in organizationServiceContext.CreateQuery("incident")
                                       where (Guid)tra["incidentid"] == incident.Id
                                       select new
                                       {
                                           Id = tra.Contains("incidentid") ? (Guid)tra["incidentid"] : Guid.Empty,
                                           InteractionType = tra.Contains("mdc_interactiontype") ? ((EntityReference)tra["mdc_interactiontype"]).Name : string.Empty
                                       }).FirstOrDefault();
 
                if (incidentDetails.InteractionType.ToLower() == "conflict of interest")
                {
                    SetProcessRequest request = new SetProcessRequest();
 
                    request.Target = new EntityReference("incident", incident.Id);
 
                    // THE BELOW POINTS TO THE CORRECT GUID OF THE BUSINESS PROCESS FLOW
 
                    request.NewProcess = new EntityReference("workflow", new Guid("7A538A01-DD47-4335-833E-11E8F9BAD906"));
 
                    organizationService.Execute(request);
                }
                else if (incidentDetails.InteractionType.ToLower() == "gift & entertainment")
                {
                    SetProcessRequest request = new SetProcessRequest();
 
                    request.Target = new EntityReference("incident", incident.Id);
 
                    // THE BELOW POINTS TO THE CORRECT GUID OF THE BUSINESS PROCESS FLOW
 
                    request.NewProcess = new EntityReference("workflow", new Guid("57E8BC82-F936-4CBA-B6C6-18A7C3E270A2"));
 
                    organizationService.Execute(request);
                }
                try
                {
                    if (executionContext.MessageName.ToUpper() == "UPDATE")
                    {
                        if (executionContext.InputParameters.Contains("Target") && executionContext.InputParameters["Target"] is Entity)
                        {
                            Entity entity = (Entity)executionContext.InputParameters["Target"];
                            Guid id = entity.Id;
                            if (entity.Contains("mdc_action") && entity["mdc_action"] != null)
                            {
                                OptionSetValue value = (OptionSetValue)entity.Attributes["mdc_action"];
                                int action = value.Value;
                                if (action == 755040000)//Approved
                                {
                                    tracingService.Trace("Selected Approved");
                                    //var entity = organizationService.Retrieve("incident", entities.Id, new ColumnSet(true));
                                    //ChangeStage(organizationService, tracingService, entity);
                                    // Get Process Instances
                                    RetrieveProcessInstancesRequest processInstanceRequest = new RetrieveProcessInstancesRequest
                                    {
                                        EntityId = entity.Id,
                                        EntityLogicalName = entity.LogicalName
                                    };
                                    tracingService.Trace("Got Req");
                                    RetrieveProcessInstancesResponse processInstanceResponse = (RetrieveProcessInstancesResponse)organizationService.Execute(processInstanceRequest);
                                    // Declare variables to store values returned in response
                                    Entity activeProcessInstance = null;
                                   // Guid activeProcessInstanceID = null;
                                    //if (processInstanceResponse.Processes.Entities.Count > 0)
                                    //{
                                       activeProcessInstance = processInstanceResponse.Processes.Entities[0];
                                      Guid activeProcessInstanceID = activeProcessInstance.Id;
                                        tracingService.Trace("Process instance automatically created for the new Case record: '{0}'", activeProcessInstance["name"]);
                                   string processInstanceLogicalName = activeProcessInstance["name"].ToString().Replace(" ", string.Empty).ToLower();
                                    //}
                                    //else
                                    //{
                                    //    tracingService.Trace("No processes found for the Case record; aborting the sample.");
                                    //    Environment.Exit(1);
                                    //}                                 
                                    Guid activeStageID = new Guid(activeProcessInstance.Attributes["processstageid"].ToString());
 
                                    // Retrieve the process stages in the active path of the current process instance
                                    RetrieveActivePathRequest pathReq = new RetrieveActivePathRequest
                                    {
                                        ProcessInstanceId = activeProcessInstanceID
                                    };
                                    RetrieveActivePathResponse pathResp = (RetrieveActivePathResponse)organizationService.Execute(pathReq);
                                    tracingService.Trace("Retrieved stages in the active path of the process instance:");
                                    string activeStageName = string.Empty;
                                    int activeStagePosition = -1;
                                    for (int i = 0; i < pathResp.ProcessStages.Entities.Count; i++)
                                    {
                                        // Retrieve the active stage name and active stage position based on the activeStageId for the process instance
                                        if (pathResp.ProcessStages.Entities[i].Attributes["processstageid"].ToString() == activeStageID.ToString())
                                        {
                                            activeStageName = pathResp.ProcessStages.Entities[i].Attributes["stagename"].ToString();
                                            activeStagePosition = i;
                                            tracingService.Trace($"Active Stage Name and Step Index set: {activeStageName}, {activeStagePosition}");
                                            //break;
                                        }
                                    }
                                    bool moveToNextStage = true;
                                    //string ProcessStage = "";
                                    if (moveToNextStage)
                                    {
                                        activeStageID = (Guid)pathResp.ProcessStages.Entities[activeStagePosition + 1].Attributes["processstageid"];
                                        tracingService.Trace($"Active Stage ID set: {activeStageID}");
 
                                        // Retrieve the process instance record to update its active stage
                                        ColumnSet cols1 = new ColumnSet();
                                        cols1.AddColumn("activestageid");
                                        tracingService.Trace($"Retrieve Process Instance for ID: {activeProcessInstanceID}");
                                        Entity retrievedProcessInstance = organizationService.Retrieve("mdc_gegroupprocess", activeProcessInstanceID, cols1);
                                        // Set the next stage as the active stage
                                        retrievedProcessInstance["activestageid"] = new EntityReference(pathResp.ProcessStages.EntityName, activeStageID);
                                        tracingService.Trace($"Update the process stage, set Active Stage Id");
                                        organizationService.Update(retrievedProcessInstance);
                                    }                                               
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred here " + ex.Message, ex);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the set COI Process Plug-in: " + ex.Message, ex);
            }
        }      
If anyone has idea let me know it would be helpful.
Thanks,
Jharana

Helpful resources

Quick Links

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,711 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,458 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans