Friday, October 11, 2024

D365 F&O Form refresh event handler

 [FormDataSourceEventHandler(formDataSourceStr(SalesTable, SalesTable), FormDataSourceEventType::Refreshed)]

public static void SalesTable_OnRefreshed(FormDataSource sender, FormDataSourceEventArgs e)

{

    FormRun formRun = sender.formRun();

    FormDataSource  salesTable_ds   = sender;

    SalesTable salesTable           = salesTable_ds.cursor();

    

    FormControl buttonUpdateConfirmation = formRun.control(formRun.controlId('button'));

    

    if (salesTable.active == NoYes::Yes)

    {

        buttonUpdateConfirmation.enabled(true);

    }

    else

    {

        buttonUpdateConfirmation.enabled(false);

    }

}

D365 F&O form refresh after pressing button using event handler

 [FormControlEventHandler(formControlStr(SalesTable, Button), FormControlEventType::Clicked)]

public static void Button_OnClicked(FormControl sender, FormControlEventArgs e)

{

       #Task

    FormDataSource  salesTable_ds = sender.formRun().dataSource(formDataSourceStr(SalesTable, SalesTable));        

    SalesTable salesTable = salesTable_ds.cursor();

           

    sender.formRun().dataSource(formDataSourceStr(SalesTable, SalesTable)).refreshEx();

    salesTable_ds.refresh();

    salesTable_ds.research(true);

    sender.formRun().task(#taskF5);

}

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