Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

How to Retrieve the value of an optionset field within a plugin

 

In Dynamics 365 C# Plugin, if retrieve optionset type fields value, you may need to convert the object to optionsetvalue type before quote its value. See below bold red code.

namespace UpdateTasksByOpportunity.Plugin

{

    public class ChangeAllKidEntityRecordsStatusByParentEnty : IPlugin

    {

        public void Execute(IServiceProvider serviceProvider)

        {

            // Obtain the tracing service

            ITracingService tracingService =

            (ITracingService)serviceProvider.GetService(typeof(ITracingService));


            // Obtain the execution context from the service provider.  

            IPluginExecutionContext context = (IPluginExecutionContext)

                serviceProvider.GetService(typeof(IPluginExecutionContext));


            // The InputParameters collection contains all the data passed in the message request.  

            if (context.InputParameters.Contains("Target") &&

                (context.InputParameters["Target"] is Entity ||

                context.InputParameters["Target"] is EntityReference))

            {


                Guid regardingobjectid = Guid.NewGuid();


                if (context.InputParameters["Target"] is Entity)

                {

                    // Obtain the Parent entity from the input parameters.  

                    Entity entity = (Entity)context.InputParameters["Target"];


                    // Refer to the opportunity in the task activity.

                    // Get the current opportunity ID / Parent Entity GUID            

                    regardingobjectid = new Guid(entity.Id.ToString());

                }


                else if (context.InputParameters["Target"] is EntityReference)

                {

                    // Obtain the Parent entity reference from the input parameters.  

                    EntityReference entityReference = (EntityReference)context.InputParameters["Target"];


                    // Refer to the opportunity in the task activity.

                    // Get the current opportunity ID / Parent Entity GUID            

                    regardingobjectid = new Guid(entityReference.Id.ToString());

                }


               


                // Obtain the organization service reference which you will need for  

                // web service calls.  

                IOrganizationServiceFactory serviceFactory =

                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

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


                //Check if Opportunity status is changed to "OPEN". If not, return.

                //0 - "OPEN";  1 - "WON";  2 - "LOST"

                Entity entityOpportunity = service.Retrieve("opportunity", regardingobjectid, new ColumnSet("statecode"));

                if(((OptionSetValue)entityOpportunity["statecode"]).Value != 0)

                {

                    tracingService.Trace("Opportunity new status: {0} is not OPEN", ((OptionSetValue)entityOpportunity["statecode"]).Value);

                    return;

                }



                //0 Open;  1 Completed;  2 Canceled

                int stateCode = 2;

                string kidEntity = "task";


                try

                {

                    // Retrieve all tasks with regarding opportunity is current opportunity

                    var queryExpression = new QueryExpression(kidEntity);

                    var qeFilter = new FilterExpression(LogicalOperator.And);

                    qeFilter.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Open"));

                    qeFilter.AddCondition(new ConditionExpression("subject", ConditionOperator.Like, "%F/U%"));

                    qeFilter.AddCondition(new ConditionExpression("description", ConditionOperator.Like, "%Automated Task%"));

                    qeFilter.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Like, regardingobjectid));

                    queryExpression.Criteria = qeFilter;

                    queryExpression.ColumnSet = new ColumnSet("regardingobjectid");


                    //Get results:

                    var result = service.RetrieveMultiple(queryExpression);

                    foreach (var relatedTask in result.Entities)

                    {

                        

                        // Create the Request Object

                        var state = new SetStateRequest();

                        state.State = new OptionSetValue(stateCode);


                        // Point the Request to the case whose state is being changed

                        state.EntityMoniker = new EntityReference(kidEntity, relatedTask.Id);


                        // Execute the Request

                        var stateSet = (SetStateResponse)service.Execute(state);                                             

                    }

                }


                catch (FaultException<OrganizationServiceFault> ex)

                {

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

                }


                catch (Exception ex)

                {

                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());

                    throw;

                }

            }

        }

    }


    [Serializable]

    internal class FaultException<T> : Exception

    {

        public FaultException()

        {

        }


        public FaultException(string message) : base(message)

        {

        }


        public FaultException(string message, Exception innerException) : base(message, innerException)

        {

        }


        protected FaultException(SerializationInfo info, StreamingContext context) : base(info, context)

        {

        }

    }

}

Query Expression Add Criteria for look up field (Dynamics 365

Microsoft Dynamics 365 Plugin C# code.

If you wanna retrieve multiple records, you may use RetrieveMultiple function.

You can set filters and select the columns(fields) in the retrieve response.

When I set a filter for a lookup field (GUID), I tried two ways.





Both options work normally, the second way is better, greatly reduced the Amount of retrieved records, better for system performance. But the first way is still a good try for reading and comparing GUID value from retrieve response.

Option 1:  Add filter in retrieve result procession. (Bad performance.)

// Retrieve all tasks with regarding opportunity is current opportunity

var queryExpression = new QueryExpression(kidEntity);

var qeFilter = new FilterExpression(LogicalOperator.And);

qeFilter.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Open"));

qeFilter.AddCondition(new ConditionExpression("subject", ConditionOperator.Like, "%F/U%"));

qeFilter.AddCondition(new ConditionExpression("description", ConditionOperator.Like, "%Automated Task%"));

queryExpression.Criteria = qeFilter;

queryExpression.ColumnSet = new ColumnSet("regardingobjectid");

//Get results:

var result = service.RetrieveMultiple(queryExpression);

foreach (var relatedTask in result.Entities)

{

    if(((EntityReference)relatedTask.Attributes["regardingobjectid"]).Id.ToString() == (regardingobjectid).ToString())

    {

        // Create the Request Object

        var state = new SetStateRequest();

        state.State = new OptionSetValue(stateCode);

        // Point the Request to the case whose state is being changed

        state.EntityMoniker = new EntityReference(kidEntity, relatedTask.Id);

        // Execute the Request

        var stateSet = (SetStateResponse)service.Execute(state);

    }                        

}


Option 2:  Add the filter into the query expression criteria. (Good performance.)

// Retrieve all tasks with regarding opportunity is current opportunity

var queryExpression = new QueryExpression(kidEntity);

var qeFilter = new FilterExpression(LogicalOperator.And);

qeFilter.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Open"));

qeFilter.AddCondition(new ConditionExpression("subject", ConditionOperator.Like, "%F/U%"));

qeFilter.AddCondition(new ConditionExpression("description", ConditionOperator.Like, "%Automated Task%"));

qeFilter.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Like, regardingobjectid));

queryExpression.Criteria = qeFilter;

queryExpression.ColumnSet = new ColumnSet("regardingobjectid");


//Get results:

var result = service.RetrieveMultiple(queryExpression);

foreach (var relatedTask in result.Entities)

{    

        // Create the Request Object

        var state = new SetStateRequest();

        state.State = new OptionSetValue(stateCode);

        // Point the Request to the case whose state is being changed

        state.EntityMoniker = new EntityReference(kidEntity, relatedTask.Id);

        // Execute the Request

        var stateSet = (SetStateResponse)service.Execute(state);                 

}