Monday, April 15, 2024

Dynamics CE: Retrieve record based on account Id and find the GUID from entity reference

 The following code can be used to retrieve the record and find the GUID of the lookup field.


using System;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Xrm.Sdk.Query;


namespace XMA_UpdateOppotunityAccOwner.XMA_UpdateOpportunityAccOwner

{


  

    public class PostOperationaccountUpdate: IPlugin

    {

        public void Execute(IServiceProvider serviceProvider)

        {

            //Initializing Service Context.

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

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


            try

            {

                //Defining Entity Object.

                Entity eTarget = null;

                if (context.MessageName == "Update")

                {

                    eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ?

                    context.InputParameters["Target"] as Entity : null;

                    Guid accountIdGuid = eTarget.GetAttributeValue<Guid>("accountid");


                    RetrieveRequest request = new RetrieveRequest()

                    {

                        ColumnSet = new ColumnSet("ownerid"),

                        Target = new EntityReference("account", accountIdGuid)

                    };

                    var response = (RetrieveResponse)service.Execute(request);

                    Entity entity = response.Entity;

               Guid ownerId = ((EntityReference)entity.Attributes["ownerid"]).Id;//Find Guid from a lookup


                    RetrieveRequest requestUer = new RetrieveRequest()

                    {

                        ColumnSet = new ColumnSet("fullname"),

                        Target = new EntityReference("systemuser", ownerId)

                    };

                    response = (RetrieveResponse)service.Execute(requestUer);

                    entity = response.Entity;

                    var ownerName = entity["fullname"];


                    QueryExpression query = new QueryExpression();

                    query.EntityName = "opportunity";

                    query.ColumnSet = new ColumnSet("opportunityid", "parentaccountid", "name");


                    FilterExpression filter = new FilterExpression(LogicalOperator.And);

                    filter.AddCondition("parentaccountid", ConditionOperator.Equal, accountIdGuid);

                    query.Criteria.AddFilter(filter);


                    EntityCollection entityCollection = service.RetrieveMultiple(query);


                    if (entityCollection.Entities.Count > 0)

                    {

                        int TotalAccountCount = entityCollection.Entities.Count;

                        foreach (var accountEntity in entityCollection.Entities)

                        {

                            //Stage 6.

                            Entity opportunity = new Entity("opportunity");

                            opportunity.Id = accountEntity.Id;

                            opportunity["fieldName"] = ownerName;

                            service.Update(opportunity);

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                throw new InvalidPluginExecutionException(ex.Message);

            }

        }

    }

}


Regards,

Arun S Keerthi



Saturday, April 6, 2024

Dynamics 365 CE: Create C# plugin, search related records and update records

 The following C# plugin is used to fetch the record through relation and update contact records.

using System;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Xrm.Sdk.Query;


namespace XMA_ContactEntityUpdate_Plugin.XMA_ContactEntityUpdate

{

    /// <summary>

    /// PostOperationaccountUpdate Plugin.

    /// </summary>    

    public class PostOperationaccountUpdate: IPlugin

    {

        public void Execute(IServiceProvider serviceProvider)

        {

            //Initializing Service Context.

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

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


            try

            {

                //Defining Entity Object.

                Entity eTarget = null;

                if (context.MessageName == "Update")

                {                    

                    eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ?

                    context.InputParameters["Target"] as Entity : null;                    

                    Guid accountIdGuid = eTarget.GetAttributeValue<Guid>("accountid");                                

                    QueryExpression query = new QueryExpression();

                    query.EntityName = "EntityName";

                    query.ColumnSet = new ColumnSet("columname");


                    Relationship relationship = new Relationship("relation_name");

                    relationship.PrimaryEntityRole = EntityRole.Referenced;


                    RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

                    relatedEntity.Add(relationship, query);


                    RetrieveRequest request = new RetrieveRequest();

                    request.RelatedEntitiesQuery = relatedEntity;

                    request.ColumnSet = new ColumnSet("name");

                    request.Target = new EntityReference("account", accountIdGuid);


                    RetrieveResponse response = (RetrieveResponse)service.Execute(request);

                    

                    foreach (var industry in response.Entity.RelatedEntities[relationship].Entities)

                    {

                        var phone = industry["name"];


                        if (industryName != null)

                        {                            

                            QueryExpression qeContactUpdate = new QueryExpression("contact");

                            qeContactUpdate.ColumnSet.AddColumns("contactname");

                            FilterExpression filterUpdate = new FilterExpression(LogicalOperator.And);

                            filterUpdate.AddCondition("accountid", ConditionOperator.Equal, accountIdGuid);

                            qeContactUpdate.Criteria.AddFilter(filterUpdate);

                            EntityCollection entityCollectionUpdate = service.RetrieveMultiple(qeContactUpdate);


                            if (entityCollectionUpdate.Entities.Count > 0)

                            {                                

                                foreach (var entity in entityCollectionUpdate.Entities)

                                {

                                    if (entity.Id != null)

                                    {

                                        Entity eContactUpdate = new Entity("contact");

                                        eContactUpdate.Id = entity.Id;

                                        eContactUpdate["phone"] = phone;

                                        service.Update(eContactUpdate);

                                    }

                                }

                            }

                        }

                    }                    

                }

            }

            catch (Exception ex)

            {

                throw new InvalidPluginExecutionException(ex.Message);

            }

        }

    }

}

Regards,

Arun S Keerthi

Wednesday, April 3, 2024

Dynamics 365 CE: Call Xrm.WebApi using asynchronous call (async and await)

The following code can be used to call Xrm.Webapi using async and await.


function assignIndustryToContact(executionContext){
    var formContext = executionContext.getFormContext();    
    var accountId = formContext.getAttribute("parentcustomerid").getValue();

    if (accountId != null){
        getIndustryName(executionContext);              
    }
}

async function getIndustryName(executionContext){
    var formContext = executionContext.getFormContext();  
    var accountId = formContext.getAttribute("parentcustomerid").getValue();
    var accountIdGUID = accountId[0].id;    
    let industry = await Xrm.WebApi.retrieveRecord("account", accountIdGUID, "?$select=name,industryid");  
     
    if (industry._igl_industryid_value != null){
        let industryName = await Xrm.WebApi.retrieveRecord("igl_industry", industry.industryid, "?$select=name");
        formContext.getAttribute("fieldName").setValue(industryName.name);
    }  
}


Regards,

Arun S Keerthi

Saturday, March 30, 2024

Dynamics 365 F&O: Create form control and form event handler

 This post describes the steps and code required to create an event handler for SalesTable form.

1. Create a class

class salesTableForm_EventHandler

{


}

2. Open SalesTable form Events node.

3. Right click the event and Copy Event Handler Method

4. Paste the code in the class you created.


[FormEventHandler(formStr(SalesTableListPage), FormEventType::Activated)]
public static void SalesTableListPage_OnActivated(xFormRun sender, FormEventArgs e)
{
    XMA_SalesOrderLoqateAddressList_Table   addressList;  
    FormDataSource  salesTable_ds = sender.dataSource(formDataSourceStr(SalesTable, SalesTable));
    FormControl buttonUpdateConfirmation = sender.control(sender.controlId('buttonUpdateConfirmation'));
    SalesTable salesTable = salesTable_ds.cursor();

    if (salesTable.deliveryAddress == NoYes::Yes)
    {
        buttonUpdateConfirmation.visible(true);            
    }
    else
    {
        buttonUpdateConfirmation.visible(false);
    }
}


5. Right click the form control and copy Event Handler method


[FormControlEventHandler(formControlStr(SalesTable, CopyOfReferenceGroup), FormControlEventType::Modified)]
public static void CopyOfReferenceGroup_OnModified(FormControl sender, FormControlEventArgs e)
{
    FormDataSource  salesTable_ds = sender.formRun().dataSource(formDataSourceStr(SalesTable, SalesTable));
    FormControl buttonUpdateConfirmation = sender.formRun().design().controlName('buttonUpdateConfirmation');
    SalesTable salesTable = salesTable_ds.cursor();
    SalesTable salesTableOrig = salesTable.orig();
   
    if (salesTable.deliveryAddress().RecId != salesTableOrig.deliveryAddress().RecId)
    {
        Error("Error");
        ttsbegin;
        salesTable.deliveryAddress = 555665544;
        salesTable.doUpdate();
        ttscommit;
        sender.formRun().reload();            
        buttonUpdateConfirmation.visible(false);            
    }            
}


Regards,

Arun S Keerthi



Tuesday, March 26, 2024

Dynamics 365 CE: Set and clear notification on a field using JavaScript

The following JavaScript code can be used to set and clear notification on a field.

formContext.getControl("attributename").setNotification("Message");                            
formContext.getControl("attributename").clearNotification();


formContext.ui.setFormNotification("Your message", "WARNING", "MessageID001");
formContext.ui.clearFormNotification("MessageID001");

Regards,

Arun S Keerthi

Monday, March 25, 2024

Dynamics 365 CE: Set lookup field value from a related record using JavaScript

 The following JavaScript code can be used to set a lookup field's value by retrieving the record from the child table and assign it to the parent table's related field on a form. 


Xrm.WebApi.retrieveRecord(entityName, '00000000-0000-0000-0000-000000000001', "?$select=field_name")
                .then(
                    function success(result1) {                                                                                                
                        var lookupValue             = new Array();
                        lookupValue[0]              = new Object();                        
                        lookupValue[0].id           = LookupFieldId;
                        lookupValue[0].name         = result1.field_name;
                        lookupValue[0].entityType   = "LookupEntityName";
                       
                        formContext.getAttribute("FormLookupAAttributeName").setValue(lookupValue);                            
                    },
                    function (error) {
                        console.log(error.message);
                    }
                );

Regards,

Arun S Keerthi

Dynamics 365 CE: Set a field visible using JavaScript

The following JavaScript code can be used to make a field Visible in Dynamics 365 app. 


function showField(executionContext){
    var formContext = executionContext.getFormContext();

    var attributename = formContext.getAttribute("attributename");

    if (attributename == true){
        formContext.getControl("attributename1").setVisible(false);
    }

}