HTML Dropdown

Tuesday 27 September 2016

Detect Duplicate workflow and cases using C# workflow and FetchXML




Problem:

  1. There is situation when workflow is called on creation and on change event of case initiation date on organisation entity.
  2. Now the problem is if user update the organisation record before the case initiation date started two workflow will be triggered: one on create which is waiting for Case initiation date to create case, other one update of record.

Solution:

To overcome with such kind of problem create a C# Workflow and add the workflow .dll to your actual workflow in CRM. C# Workflow will check whether the case exist or not, if exist it will not create another one.

Step1: Create Workflow in VS

File -> New -> Project -> Visual C# ->Workflow -> Activity Library

Select .NET Framework 4.0 -> For Plugin Registration Tool 2011

Select location and Solution of Project


Step2: Check the Project Settings


Step3: Add Class File DetectDuplicate.cs and remove the .xaml file and add the references like below


Step4: Add the following using statement

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Activities;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Workflow;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Xrm.Sdk.Query;

using System.IO;

using System.Linq.Expressions;

using Microsoft.Xrm.Sdk.Metadata;

Step6: make class Inherit from Code activity

namespace CWFDuplicateCases

    {

 

        public sealed partial class DetectDuplicate : CodeActivity

        {

 

            protected override void Execute(CodeActivityContext executionContext)

                {

                }

 

              

        }

    }

Step7: Declare the Input Parameter/ Output parameter

            [RequiredArgument]

            [Input("Organisation")]

            [ReferenceTarget("account")]

            public InArgument<EntityReference> case_org { get; set; }

 

            [Output("Case Exists")]

            [Default("False")]

            public OutArgument<bool> Bool { get; set; }

Step8: Sign In the assembly

Right Click Project Properties -> Signing


Step9:

Now Go to CRM solution and advanced find like below and Download the fetch XML


Step10: Change the Fetch XML “” to ‘’  customer id value equals to 0

<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

  <entity name='incident'>

    <attribute name='title' />

    <attribute name='ticketnumber' />

    <attribute name='createdon' />

    <attribute name='incidentid' />

    <attribute name='caseorigincode' />

    <order attribute='title' descending='false' />

    <filter type='and'>

      <condition attribute='customerid' operator='eq' uitype='account' value='{0}' />

      <condition attribute='statecode' operator='eq' value='0' />

    </filter>

  </entity>

</fetch>

Step11: Write the code

public sealed partial class DetectDuplicate : CodeActivity

        {

 

            protected override void Execute(CodeActivityContext executionContext)

                {

                //Create the services

                ITracingService tracingService = executionContext.GetExtension<ITracingService>();

                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();

                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                EntityReference Organisation = this.case_org.Get(executionContext);

                Guid orgId = Organisation.Id;

 

                try

                    {

                    if (orgId != Guid.Empty)

                        {

                        //Get all activity metadata related with the case through email

                        tracingService.Trace("CALLING; FETCH ACTIVITY METADATA RELATED WITH CASE");

                        String fetchXmlCases = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

                                                                  <entity name='incident'>

                                                                    <attribute name='title' />

                                                                    <attribute name='ticketnumber' />

                                                                    <attribute name='createdon' />

                                                                    <attribute name='incidentid' />

                                                                    <attribute name='caseorigincode' />

                                                                    <order attribute='title' descending='false' />

                                                                    <filter type='and'>

                                                                      <condition attribute='customerid' operator='eq' uitype='account' value='{0}' />

                                                                      <condition attribute='statecode' operator='eq' value='0' />

                                                                    </filter>

                                                                  </entity>

                                                                </fetch>", orgId);

 

                        // Build fetch request and obtain results.

                        RetrieveMultipleRequest efrOrg = new RetrieveMultipleRequest()

                        {

                            Query = new FetchExpression(fetchXmlCases)

                        };

                        tracingService.Trace("AMD RETREIVED");

                        EntityCollection caseResults = ((RetrieveMultipleResponse)service.Execute(efrOrg)).EntityCollection;

                        if (caseResults.Entities.Count > 0)

                            {

                            Bool.Set(executionContext, true);

 

                            }

                        else

                        {

                        Bool.Set(executionContext, false);

                         }

 

 

                        }

                    }

                catch (Exception ex)

                    {

                    throw new InvalidPluginExecutionException("An error occurred in Workflow assembly.", ex);

                    }

                tracingService.Trace("end of wf");

                }

 

            [RequiredArgument]

            [Input("Organisation")]

            [ReferenceTarget("account")]

            public InArgument<EntityReference> case_org { get; set; }

 

            [Output("Case Exists")]

            [Default("False")]

            public OutArgument<bool> Bool { get; set; }

 

              

        }

Step12: Compile and deploy the assembly

->Rebuild the Solution and deploy it to CRM Systems

->Login to Plugin Registration Tool 2011 -> Bin -> Click on Plugin Registration Tool

->Create a new Connection or Choose Existing (Add URL, username, password)

->Choose the environment in which you want to register (Staging or Production)

->Register New Assembly


Step13: Specify the location where assembly should be stored


Maximize and Register the Selected Plugin

Step14:  Create Process workflow add the workflow dll in CRM



Step15: Create Logic


Set Properties:


Create the logic like below and activate


Testing: