private void execWFs(object sender) { if (ExecutionRecordSet.Entities.Count <= 0) { MessageBox.Show("Please click 'Count Records' before Executing Workflows"); return; } #region Bulk Data API Stuff // Create an ExecuteMultipleRequest object. requestWithResults = new ExecuteMultipleRequest() { // Assign settings that define execution behavior: continue on error, return responses. Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, // Create an empty organization request collection. Requests = new OrganizationRequestCollection() }; #endregion if (txtBatch.Text != "") { emrBatchSize = Convert.ToInt32(txtBatch.Text); } else { emrBatchSize = 200; } /* this.Invoke((MethodInvoker)delegate() { toolStripProgressBar1.Style = ProgressBarStyle.Marquee; toolStripStatusLabel1.Text = "Executing Workflows"; emrBatchSize = Convert.ToInt32(txtBatchSize.Text); }); */ foreach (var item in ExecutionRecordSet.Entities) { ExecuteWorkflowRequest _execWF = new ExecuteWorkflowRequest { WorkflowId = _selectedWorkflow.Id, EntityId = item.Id }; RunEMR(_execWF, ((BackgroundWorker)sender)); } FlushEMR((BackgroundWorker)sender); /* this.Invoke((MethodInvoker)delegate() { toolStripProgressBar1.Style = ProgressBarStyle.Continuous; toolStripStatusLabel1.Text = "Execution of Workflows Completed"; }); */ }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); #endregion #region "Read Parameters" String _RecordID = this.RecordID.Get(executionContext); EntityReference process = this.Process.Get(executionContext); #endregion #region "SetProcess Execution" ExecuteWorkflowRequest wfRequest = new ExecuteWorkflowRequest(); wfRequest.EntityId = new Guid(_RecordID); wfRequest.WorkflowId = process.Id; ExecuteWorkflowResponse wfResponse = (ExecuteWorkflowResponse)objCommon.service.Execute(wfRequest); #endregion }
public static void RunWorkflow(string name, string entityId, string completeCallback, string errorCallback) { // Get the name of the workflow string fetch = String.Format(@"<fetch count='1'> <entity name='workflow'> <attribute name='workflowid'/> <filter type='and'> <condition attribute='name' operator='eq' value='{0}'/> <condition attribute='ondemand' operator='eq' value='true'/> <condition attribute='statuscode' operator='eq' value='2'/> <condition attribute='type' operator='eq' value='1'/> </filter> </entity> </fetch>", name); OrganizationServiceProxy.BeginRetrieveMultiple(fetch, delegate(object state) { EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(state, typeof(Entity)); if (results.Entities.Count == 0) { Page.Ui.SetFormNotification("Workflow " + name + " is not published", FormNotificationLevel.Error, "RibbonWorkflowError"); } bool isError = false; foreach (Entity row in results.Entities) { // Run Workflow ExecuteWorkflowRequest request = new ExecuteWorkflowRequest(); request.EntityId = entityId.Replace("{", "").Replace("}", ""); request.WorkflowId = row.GetAttributeValueString("workflowid"); OrganizationServiceProxy.BeginExecute(request, delegate(object executeState) { try { ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)OrganizationServiceProxy.EndExecute(executeState); if (completeCallback != null) { if (response.Id == Guid.Empty.Value) { Script.Eval(completeCallback); } else { // Query until completed WaitForWorkflowToComplete(response.Id, completeCallback, errorCallback, null); } } } catch (Exception e) { string stackTrace = e.StackTrace; Script.Literal("console.log(stackTrace)"); Script.Eval(errorCallback); } }); break; } }); }
public void ConvertDateTimeToString(StringConversionTests testCase) { // Arrange Dictionary <string, object> attributesDictionary = new Dictionary <string, object> { { "cn_name", $"Convert DateTime to String Conversion - {testCase.InputDate}" }, { "cn_datetimevalue", testCase.InputDate } }; var guid = _crm.CreateCrmRecord(IntegrationTestEntityName, attributesDictionary); Console.WriteLine($"Created test record: {guid}"); // Act ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = guid, WorkflowId = new Guid("731AA509-F313-478C-AFE0-E3CA35153481") }; _crm.Execute(request); // Assert var processedRecord = _crm.GetCrmRecord(IntegrationTestEntityName, guid, null); Assert.AreEqual(testCase.OutputString, processedRecord["cn_textvalue"]); // Tear Down _crm.DeleteCrmRecord(IntegrationTestEntityName, guid); }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { EntityCollection recordsToProcess = service.RetrieveMultiple(new FetchExpression(FetchXMLQuery.Get(executionContext))); recordsToProcess.Entities.ToList().ForEach(a => { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = a.Id, WorkflowId = (Workflow.Get(executionContext)).Id }; service.Execute(request); //run the workflow }); } catch (FaultException <OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } catch (Exception e) { tracingService.Trace("Exception: {0}", e.ToString()); throw; } tracingService.Trace("Exiting " + _activityName + ".Execute(), Correlation Id: {0}", context.CorrelationId); }
public void ConvertStringToBoolean(string input, bool expectedOutput) { // Arrange Dictionary <string, object> attributesDictionary = new Dictionary <string, object>(); attributesDictionary.Add("cn_name", $"Convert String to Boolean Conversion - {input}"); attributesDictionary.Add("cn_textvalue", input); var guid = _crm.CreateCrmRecord(IntegrationTestEntityName, attributesDictionary); _recordsCreated.Add(guid); Console.WriteLine($"Created test record: {guid}"); // Act ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = guid, WorkflowId = new Guid("980EE56B-FBB8-4516-A8AE-B70553F5463E") // "CWL - DataConversion - Convert String To Boolean" }; _crm.Execute(request); // Assert var processedRecord = _crm.GetCrmRecord(IntegrationTestEntityName, guid, null); Assert.AreEqual(expectedOutput, processedRecord["cn_booleanvalue"]); // Tear Down _crm.DeleteCrmRecord(IntegrationTestEntityName, guid); }
public CRMWorkflow CRMStartWorkflowByID(CRMWorkflow crmWF) { OrganizationServiceProxy _serviceProxy; //IOrganizationService _service; using (_serviceProxy = GetCRMConnection()) { try { // Create an ExecuteWorkflow request. ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = new Guid(crmWF.WorkflowId), EntityId = new Guid(crmWF.EntityId) }; // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request); } catch (Exception ex) { throw; } } return(crmWF); }
public void ConvertIntegerToBoolean(int input, bool expectedOutput) { // Arrange Dictionary <string, object> attributesDictionary = new Dictionary <string, object>(); attributesDictionary.Add("cn_name", $"Convert Int to Boolean - {input}"); attributesDictionary.Add("cn_wholenumbervalue", input); var guid = _crm.CreateCrmRecord(IntegrationTestEntityName, attributesDictionary); _recordsCreated.Add(guid); Console.WriteLine($"Created test record: {guid}"); // Act ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = guid, WorkflowId = new Guid("7EBA7122-74BD-40B2-B621-4BAC2F292956") // "CWL - DataConversion - Convert Int To Boolean" }; _crm.Execute(request); // Assert var processedRecord = _crm.GetCrmRecord(IntegrationTestEntityName, guid, null); Assert.AreEqual(expectedOutput, processedRecord["cn_booleanvalue"]); // Tear Down _crm.DeleteCrmRecord(IntegrationTestEntityName, guid); }
public ActionResult ExecuteWorkflow(EntityReference workflow, EntityReference entity) { string portalName = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); var languageCodeSetting = portalContext.ServiceContext.GetSiteSettingValueByName(portalContext.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { portalName = languageCode.ToString(CultureInfo.InvariantCulture); } } var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: portalName); var serviceContext = dataAdapterDependencies.GetServiceContext(); var request = new ExecuteWorkflowRequest { WorkflowId = workflow.Id, EntityId = entity.Id }; serviceContext.Execute(request); serviceContext.TryRemoveFromCache(entity); return(new HttpStatusCodeResult(HttpStatusCode.NoContent)); }
protected override void Execute(CodeActivityContext executionContext) { IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); string fetchXMLQuery = FetchXML.Get(executionContext); EntityCollection recordsToProcess = service.RetrieveMultiple(new FetchExpression(fetchXMLQuery)); EntityReference processEntityReference = WorkflowToExecute.Get(executionContext); foreach (var entity in recordsToProcess.Entities) { try { var request = new ExecuteWorkflowRequest { EntityId = entity.Id, WorkflowId = processEntityReference.Id }; service.Execute(request); } catch (Exception ex) { throw new Exception($"Error executing workflow on {entity.Id}: {ex.Message}", ex); } } }
protected override void Execute(System.Activities.CodeActivityContext context) { var workflowContext = context.GetExtension <IWorkflowContext>(); var service = this.RetrieveOrganizationService(context); QueryResult result = ExecuteQueryForRecords(context); Entity workflow = service.Retrieve("workflow", this.Workflow.Get(context).Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("primaryentity")); if (workflow.GetAttributeValue <string>("primaryentity").ToLower() != result.EntityName) { throw new ArgumentException($"Workflow entity ({workflow.GetAttributeValue<string>("primaryentity")} does not match query entity ({result.EntityName})"); } int numberStarted = 0; foreach (Guid id in result.RecordIds) { try { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { EntityId = id, WorkflowId = workflow.Id }; ExecuteWorkflowResponse response = service.Execute(request) as ExecuteWorkflowResponse; } catch (Exception ex) { throw new Exception($"Error initiating workflow on record with ID = {id}; {ex.Message}"); } numberStarted++; } this.NumberOfWorkflowsStarted.Set(context, numberStarted); }
private void execWFs(object sender) { if (ExecutionRecordSet.Entities.Count <= 0) { MessageBox.Show("Please click 'Count Records' before Executing Workflows"); return; } #region Bulk Data API Stuff // Create an ExecuteMultipleRequest object. requestWithResults = new ExecuteMultipleRequest() { // Assign settings that define execution behavior: continue on error, return responses. Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, // Create an empty organization request collection. Requests = new OrganizationRequestCollection() }; #endregion if (txtBatch.Text != "") { emrBatchSize = Convert.ToInt32(txtBatch.Text); } else { emrBatchSize = 200; } /* * this.Invoke((MethodInvoker)delegate() * { * toolStripProgressBar1.Style = ProgressBarStyle.Marquee; * toolStripStatusLabel1.Text = "Executing Workflows"; * emrBatchSize = Convert.ToInt32(txtBatchSize.Text); * }); */ foreach (var item in ExecutionRecordSet.Entities) { ExecuteWorkflowRequest _execWF = new ExecuteWorkflowRequest { WorkflowId = _selectedWorkflow.Id, EntityId = item.Id }; RunEMR(_execWF, ((BackgroundWorker)sender)); } FlushEMR((BackgroundWorker)sender); /* * this.Invoke((MethodInvoker)delegate() * { * toolStripProgressBar1.Style = ProgressBarStyle.Continuous; * toolStripStatusLabel1.Text = "Execution of Workflows Completed"; * }); */ }
public void StartWorkflow(Guid workflowId, Guid targetId) { var request = new ExecuteWorkflowRequest { EntityId = targetId, WorkflowId = workflowId }; Execute(request); }
public static ExecuteWorkflowResponse ExecuteProcess(this IOrganizationService organizationService, Guid processId, Guid entityId) { var request = new ExecuteWorkflowRequest() { WorkflowId = processId, EntityId = entityId }; return((ExecuteWorkflowResponse)organizationService.Execute(request)); }
public static ExecuteWorkflowResponse ExecuteWorkflowWithRetry(this IOrganizationService service, Guid entityId, Guid workflowId, int retryTimes = 1) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = entityId, WorkflowId = workflowId }; return(ExecuteWorkflowWithRetry(service, request, retryTimes)); }
/// <summary> /// Executes a workflow on an record /// </summary> /// <param name="workflowId">The id of the workflow to execute</param> /// <param name="entityId">The id of the entity over which to execute to workflow</param> /// <returns>The response from the ExecuteWorkflow request</returns> protected ExecuteWorkflowResponse ExecuteWorkflowOnEntity(Guid workflowId, Guid entityId) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = workflowId, EntityId = entityId }; return((ExecuteWorkflowResponse)(OrganizationService.Execute(request))); }
public static void ExecuteWorkflowOnRecord(IOrganizationService service, Guid workflowId, Guid recordId) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { EntityId = recordId, WorkflowId = workflowId, }; service.Execute(request); }
public void ExecutaWorkFlow(Contato contato, Guid WorkFlowId) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = WorkFlowId, EntityId = contato.Id }; ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)base.Execute(request); }
protected override void Execute(CodeActivityContext executionContext) { IOrganizationServiceFactory factory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = factory.CreateOrganizationService(null); ExecuteWorkflowRequest request = new ExecuteWorkflowRequest(); request.EntityId = this.Target.Get(executionContext).Id; request.WorkflowId = this.Workflow.Get(executionContext).Id; service.Execute(request); }
public static Guid ApplyWorkFlow(Entity entity, Guid workflowId, InputArgumentCollection args = null, CrmConnection connection = null) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { EntityId = entity.Id, WorkflowId = workflowId, InputArguments = args }; ExecuteWorkflowResponse response = Execute <ExecuteWorkflowRequest, ExecuteWorkflowResponse>(request, connection); return(response.Id); }
/// <inheritdoc/> public void ExecuteWorkflowForEntity(Entity entity, Guid workflowId) { this.EnsureLogicalNameIsValid(entity); var request = new ExecuteWorkflowRequest { WorkflowId = workflowId, EntityId = entity.Id, }; this.OrgService.Execute(request); }
public Guid ExecuteWorkflow(Guid workflowId, Guid entityId) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest(); //Assign the ID of the workflow you want to execute to the request. request.WorkflowId = workflowId; //Assign the ID of the entity to execute the workflow on to the request. request.EntityId = entityId; // Execute the workflow. return(((ExecuteWorkflowResponse)OrganizationService.Execute(request)).Id); }
public static void Distribute(this IDistributeWorkflowActivity activity, Guid workflowId, IEnumerable <Guid> keys, IOrganizationService orgService, ITracingService tracer) { foreach (var key in keys) { ExecuteWorkflowRequest req = new ExecuteWorkflowRequest() { EntityId = key, WorkflowId = workflowId }; var resp = (ExecuteWorkflowResponse)orgService.Execute(req); tracer.Trace($"A system job {resp.Id} is created for the workflow {workflowId}"); } }
/// <summary> /// Launch workflows for dependent entities. /// </summary> protected void Distribute(CodeActivityContext executionContext) { var keyList = this.GatherKeys(executionContext); var workflowId = this.Workflow.Get(executionContext).Id; var svc = this.GetService(executionContext); foreach (Guid key in keyList) { ExecuteWorkflowRequest workflowRequest = new ExecuteWorkflowRequest(); workflowRequest.EntityId = key; workflowRequest.WorkflowId = workflowId; svc.Execute(workflowRequest); } }
/// <summary> /// InvokeWorkflows method is to call workflow dynamically based on passed parameters /// </summary> /// <param name="_workflowGuid"></param> /// <param name="entityResult"></param> /// <param name="serviceProxy"></param> private void InvokeWorkflows(Guid _workflowGuid, EntityCollection entityResult, IOrganizationService serviceProxy) { tracingService.Trace("Related Entity Collection Count: {0}", entityResult.Entities.Count); entityResult.Entities.ToList().ForEach(entity => { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = entity.Id, WorkflowId = _workflowGuid }; serviceProxy.Execute(request); //run the workflow }); }
private void updateExistingAccount(Guid _leadId) { //Code added as part of S893 by Meghana on Lead create for Incoming Phone call,web creation/import //wf name - fdx_Lead update Existing Account tracingService.Trace("OnDemand workflow started"); string wfid = "8622B036-D051-489A-9C0F-B168554B1938"; ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = _leadId, WorkflowId = new Guid(wfid) }; tracingService.Trace("OnDemand workflow in loop"); service.Execute(request); tracingService.Trace("OnDemand workflow req executed"); }
/// <summary> /// Launch workflows for dependent entities. /// </summary> protected void Distribute(CodeActivityContext executionContext) { var workflowId = this.Workflow.Get(executionContext).Id; var keyList = this.GatherKeys(executionContext); IWorkflowContext workflowContext = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId); foreach (Guid key in keyList) { ExecuteWorkflowRequest workflowRequest = new ExecuteWorkflowRequest(); workflowRequest.EntityId = key; workflowRequest.WorkflowId = workflowId; service.Execute(workflowRequest); } }
/// <summary> /// Executes an active workflow by name. /// </summary> /// <param name="context"></param> /// <param name="workflowName"></param> /// <param name="entityId"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public static ExecuteWorkflowResponse ExecuteWorkflowByName(this OrganizationServiceContext context, string workflowName, Guid entityId) { var workflow = context.GetWorkflowByName(workflowName); if (workflow == null) { throw new InvalidOperationException("Unable to find the '{0}' workflow.".FormatWith(workflowName)); } var request = new ExecuteWorkflowRequest { EntityId = entityId, WorkflowId = workflow.Id, }; return((ExecuteWorkflowResponse)context.Execute(request)); }
public override void DoAction(BaseSolution solution) { ActionStarted(); DynamicsSolution ds = (DynamicsSolution)solution; if (!String.IsNullOrEmpty(FetchXml) && !String.IsNullOrEmpty(WorkflowId)) { var results = ds.Service.Service.RetrieveMultiple(new FetchExpression(FetchXml)); foreach (var r in results.Entities) { ExecuteWorkflowRequest ewr = new ExecuteWorkflowRequest(); ewr.EntityId = r.Id; ewr.WorkflowId = Guid.Parse(WorkflowId); ds.Service.Service.Execute(ewr); } } ActionCompleted(); }
/// <summary> /// Runs the Workflow Execution profile. /// </summary> /// <param name="profile">The profile.</param> public void RunProfile(MSCRMWorkflowExecutionProfile profile) { LogManager.WriteLog("Running Workflow Execution Profile: " + profile.ProfileName); try { MSCRMConnection connection = profile.getSourceConneciton(); _serviceProxy = cm.connect(connection); EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(profile.FetchXMLQuery)); foreach (Entity record in result.Entities) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = profile.WorkflowId, EntityId = record.Id }; // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request); } } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText); throw; } catch (Exception ex) { if (ex.InnerException != null) { LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message); } else { LogManager.WriteLog("Error:" + ex.Message); } throw; } LogManager.WriteLog("All workflows were launched."); }
public static void FireWorkflow(IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxStep, bool entryWorkflow) { try { string workflowProperty = entryWorkflow ? "aspect_entryworkflowid" : "aspect_answerworkflowid"; if (cxStep.Contains(workflowProperty)) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = ((EntityReference)cxStep[workflowProperty]).Id, EntityId = (Guid)(((AliasedValue)cxStep["aspect_cxconversation.aspect_cxconversationid"]).Value) }; // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)service.Execute(request); } } catch (Exception ex) { //user defined workflow errored } }
/// <summary> /// Runs the Workflow Execution profile. /// </summary> /// <param name="profile">The profile.</param> public void RunProfile(MSCRMWorkflowExecutionProfile profile) { LogManager.WriteLog("Running Workflow Execution Profile: " + profile.ProfileName); try { MSCRMConnection connection = profile.getSourceConneciton(); _serviceProxy = cm.connect(connection); EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(profile.FetchXMLQuery)); foreach (Entity record in result.Entities) { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = profile.WorkflowId, EntityId = record.Id }; // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request); } } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText); throw; } catch (Exception ex) { if (ex.InnerException != null) LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message); else LogManager.WriteLog("Error:" + ex.Message); throw; } LogManager.WriteLog("All workflows were launched."); }
public void StartWorkflow(Guid workflowId, Guid targetId) { var request = new ExecuteWorkflowRequest {EntityId = targetId, WorkflowId = workflowId}; Execute(request); }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension<ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered " + _activityName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace(_activityName + ".Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { EntityCollection recordsToProcess = service.RetrieveMultiple(new FetchExpression(FetchXMLQuery.Get(executionContext))); recordsToProcess.Entities.ToList().ForEach(a => { ExecuteWorkflowRequest request = new ExecuteWorkflowRequest { EntityId = a.Id, WorkflowId = (Workflow.Get(executionContext)).Id }; service.Execute(request); //run the workflow }); } catch (FaultException<OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } catch (Exception e) { tracingService.Trace("Exception: {0}", e.ToString()); throw; } tracingService.Trace("Exiting StartScheduledWorkflows.Execute(), Correlation Id: {0}", context.CorrelationId); }
static void Main(string[] args) { try { logfilename = string.Format("{0}.log", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); log("BEGIN"); log("This code is supplied as is without guarantee. The latest code can be download from https://mscrmworkflowrunner.codeplex.com/"); if (args.Count() != 1) { throw new Exception("Invalid argument: config xml file."); } log(string.Format("Config file: {0}", args[0].ToString())); var configxml = new XmlDocument(); configxml.Load(args[0].ToString()); var connectionstring = configxml.SelectSingleNode("//config/connectionstring").InnerText; var workflownode = configxml.SelectSingleNode("//config/workflow"); var workflowname = workflownode.Attributes["name"] != null ? workflownode.Attributes["name"].Value : null; Guid workflowid = workflownode.Attributes["id"] != null && !string.IsNullOrEmpty(workflownode.Attributes["id"].Value) ? new Guid(workflownode.Attributes["id"].Value) : Guid.Empty; var fetchxml = configxml.SelectSingleNode("//config/fetchxml").InnerText; var connection = CrmConnection.Parse(connectionstring); var service = new OrganizationService(connection); var context = new CrmOrganizationServiceContext(connection); if (workflowid == Guid.Empty) { if (workflowname == null) { throw new Exception("Workflow name is required when no workflow id is specified!"); } var query = new FetchExpression("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + " <entity name='workflow'>" + " <attribute name='workflowid' />" + " <attribute name='name' />" + " <filter type='and'>" + " <condition attribute='category' operator='eq' value='0' />" + " <condition attribute='type' operator='eq' value='1' />" + " <condition attribute='name' operator='eq' value='" + workflowname + "' />" + " </filter>" + " </entity>" + "</fetch>"); var workflows = service.RetrieveMultiple(query); if (workflows.Entities.Count < 1) { throw new Exception(string.Format("A workflow with the name {0} could not be found!", workflowname)); } else if (workflows.Entities.Count > 1) { throw new Exception(string.Format("More than one workflow with the name {0} found!", workflowname)); } workflowid = workflows.Entities[0].Id; } var results = service.RetrieveMultiple(new FetchExpression(fetchxml)); foreach (var entity in results.Entities) { var req = new ExecuteWorkflowRequest() { EntityId = entity.Id, WorkflowId = workflowid }; try { service.Execute(req); logsuccess(string.Format("Workflow request complete for entity id {0}", entity.Id.ToString())); } catch (Exception ex) { logerror(ex.Message); } } } catch (Exception ex) { logerror(ex.Message); } finally { log("END"); } }
public CRMWorkflow CRMStartWorkflowByID(CRMWorkflow crmWF) { OrganizationServiceProxy _serviceProxy; //IOrganizationService _service; using (_serviceProxy = GetCRMConnection()) { try { // Create an ExecuteWorkflow request. ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = new Guid(crmWF.WorkflowId), EntityId = new Guid(crmWF.EntityId) }; // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request); } catch (Exception ex) { throw; } } return crmWF; }
/// <summary> /// Demonstrates how to programmatically execute a workflow. /// </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(); OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy); CreateRequiredRecords(); //<snippetExecuteWorkflow1> // Create an ExecuteWorkflow request. ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = _workflowId, EntityId = _leadId }; Console.Write("Created ExecuteWorkflow request, "); // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request); Console.WriteLine("and sent request to service."); //</snippetExecuteWorkflow1> #region Check success ColumnSet cols = new ColumnSet("statecode"); QueryByAttribute retrieveOpQuery = new QueryByAttribute(); retrieveOpQuery.EntityName = AsyncOperation.EntityLogicalName; retrieveOpQuery.ColumnSet = cols; retrieveOpQuery.AddAttributeValue("asyncoperationid", response.Id); // Wait for the asyncoperation to complete. // (wait no longer than 1 minute) for (int i = 0; i < 60; i++) { System.Threading.Thread.Sleep(1000); EntityCollection retrieveOpResults = _serviceProxy.RetrieveMultiple(retrieveOpQuery); if (retrieveOpResults.Entities.Count() > 0) { AsyncOperation op = (AsyncOperation)retrieveOpResults.Entities[0]; if (op.StateCode == AsyncOperationState.Completed) { _asyncOperationId = op.AsyncOperationId.Value; Console.WriteLine("AsyncOperation completed successfully."); break; } } if (i == 59) { throw new TimeoutException("AsyncOperation failed to complete in under one minute."); } } // Retrieve the task that was created by the workflow. cols = new ColumnSet("activityid"); QueryByAttribute retrieveActivityQuery = new QueryByAttribute(); retrieveActivityQuery.EntityName = PhoneCall.EntityLogicalName; retrieveActivityQuery.ColumnSet = cols; retrieveActivityQuery.AddAttributeValue("subject", "First call to Diogo Andrade"); EntityCollection results = _serviceProxy.RetrieveMultiple(retrieveActivityQuery); if (results.Entities.Count() == 0) { throw new InvalidOperationException("Phone call activity was not successfully created"); } else { Console.WriteLine("Phone call activity successfully created from workflow."); } #endregion Check success DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }