web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

BPF stage move to next using plugin in Crm 9.0

(0) ShareShare
ReportReport
Posted on by 2,667

Hi All,

I have used plugin for stage movement based on field change but getting error "Index out of range & must be non negative & less than d size of collection."

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);

}

}

Any idea or help...

Thanks,

Jharana

I have the same question (0)
  • a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Hello,

    It's a bit hard to recommend anything when the source code is not available.

  • Suggested answer
    sdfasdf Profile Picture
    842 on at
  • Jharana Baliyar Singh Profile Picture
    2,667 on at

    Hi All

    I have updated the code in my above post.

    The above code is working fine but problem is in this line processInstanceResponse.Processes.Entities[0] , becz processInstanceResponse.Processes.Entities.Count am getting 2 which is 2 process am getting so need to check for the correct process if it has then only loop will continue.

    In Below how can I get Key value for Process Name or processid from rocessInstanceResponse.Processes.Entities

    4353.BPF.png

    2161.BPF1.png

    Thanks

    Jharana

  • Verified answer
    Jharana Baliyar Singh Profile Picture
    2,667 on at

    Hi All,

    Now this is working fine now to get the correct process with below modified code.

    if (processInstanceResponse.Processes.Entities.Count > 0)

                   {

                       foreach (var item in processInstanceResponse.Processes.Entities)

                       {

                           if (item.Attributes.ContainsKey("processid"))

                           {                          

                               if ((item.GetAttributeValue<EntityReference>("processid")).Id.ToString().ToUpper() == "57E8BC82-F936-4CBA-B6C6-18A7C3E270A2")

                               {

                                   activeProcessInstance = item;

                                   activeProcessInstanceID = activeProcessInstance.Id;

                                   Console.WriteLine("Process instance automatically created for the new Case record: '{0}'", activeProcessInstance["name"]);

                                   Console.ReadLine();

                                   string processInstanceLogicalName = activeProcessInstance["name"].ToString().Replace(" ", string.Empty).ToLower();

                                   Guid activeStageID = new Guid(activeProcessInstance.Attributes["processstageid"].ToString());

                                   Console.WriteLine(activeStageID);

                                   Console.ReadLine();

    Thanks,

    Jharana

  • Suggested answer
    Jharana Baliyar Singh Profile Picture
    2,667 on at

    It is resolved now. Thanku

Under review

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

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 137 Super User 2025 Season 2

#2
#ManoVerse Profile Picture

#ManoVerse 57

#3
Jimmy Passeti Profile Picture

Jimmy Passeti 50 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans