Thursday, 14 November 2019

Dynamic 365, Create Associated view or other OOB view in C#

Sometimes the OOB view deleted mistakenly and it create problems.
The same scenario come with me, I have custom entity Bid and its associated view deleted mistakenly and we need to create one to many relationship with same Bid entity.
But the associated view of custom entity bid is deleted so we can't create relationship.

Through following code i created the associated view of Bid entity and then i create one to many relationship with same bid entity.

                // Create the view.
                System.String layoutXml =@"<grid name='resultset' object='3' jump='ab_name' select='1'
                                            preview='1' icon='1'>
                                            <row name='result' id='ab_bidid'>
                                            <cell name='ab_name' width='150' />
                                            </row>
                                        </grid>";

 System.String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                <entity name='ab_bid'>
                  <attribute name='ab_name' />
                  <attribute name='ab_bidid' />
                  <filter type='and'>
                    <condition attribute='statecode' operator='eq' value='0' />
                  </filter>
                  <order attribute='ab_name' descending='false' />
                </entity>
              </fetch>";
 
                
 
                Entity entity = new Entity("savedquery");
                entity["description"] = "Bid Associated View";
                entity["name"] = "Bid Associated View";
                entity["querytype"] = 2; // 2 is type code of Associated view
                entity["returnedtypecode"] = "ab_bid";  // enity name
                entity["fetchxml"] = fetchXml;
 
                entity["layoutxml"] = layoutXml;
               
                Guid _customViewId = service.Create(entity);

Friday, 9 August 2019

Add Custom View to lookup field and hide all other views in Dynamic 365 in javascript


Follow the below steps to add custom view to lookup field and hide all other views.

1)Go to lookup field on form, select the lookup field and click on change properties button.
Go to the additional properties and set view selector to off.


Step 2)  register this function with form onload event.


function formOnLoad(context) {
        debugger;
        try {
            var formContext = context.getFormContext();
           
            if (formContext.getControl("lookupfieldname") != null) {
                formContext.getControl("lookupfieldname").addPreSearch(function () {
                    filterServiceTypeLookup(context);
                });
            }
         
        } catch (ex) {

        }
    }


function to filter your lookup field record

    function  filterServiceTypeLookup(context) {
       
        try {
            var formContext = context.getFormContext();
            var opp = formContext.getAttribute("ab_opportunityid");
            if (opp != null) {
                var oppValue = opp.getValue();
                if (oppValue != null) {
                    var oppId = oppValue[0].id;
                    oppId = oppId.replace("{", "");
                    oppId = oppId.replace("}", "");
                   
 var fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical'    distinct='true' no-lock='true'>";
                    fetchXML += "<entity name='ab_servicetype'>";
                    fetchXML += "<attribute name='ab_servicetypeid' />";
                    fetchXML += "<attribute name='ab_name' />";
                    fetchXML += "<attribute name='createdon' />";
                    fetchXML += "<order attribute='ab_name' descending='false' />";
                    fetchXML += "<link-entity name='ab_ab_servicetype_opportunity' from='ab_servicetypeid' to='ab_servicetypeid' visible='false' intersect='true'>";
                    fetchXML += "<link-entity name='opportunity' from='opportunityid' to='opportunityid' alias='aa'>";
                    fetchXML += "<filter type='and'>";
                    fetchXML += "<condition attribute='opportunityid' operator='eq' value='" + oppId + "' />";
                    fetchXML += "</filter>";
                    fetchXML += "</link-entity>";
                    fetchXML += "</link-entity>";
                    fetchXML += "</entity>";
                    fetchXML += "</fetch>";

                    var layoutXML = "<grid name='' icon='1' select='1' jump='ab_name' object='10086' preview='1'>";
                    layoutXML += "<row id='ab_servicetypeid' name='ab_servicetype'>";
                    layoutXML += "<cell name='ab_name' width='200' imageproviderfunctionname='' imageproviderwebresource='$webresource:' />";
                    layoutXML += "<cell name='createdon' width='200' imageproviderfunctionname='' imageproviderwebresource='$webresource:' />";
                    layoutXML += "</row>";
                    layoutXML += "</grid>";

                    var viewId = "{AEFB3055-52B4-491C-B0CF-11AEFDF82825}"  // lookup view id

                    var entityName = "entityname";
                    var viewDisplayName = "Filtered View Name";

                    formContext.getControl("ab_servicetypeid").addCustomView(viewId, entityName, viewDisplayName, fetchXML, layoutXML, true);
                 
                }
            }
        } catch (ex) {

        }
    }


Step 3)
 view id is the lookup view id of the entity
 var viewId = "{AEFB3055-52B4-491C-B0CF-11AEFDF82825}

Wednesday, 31 July 2019

Show Hide Control on form in JavaScript on record status Changed dynamic 365

One of our client requirements to show custom entity grid on opportunity form when opportunity is closed as won otherwise hide the grid.
To achieve the requirement, I add the custom entity grid to section on form and register a custom JavaScript function with statuscode field.

JavaScript code of function

function showHidSubGridProjectSectionOnStatusChange ()
{
        var oppStatus = Xrm.Page. getAttribute("statuscode"). getValue();                   
        if (oppStatus == 3) {   //3 is for Won opportunity
            Xrm.Page.ui.tabs.get("Summary"). sections.get("section_subgridProjects"). setVisible(true);                
        } else {
            Xrm.Page.ui.tabs.get("Summary"). sections.get("section_subgridProjects"). setVisible(false);                             
        }
 }



To trigger the JavaScript function, click on close As won button and when click on Ok button the function will called.



I am showing the highlighted section when opportunity status become won otherwise I hide it.



This method works for any entity if you want to trigger JavaScript function on record status change.
Every entity in CRM has OOB field statuscode register JavaScript function with statuscode field.
When record status the JavaScript code will execute.

That’s it for today, I hope it helped you.

Change Display name of Managed Field in Dynamic 365


Sometime we need to change the Display name of Managed field in Dynamic 365.

The following code is used to change the Display name of Managed field.  

IOrganizationService orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;


RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest

                {
                    EntityLogicalName = Opportunity.EntityLogicalName,

                    LogicalName = "parentaccountid",

                    RetrieveAsIfPublished = true

                };

                // Execute the request

                RetrieveAttributeResponse attributeResponse =

                   (RetrieveAttributeResponse)orgService.Execute(attributeRequest);

                Console.WriteLine("Retrieved the attribute {0}.",

                   attributeResponse.AttributeMetadata.SchemaName);

                // Modify the retrieved attribute

                AttributeMetadata retrievedAttributeMetadata =

                   attributeResponse.AttributeMetadata;

                retrievedAttributeMetadata.DisplayName =

                   new Label("Bidding To", 1033);

                // Update an attribute retrieved via RetrieveAttributeRequest



                UpdateAttributeRequest updateRequest = new UpdateAttributeRequest

                {

                    Attribute = retrievedAttributeMetadata,
                   

                    EntityName = Opportunity.EntityLogicalName,

                    MergeLabels = false
                   

                };

                // Execute the request

                orgService.Execute(updateRequest);

Wednesday, 22 May 2019

Retrieve Local Option set metadata in java script using webapi, Dynamic 365

   function GetOptionSetOptionValue(optionText, optionSetLogicalName)
{
        debugger;
        var req = new XMLHttpRequest();
        req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/EntityDefinitions(LogicalName='ab_bid')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$filter=LogicalName eq '" + optionSetLogicalName + "' &$expand=OptionSet", false);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
        req.send(null);
        if (req.readyState === 4) {
            req.onreadystatechange = null;
            if (req.status === 200) {
                var results = JSON.parse(req.response);
                debugger;
                for (var i = 0; i < results.value[0].OptionSet.Options.length; i++) {
                    debugger;
                    var Label = results.value[0].OptionSet.Options[i].Label.UserLocalizedLabel.Label;
                    if (Label.trim().toLowerCase() == optionText.trim().toLowerCase()) {
                        return results.value[0].OptionSet.Options[i].Value;
                    }
                    //alert(Label);
                }
            } else {
                Xrm.Utility.alertDialog(req.statusText);
            }
        }
    }

Thursday, 16 May 2019

Retrieve note from opportunity and associate with custom entity note in C#



private void RetrieveRelatedNoteFromOppAndAttachWithBid(IOrganizationService orgService, Guid oppId, Guid bidId)
        {
            try
            {
                string fetchxml = @"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
                                    <entity name='annotation'>
                                    <attribute name='subject'/>
                                    <attribute name='notetext'/>
                                    <attribute name='filename'/>
                                    <attribute name='annotationid'/>
                                    <attribute name='isdocument'/>
                                    <attribute name='filesize'/>
                                    <attribute name='mimetype' />
                                    <attribute name='documentbody'/>
                                    <order descending='true' attribute='createdon'/>
                                    <filter type='and'>
                                       <condition attribute='objectid' operator='eq' value='" + oppId + @"'/>
                                    </filter>
                                    </entity>
                                    </fetch>";
                EntityCollection results = orgService.RetrieveMultiple(new FetchExpression(fetchxml));
                if (results.Entities.Count > 0)
                {
                    Entity noteOpp = results.Entities[0];
                    Entity noteBid = new Entity("annotation");
                    noteBid["objectid"] = new EntityReference("ab_bid", bidId);
                    noteBid["objecttypecode"] = "ab_bid";
                    noteBid["subject"] = noteOpp["subject"];
                    noteBid["documentbody"] = noteOpp["documentbody"];
                    noteBid["mimetype"] = noteOpp["mimetype"];
                    noteBid["filename"] = noteOpp["filename"];

                    orgService.Create(noteBid);
                    orgService.Delete(noteOpp.LogicalName, noteOpp.Id);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }

Monday, 22 April 2019

Fetch Xml query in webapi Javascript Dynamic 365

    try {

    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical'                                                              distinct='false'>";
fetchXml += "<entity name='opportunity'>";
fetchXml += "<attribute name='budgetamount' />";
fetchXml += "<attribute name='statuscode' />";
fetchXml += "<attribute name='opportunityid' />";
fetchXml += "<attribute name='name' />";
fetchXml += "<attribute name='createdby' />";
fetchXml += "<attribute name='ss_requesttype' />";
fetchXml += "<order attribute='name' descending='false' />";
fetchXml += "<filter type='and'>";
fetchXml += "<condition attribute='opportunityid' operator='in'>";
for (var i = 0; i < arrayVals.length; i++) {
var oppId = arrayVals[i].replace("{", "").replace("}", "");
fetchXml += "<value uitype='opportunity'>" + oppId + "</value>";
}
fetchXml += "</condition>";
fetchXml += "</filter>";
fetchXml += "</entity>";
fetchXml += "</fetch>";

        var webapiPath = lXrm.Page.context.getClientUrl() + "/api/data/v9.1/opportunities?fetchXml=" + encodeURIComponent(fetchXml);
        var service = new XMLHttpRequest();
        service.open("GET", webapiPath, false);
        service.setRequestHeader("Accept", "application/json");
        service.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        service.setRequestHeader("OData-MaxVersion", "4.0");
        service.setRequestHeader("OData-Version", "4.0");
        service.setRequestHeader("Prefer", "odata.include-annotations=*");
        //service.setRequestHeader("Prefer", "odata.maxpagesize = 3"); this tag isused to retrieve no of //records
        service.send(null);

        if (service.readyState == 4 /* complete */) {
            if (service.status == 201 || service.status == 200) {
                var result = eval('(' + service.responseText + ')');
                if (result.value.length > 0) {
                   
                    for (var i = 0; i < result.value.length; i++) {
                        var opportunityid = result.value[i].opportunityid;
                        var name = result.value[i].name;
                        var budgetamount = result.value[i].budgetamount;
                        var createdby = result.value[i]['_createdby_value@OData.Community.Display.V1.FormattedValue'];
                       
                    }
                   
                }
            }
        }
    } catch (ex) {

    }

Monday, 15 April 2019

Web API request to refresh Rollup field Dynamic 365 through JavaScript

The following JS function is used to refresh Rollup field through webapi fom javascript

function calcRollupField(serverURL,strTargetEntitySetName, strTargetRecordId, strTargetFieldName)
{
    strTargetRecordId = strTargetRecordId.replace("{", "").replace("}", "");
    var req = new XMLHttpRequest();
    req.open("GET", serverURL + "/api/data/v9.0/" +
        "CalculateRollupField(Target=@p1,FieldName=@p2)?" +
        "@p1={'@odata.id':'" + strTargetEntitySetName + "(" + strTargetRecordId + ")'}&" +
        "@p2='" + strTargetFieldName + "'", false);
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.onreadystatechange = function () {
        if (req.readyState === 4) {
            req.onreadystatechange = null;
            if (req.status === 200) {
                var results = JSON.parse(this.response);
            }
            else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify({}));
}

Monday, 25 February 2019

Show only Account or Contact in customer lookup dynamic 365


To show only account or contact in customer lookup, follow the below steps

1) On Load of form add the following code

if (Xrm.Page.getControl("customerid") != null) {
            Xrm.Page.getControl("customerid").addPreSearch(function () {
                filterCustomerLookup ();
            });
        }

2)Register this function on OnChange event of customer lookup to show only account in customer lookup

    function filterCustomerLookup () {

        var lookup = Xrm.Page.getControl('customerid');

        //check if multiple type dropdowns enabled for this lookup
        if (lookup.getEntityTypes().length > 1) {
            lookup.setEntityTypes(['account']);
        }

        var fetchXml = "<filter type='and'>";
        fetchXml += "<condition attribute='statecode' operator='eq' value='0'/>";
        fetchXml += "</filter>";

        if (Xrm.Page.getAttribute("customerid") != null) {
            Xrm.Page.getControl("customerid").addCustomFilter(fetchXml, "account");
        }
    }



To show only contact  then change account to contact.

function filterCustomerLookup () {

        var lookup = Xrm.Page.getControl('customerid');

        //check if multiple type dropdowns enabled for this lookup
        if (lookup.getEntityTypes().length > 1) {
            lookup.setEntityTypes(['account']);
        }

        var fetchXml = "<filter type='and'>";
        fetchXml += "<condition attribute='statecode' operator='eq' value='0'/>";
        fetchXml += "</filter>";

        if (Xrm.Page.getAttribute("customerid") != null) {
            Xrm.Page.getControl("customerid").addCustomFilter(fetchXml, "contact");
        }
    }


Read only field , get latest value from read only field in in power app portal

Below line is used to make field readonly in power app portal through js $( "#bdo_relationshiprole_name" ).parent().css( "po...