protected override void ExecuteInternal(LocalWorkflowContext context) { var stageNameToSet = this.StageNameInArgument.Get(context.CodeActivityContext).ToUpper(); RetrieveProcessInstancesRequest retrieveProcessInstancesRequest = new RetrieveProcessInstancesRequest { EntityId = context.WorkflowContext.PrimaryEntityId, EntityLogicalName = context.WorkflowContext.PrimaryEntityName }; RetrieveProcessInstancesResponse retrievedProcessInstancesResponse = (RetrieveProcessInstancesResponse)context.OrganizationService.Execute(retrieveProcessInstancesRequest); var activeProcessInstance = retrievedProcessInstancesResponse.Processes.Entities[0]; // First record is the active process instance var workflowReference = (EntityReference)activeProcessInstance.Attributes["processid"]; Process workflow = context.OrganizationService.Retrieve(workflowReference.LogicalName, workflowReference.Id, new ColumnSet(true)).ToEntity <Process>(); RetrieveActivePathRequest pathRequest = new RetrieveActivePathRequest { ProcessInstanceId = activeProcessInstance.Id }; RetrieveActivePathResponse pathResponse = (RetrieveActivePathResponse)context.OrganizationService.Execute(pathRequest); var stageToSetId = (Guid)pathResponse.ProcessStages.Entities.Where(x => x.Attributes["stagename"].ToString().ToUpper() == stageNameToSet).First().Attributes["processstageid"]; ColumnSet columns = new ColumnSet(); columns.AddColumn("activestageid"); Entity retrievedProcessInstance = context.OrganizationService.Retrieve(workflow.UniqueName, activeProcessInstance.Id, columns); // Set the next stage as the active stage retrievedProcessInstance["activestageid"] = new EntityReference(ProcessStage.EntityLogicalName, stageToSetId); context.OrganizationService.Update(retrievedProcessInstance); }
public static void ChangeStage(IOrganizationService service, Guid op) { // Get Process Instances RetrieveProcessInstancesRequest processInstanceRequest = new RetrieveProcessInstancesRequest { EntityId = op, EntityLogicalName = Opportunity.EntityLogicalName }; RetrieveProcessInstancesResponse processInstanceResponse = (RetrieveProcessInstancesResponse)service.Execute(processInstanceRequest); // Declare variables to store values returned in response int processCount = processInstanceResponse.Processes.Entities.Count; Entity activeProcessInstance = processInstanceResponse.Processes.Entities[0]; // First record is the active process instance Guid activeProcessInstanceID = activeProcessInstance.Id; // Id of the active process instance, which will be used later to retrieve the active path of the process instance // Retrieve the active stage ID of in the active process instance 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)service.Execute(pathReq); // Retrieve the stage ID of the next stage that you want to set as active activeStageID = (Guid)pathResp.ProcessStages.Entities[4].Attributes["processstageid"]; // Retrieve the process instance record to update its active stage ColumnSet cols1 = new ColumnSet(); cols1.AddColumn("activestageid"); Entity retrievedProcessInstance = service.Retrieve("opportunitysalesprocess", activeProcessInstanceID, cols1); // Set the next stage as the active stage retrievedProcessInstance["activestageid"] = new EntityReference(OpportunitySalesProcess.EntityLogicalName, activeStageID); service.Update(retrievedProcessInstance); }
public void ChangeStage(IOrganizationService service) { // Get Process Instances var processInstanceRequest = new RetrieveProcessInstancesRequest { EntityId = new Guid(IotAlert.Id.ToString()), EntityLogicalName = IotAlert.LogicalName.ToString() }; var processInstanceResponse = (RetrieveProcessInstancesResponse)service.Execute(processInstanceRequest); // Declare variables to store values returned in response Entity activeProcessInstance = processInstanceResponse.Processes.Entities[0]; // First record is the active process instance Guid activeProcessInstanceID = activeProcessInstance.Id; // Id of the active process instance, which will be used later to retrieve the active path of the process instance // Retrieve the active stage ID of in the active process instance 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)service.Execute(pathReq); var activeStageName = ""; var activeStagePosition = -1; Console.WriteLine("\nRetrieved stages in the active path of the process instance:"); 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; } } // Retrieve the stage ID of the next stage that you want to set as active if (activeStagePosition < pathResp.ProcessStages.Entities.Count) { activeStageID = (Guid)pathResp.ProcessStages.Entities[activeStagePosition + 1].Attributes["processstageid"]; } else { Console.WriteLine("You are at latest stage"); return; } // Retrieve IoT alert Id to match the specific bpf var query = new QueryExpression { EntityName = "msdyn_bpf_477c16f59170487b8b4dc895c5dcd09b", ColumnSet = new ColumnSet("bpf_name", "bpf_msdyn_iotalertid", "activestageid") }; // query.Criteria.AddCondition("processid", ConditionOperator.Equal, activeProcessInstanceID); var retrievedProcessInstanceList = service.RetrieveMultiple(query); foreach (var entity in retrievedProcessInstanceList.Entities) { var ioTAlertBpfER = (EntityReference)entity.Attributes["bpf_msdyn_iotalertid"]; if (IotAlert.Id == ioTAlertBpfER.Id) { RetrievedProcessInstance = entity; break; } } //Retrieve Asset's account id var customerAsset = (EntityReference)IotAlert.Attributes["msdyn_customerasset"];; var customerAssetIdQuery = new QueryExpression { EntityName = "msdyn_customerasset", ColumnSet = new ColumnSet("msdyn_account", "msdyn_name", "msdyn_customerassetid"), Criteria = new FilterExpression() }; customerAssetIdQuery.Criteria.AddCondition("msdyn_customerassetid", ConditionOperator.Equal, customerAsset.Id); var customerAssetIdCollection = service.RetrieveMultiple(customerAssetIdQuery); AccountER = new EntityReference(); if (customerAssetIdCollection.Entities.Count <= 1) { //TODO: need to confirm it is account or contact AccountER = (EntityReference)customerAssetIdCollection[0].Attributes["msdyn_account"]; PrimaryAssetER.Id = customerAssetIdCollection[0].Id; PrimaryAssetER.LogicalName = customerAssetIdCollection[0].LogicalName; PrimaryAssetER.Name = customerAssetIdCollection[0].Attributes["msdyn_name"].ToString(); } else { //more than one value, need developer to do investigation return; } // Retrieve the process instance record to update its active stage // activeStagePosition == 0 && activeStageName == "Created" CreateCase(service); // activeStagePosition == 1 && activeStageName == "Create Work Order" CreateWorkOrder(service); // activeStagePosition == 2 && activeStageName == "Schedule Work Order" ScheduleWorkOrder(service); // Set the next stage as the active stage // service.Update(RetrievedProcessInstance); }
/// <summary> /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Creates required records for this sample. CreateRequiredRecords(); // Qualify a lead to create an opportunity QualifyLeadRequest qualifyRequest = new QualifyLeadRequest { LeadId = new EntityReference(Lead.EntityLogicalName, _leadId), Status = new OptionSetValue((int)lead_statuscode.Qualified), CreateOpportunity = true }; QualifyLeadResponse qualifyResponse = (QualifyLeadResponse)_serviceProxy.Execute(qualifyRequest); _opportunityId = qualifyResponse.CreatedEntities[0].Id; if (_opportunityId != Guid.Empty) { Console.WriteLine("\nQualified Lead to create an Opportunity record."); } // Verify the curently active BPF instance for the qualified Opportunity record RetrieveProcessInstancesRequest procOpp1Req = new RetrieveProcessInstancesRequest { EntityId = _opportunityId, EntityLogicalName = Opportunity.EntityLogicalName }; RetrieveProcessInstancesResponse procOpp1Resp = (RetrieveProcessInstancesResponse)_serviceProxy.Execute(procOpp1Req); // Declare variables to store values returned in response Entity activeProcessInstance = null; if (procOpp1Resp.Processes.Entities.Count > 0) { activeProcessInstance = procOpp1Resp.Processes.Entities[0]; // First record is the active process instance _processOpp1Id = activeProcessInstance.Id; // Id of the active process instance, which will be used // later to retrieve the active path of the process instance Console.WriteLine("Current active process instance for the Opportunity record: '{0}'", activeProcessInstance["name"].ToString()); _procInstanceLogicalName = activeProcessInstance["name"].ToString().Replace(" ", string.Empty).ToLower(); } else { Console.WriteLine("No process instances found for the opportunity record; aborting the sample."); Environment.Exit(1); } // Retrieve the active stage ID of the active process instance _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 = _processOpp1Id }; RetrieveActivePathResponse pathResp = (RetrieveActivePathResponse)_serviceProxy.Execute(pathReq); Console.WriteLine("\nRetrieved stages in the active path of the process instance:"); for (int i = 0; i < pathResp.ProcessStages.Entities.Count; i++) { Console.WriteLine("\tStage {0}: {1} (StageId: {2})", i + 1, pathResp.ProcessStages.Entities[i].Attributes["stagename"], pathResp.ProcessStages.Entities[i].Attributes["processstageid"]); // 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; } } // Display the active stage name and Id Console.WriteLine("\nActive stage for the process instance: '{0}' (StageID: {1})", _activeStageName, _activeStageId); // Prompt the user to move to the next stage. If user choses to do so: // Set the next stage (_activeStagePosition + 1) as the active stage for the process instance bool moveToNextStage = true; Console.WriteLine("\nDo you want to move to the next stage (y/n):"); String answer = Console.ReadLine(); moveToNextStage = (answer.StartsWith("y") || answer.StartsWith("Y")); if (moveToNextStage) { // Retrieve the stage ID of the next stage that you want to set as active _activeStageId = (Guid)pathResp.ProcessStages.Entities[_activeStagePosition + 1].Attributes["processstageid"]; // Retrieve the process instance record to update its active stage ColumnSet cols1 = new ColumnSet(); cols1.AddColumn("activestageid"); Entity retrievedProcessInstance = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols1); // Update the active stage to the next stage retrievedProcessInstance["activestageid"] = new EntityReference(ProcessStage.EntityLogicalName, _activeStageId); _serviceProxy.Update(retrievedProcessInstance); // Retrieve the process instance record again to verify its active stage information ColumnSet cols2 = new ColumnSet(); cols2.AddColumn("activestageid"); Entity retrievedProcessInstance1 = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols2); EntityReference activeStageInfo = retrievedProcessInstance1["activestageid"] as EntityReference; if (activeStageInfo.Id == _activeStageId) { Console.WriteLine("\nChanged active stage for the process instance to: '{0}' (StageID: {1})", activeStageInfo.Name, activeStageInfo.Id); } } // Prompts to delete the required records DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics 365 throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }