Thursday, 26 May 2016

CRM 2016/2015/2013: Applying custom FetchXml to a subgrid using JavaScript

I have faced a scenario to show Account related contacts emails in sub-grid on account form.
In my scenario there is a many to many relationship between account and contact.
and i want to show Account related contacts emails in sub-grid on Account.

To achieve this goal i add a sub-grid of emails on account form.



Then i developed fetch XML in advanced find to show account related contacts emails.

var FetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
                                "<entity name='email'>" +
                                    "<attribute name='subject' />" +
                                    "<order attribute='subject' descending='false' />" +
                                    "<attribute name='to' />" +
                                    "<attribute name='from' />" +
                                    "<attribute name='createdon' />" +
                                    "<attribute name='activityid' />" +
                                    "<link-entity name='activityparty' from='activityid' to='activityid' alias='ad'>" +
                                       "<link-entity name='contact' from='contactid' to='partyid' alias='ae'>" +
                                       "<link-entity name='new_account_contact' from='contactid' to='contactid' visible='false' intersect='true'>" +
                                           "<filter type='and'>" +
                                            "<condition attribute='accountid' uitype='account' value='" + accountid + "' operator='eq'/>" +
                                         "</filter>" +
                                       "</link-entity>" +
                                     "</link-entity>" +
                                    "</link-entity>" +
                                    "</entity>" +
                                  "</fetch>";


To apply this custom fetch XML  to the sub-grid i used the below JavaScript function.

function dynamicallyFilterSubGrid() {
    var objSubGrid = window.parent.document.getElementById("RelatedContactEmails");
    //CRM loads subgrid after form is loaded.. so when we are adding script on form load.. need to wait unitil subgrid is loaded.
    // thats why adding delay..
    if (objSubGrid == null) {
        setTimeout(dynamicallyFilterSubGrid, 2000);
        return;
    }
    else {
        if (objSubGrid.control != null) {
            var accountid = Xrm.Page.data.entity.getId();
            var FetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>" +
                                "<entity name='email'>" +
                                    "<attribute name='subject' />" +
                                    "<order attribute='subject' descending='false' />" +
                                    "<attribute name='to' />" +
                                    "<attribute name='from' />" +
                                    "<attribute name='createdon' />" +
                                    "<attribute name='activityid' />" +
                                    "<link-entity name='activityparty' from='activityid' to='activityid' alias='ad'>" +
                                       "<link-entity name='contact' from='contactid' to='partyid' alias='ae'>" +
                                       "<link-entity name='new_account_contact' from='contactid' to='contactid' visible='false' intersect='true'>" +
                                           "<filter type='and'>" +
                                            "<condition attribute='accountid' uitype='account' value='" + accountid + "' operator='eq'/>" +
                                         "</filter>" +
                                       "</link-entity>" +
                                     "</link-entity>" +
                                    "</link-entity>" +
                                    "</entity>" +
                                  "</fetch>";
            objSubGrid.control.SetParameter("fetchXml", FetchXml);
            objSubGrid.control.Refresh();
        }
        else {
            setTimeout(dynamicallyFilterSubGrid, 2000); // this setTimeout function is necessay because first objSubGrid.control is null
        }
    }
}

Lead not able to qualify in Microsoft Dynamics CRM

When qualifying Lead and it throw error like 

"An error has occurred. Either the data does not exist or you do not have sufficient privileges to view the data. Contact your system administrator for help" 

This error is basically occur because someone have deleted Stakeholder connection role from the CRM.

The Process of adding Stakeholder connection role to the CRM.
Create a solution in the org in which lead is qualifying successfully.
then add the Stakeholder connection role to the solution then export the solution and import the solution to the org in which lead is not qualifying and the above error is coming.
and publish the solution.

so the  above error will be resolved.


Friday, 20 May 2016

Delete Record in in Microsoft Dynamics CRM 2016 using Web API


  function DeleteAccount() {
      //get Server url
        var serverURL = Xrm.Page.context.getClientUrl();

        //create Xml request object 
        var service = new XMLHttpRequest();

        //below line is used to delete the entity record  
        service.open("DELETE", serverURL + "/api/data/v8.0/accounts(1DD18913-11CB-E511-80D2-C4346BDC11C1)", 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.send();

        if (service.readyState == 4 /* complete */) {
        if (service.status == 204) {
            //show alert message 
            alert('Field Value Deleted');
        }
        else {
            var error = JSON.parse(service.response).error;
            //show error message
            alert(error.message);
        }
    }      
}
 

Update Record in Microsoft Dynamics CRM 2016 using Web API


  function UpdateAccount() {

    var serverURL = Xrm.Page.context.getClientUrl();
    var account = {};
    account["name"] = "Create record Web API Example"; //set single line of text field
    account["address1_city"] = "Islamabad";//set single line of text field
    //Lookup
    account["primarycontactid@odata.bind"] = "/contacts(0D7AFC02-891C-E611-80E1-5065F38B0371)";  //setting existing lookup
    //Below code will create contact on fly and set in primarycontact 
    //account["primarycontactid"] = {
    //    "firstname": "Mahender",
    //    "lastname": "Pal"
    //};

    //optionset
    account["industrycode"] = 1; // set optionSet field
    //two options
    account["donotphone"] = true; //set boolean field
    //number
    account["numberofemployees"] = 20;//set whole no field
    //date time
    //account["him_approvaldate"] = new Date();

    var req = new XMLHttpRequest();
    req.open("PATCH", serverURL + "/api/data/v8.0/accounts(1DD18913-11CB-E511-80D2-C4346BDC11C1)", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.send(JSON.stringify(account));

    if (req.readyState == 4 /* complete */) {
        if (req.status == 204) {
            
        } else {
            
        }
    }
}
 

Create Record in Microsoft Dynamics CRM 2016 using Web API


  function CreateAccount() {

    var serverURL = Xrm.Page.context.getClientUrl();
    var account = {};
    account["name"] = "Create record Web API Example"; //set single line of text field
    account["address1_city"] = "Islamabad";//set single line of text field
    //Lookup
    account["primarycontactid@odata.bind"] = "/contacts(0D7AFC02-891C-E611-80E1-5065F38B0371)";  //setting existing lookup
    //Below code will create contact on fly and set in primarycontact 
    //account["primarycontactid"] = {
    //    "firstname": "Mahender",
    //    "lastname": "Pal"
    //};

    //optionset
    account["industrycode"] = 1; // set optionSet field
    //two options
    account["donotphone"] = true; //set boolean field
    //number
    account["numberofemployees"] = 20;//set whole no field
    //date time
    //account["him_approvaldate"] = new Date();

    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.0/accounts", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.send(JSON.stringify(account));

    if (req.readyState == 4 /* complete */) {
        if (req.status == 204) {
            var accountUri = this.getResponseHeader("OData-EntityId");
            var ID = accountUri.substr(accountUri.length - 38).substring(1, 37); //get only GUID
           // Xrm.Utility.openEntityForm("account", ID); //Open newly created account record
        } else {
            var error = JSON.parse(req.response).error;
            alert(error.message);
        }
    }
}
 

Create Activity and associated Activity Party in Microsoft Dynamics CRM 2016 using Web API


 function CreateEmail() {
    var quoteId = Xrm.Page.data.entity.getId();
    quoteId = quoteId.replace(/[{}]/g, "");
    var OwnerLookup = Xrm.Page.getAttribute("ownerid").getValue();
    OwnerGuid = OwnerLookup[0].id;
    OwnerGuid = OwnerGuid.replace(/[{}]/g, "");
    var CustomerLookUp = Xrm.Page.getAttribute("customerid").getValue();
    var AccountId = CustomerLookUp[0].id;
    AccountId = AccountId.replace(/[{}]/g, "");

    var webapiPath = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/emails";
    var email = {};
    //Lookup
    email["regardingobjectid_quote@odata.bind"] = "/quotes(" + quoteId + ")"; //Regarding is quote
    email["subject"] = "New Email";
    email["description"] = "Email Description";
    var parties = [];
    //ActivityParty (From)
    var sender = {};
    sender["partyid_systemuser@odata.bind"] = "/systemusers(" + OwnerGuid + ")";
    sender["participationtypemask"] = 1; //From

    //ActivityParty (To)
    var receiver = {};
    receiver["partyid_account@odata.bind"] = "/accounts(" + AccountId + ")";
    receiver["participationtypemask"] = 2; //To 
    //add this to collection
    parties.push(sender);
    parties.push(receiver);

    email["email_activity_parties"] = parties;

    var service = new XMLHttpRequest();
    service.open("POST", 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.send(JSON.stringify(email));
    if (service.readyState == 4 /* complete */) {
        if (service.status == 204) {
            
        }
    }
}
ActivityParty entity : https://msdn.microsoft.com/en-us/library/gg328549.aspx

Thursday, 19 May 2016

Query Data using the Web API

In the below function RetrieveParentAccount() i want to  show how to retrieve string, option Set, lookup and  to Two Option fields
I have test the   RetrieveParentAccount() function on form OnLoad of contact entity.


  function RetrieveParentAccount() {
   
    var accountLookup = Xrm.Page.getAttribute("parentcustomerid");
    if (accountLookup != null) {
        var accountLookupValue = accountLookup.getValue();
        var accountGuid = accountLookupValue[0].id;
        accountGuid = accountGuid.replace("{", "");
        accountGuid = accountGuid.replace("}", "");

        //name : is single line of text field
        //primarycontactid : is Lookup field
        //preferredcontactmethodcode: is optionset field
        //donotemail : is two option field

        //filter by lookup field
        // var filter = "&$filter=_primarycontactid_value eq 0F7AFC02-891C-E611-80E1-5065F38B0371";

        //filter byOptionset field
        //var filter = "&$filter=preferredcontactmethodcode eq 2";

        //filter TwoOption field
        var filter = "&$filter=donotemail eq false";
        var orderBy = "&$orderby=name asc";
        var expand = "&$expand=incident_customer_accounts($select=title)";

        //var query = "accounts?$select=name,_primarycontactid_value,preferredcontactmethodcode,donotemail" + filter + orderBy + expand ;

        var query = "accounts(" + accountGuid + ")?$select=name,_primarycontactid_value,preferredcontactmethodcode,donotemail" + expand;
        var webapiPath = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" + query;

        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();

        if (service.readyState == 4 /* complete */) {

            if (service.status == 201 || service.status == 200) {

                var result = eval('(' + service.responseText + ')');
                var name = result.name; // extract single line of text field
                var lookupGuid = result._primarycontactid_value; // extract Look up guid
                var lookupEntityName = result['_primarycontactid_value@Microsoft.Dynamics.CRM.lookuplogicalname']; //extract look up logical name
                var lookupName = result['_primarycontactid_value@OData.Community.Display.V1.FormattedValue']; // extract lookup text
                var booleanFieldValue = result.donotemail; // boolean field
                var booleanFieldText = result['donotemail@OData.Community.Display.V1.FormattedValue']; // boolean field text
                var optionsetValue = result.preferredcontactmethodcode; // extract optionSetValue
                var optionsetText = result['preferredcontactmethodcode@OData.Community.Display.V1.FormattedValue'];//extract optionset text
                var releatedEntityCaseTitle = result.incident_customer_accounts[0].title;
            }
        }
    }
}  

Thursday, 18 February 2016

Query Metadata of Global OptionSet in Microsoft Dynamics CRM 2016 using Web API


To retrieve meta data of global optionSet in Web API, first you will need to retrieve  meta data id of option Set.
So i create two functions , 

RetrieveGlobalOptionSetMetaDataId("OptionSetSchemaName") function 

will retrieve meta data id of optionSet by passing schema name of option , then pass meta data id to


RetrieveGlobalOptionSetOptionsMetaData(optionSetMetaDataId) 

it will retrieve meta data of optionSet.

I am binding options of global optionSet to Select element in Html Page , 




var globalOptionSetMetaDataId = RetrieveGlobalOptionSetMetaDataId("OptionSetSchemaName");

RetrieveGlobalOptionSetOptionsMetaData(globalOptionSetMetaDataId );


function RetrieveGlobalOptionSetMetaDataId(OptionSetSchemaName) {

    var globalOptionSetMetaDataId = null;
    var context = parent.Xrm.Page.context;
    var webapiQuery = context.getClientUrl() + "/api/data/v8.0/GlobalOptionSetDefinitions?$select=Name";
    var service = new XMLHttpRequest();
    service.open("GET", webapiQuery, 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.send();
    if (service.readyState == 4 /* complete */) {
        if (service.status == 201 || service.status == 200) {
            var RetrieveService = eval('(' + service.responseText + ')');
            if (RetrieveService.value.length > 0) {
                for (var i = 0; i < RetrieveService.value.length; i++) {
                    if (RetrieveService.value[i].Name == OptionSetSchemaName) {
                        globalOptionSetMetaDataId = RetrieveService.value[i].MetadataId;
                        break;
                    }
                }
            }
        }
    }
    return globalOptionSetMetaDataId ;
}


function RetrieveGlobalOptionSetOptionsMetaData(optionSetMetaDataId) {

    var context = parent.Xrm.Page.context;
    var webapiQuery = context.getClientUrl() + "/api/data/v8.0/GlobalOptionSetDefinitions(" + optionSetMetaDataId + ")";
    var service = new XMLHttpRequest();
    service.open("GET", webapiQuery, 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.send();
    if (service.readyState == 4 /* complete */) {
        if (service.status == 201 || service.status == 200) {
            var RetrieveService = eval('(' + service.responseText + ')');
            if (RetrieveService.Options.length > 0) {
                var options = "";
                for (var i = 0; i < RetrieveService.Options.length; i++) {
                    var optionLabel = RetrieveService.Options[i].Label.UserLocalizedLabel.Label;
                    var optionValue = RetrieveService.Options[i].Value;
                    options += "<option value='" + optionValue + "'>" + optionLabel + "</option>";
                }
                $("#dropdownReason").html(options);
            }
        }
    }
}

Thursday, 14 January 2016

Encode Xml Special Character (<,>,',",&) in javaScript and C#

These special character (<,>,',",&) will be encode first when making xml because on these special character the xml will broke.
The below function is used when string containing the above special character,

function specialXmlCharacterEncode(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&apos;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}


In C# this line of code is used when string containing  special character and you make xml query and use string in xml query like in fetchXml query.

 string  str =  SecurityElement.Escape(str);

Monday, 11 January 2016

Difference between FetchXML and QueryExpression

To Query MS CRM DB there are the two distinct ways.
  • Using QueryExpression
  • Using FetchXML
Limitation of the QueryExpression is , If you are Querying CRM DB using QueryExpression you cannot able to set Related Entity columns as filter criteria or 
to provide a column of a linked entity to be returned as the query result.
So you are not able to execute a query similar to the following
Select Opportunity.name, Opportunity.estimatedvalue, Account.address1_city from FilteredOpportunity Opportunity
Inner join
FilteredAccount Account on Opportunity.customerid = Account.accountis
Where account.address1_country = “US”
Also you cannot use aggregate functions in query expression.
In Fetch Xml Query you can retrieve the columns of related entity and you can set the related entity columns  as filter criteria and you can use the aggregate functions in Fetch Xml query.
Query Expression can only be used in server side language i.e C#.
But Fetch Xml query can only be used in SSRS , JavaScript(Webapi),C#.
But in performance  Query Expression is better than Fetch Xml query. 



Sunday, 10 January 2016

Change Record Status in CRM 2016 through Webapi in javascript

In the below code i am deactivating account record to Inactive


function decativateRecordThroughWebapi() {

    var entityId = Xrm.Page.data.entity.getId();
    var clientURL = Xrm.Page.context.getClientUrl();
    entityId = entityId.replace("{","");
    entityId = entityId.replace("}", "");

    var req = new XMLHttpRequest();
    var odataQuery = encodeURI(clientURL + "/api/data/v8.0/accounts(" + entityId + ")");
    req.open("PATCH", odataQuery, false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    //Parameters
    var account = {};
    account["statecode"] = 1; // State code value
    account["statuscode"] = 2; //  status reason Value

    req.send(JSON.stringify(account));

    if (req.readyState == 4) {
        if (req.status == 204) {

            alert("Success");
        } else {
            var error = JSON.parse(req.response).error;
            alert(error.message);
        }

    }

}

Thursday, 7 January 2016

Debugging in Dynamics CRM 2015 and 2016 Plugin

Use tracing in Dynamics CRM plugin for debugging purposes.
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Plugin Message" + context.MessageName.ToUpper());


After the Spring Update 1 of CRM 2015 you can write and check these trace logs in Plugin Tracing Logs.
For using this feature you have to enable Plugin Tracing Logs in your organization.
To enable Plugin tracing logs follow the following steps.
  • Select Settings and under the System menu, Select Administration.
  • On Administration page click on System Settings and navigate to Customization tab.
  • Change “Enable logging to plug-in tracing log” to All or Exception.


To open Plugin Tracing Logs select Settings and under the Customization menu, select Plug-In Trace Logs.


Tuesday, 5 January 2016

Pass entity reference attributes and other attribute to global action by calling action through Webapi in JavaScript Dynamics CRM 2016

In the following code actionName  is the name of action.
primarycontact and parentaccount is the entityreference attribute in action.
name and email is the string attribute in action


var oDataEndpointUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/actionName";
        var service = new XMLHttpRequest();
        service.open("POST", oDataEndpointUrl, 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");
        var parameter = { "name": "nizam",
                          "email": "syed.nizam69@gmail.com",
                          "primarycontact": { "contactid": "AEAD37F8-F39D-E511-80D3-2C59E5420648", "@odata.type": "Microsoft.Dynamics.CRM.contact" },
                          "parentaccount": { "accountid": "54AD37F8-F39D-E511-80D3-2C59E5420648", "@odata.type": "Microsoft.Dynamics.CRM.account" }
                         }

        service.send(JSON.stringify(parameter));
        if (service.readyState == 4 /* complete */) {
            if (service.status == 201 || service.status == 200) {
            }
        }

Change State of Record in Dynamics CRM in JavaScript by Soap Call

function changeStateOfRecord() {
    debugger;
  var entityName = Xrm.Page.data.entity.getEntityName();
  var entityId = Xrm.Page.data.entity.getId();
  SetStateRequest(entityName,entityId,2,4);
}

SetStateRequest = function (_entityname, entityid, _state, _status)
{
    var requestMain = ""
    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>EntityMoniker</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + entityid + "</a:Id>";
    requestMain += "              <a:LogicalName>" + _entityname + "</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>State</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _state + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Status</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _status + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>SetState</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";
    var req = new XMLHttpRequest();
    req.open("POST", getClientUrl() + "XRMServices/2011/Organization.svc/web", false)

    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    var successCallback = null;
    var errorCallback = null;
    req.onreadystatechange = function () { SetStateResponse(req, successCallback, errorCallback); };
    req.send(requestMain);
}

SetStateResponse = function (req, successCallback, errorCallback) {
    debugger;
    if (req.readyState == 4) {
        if (req.status == 200) {
            if (successCallback != null)
            { successCallback(); }
        }
        else {
            errorCallback
(_getError(req.responseXML));
        }
    }
}

//Also need below two supportive methods.

_getError = function (faultXml) {
    debugger;
    var errorMessage = "Unknown Error (Unable to parse the fault)";
    if (typeof faultXml == "object") {
        try {
            var bodyNode = faultXml.firstChild.firstChild;
            //Retrieve the fault node
            for (var i = 0; i < bodyNode.childNodes.length; i++) {
                var node = bodyNode.childNodes[i];
                if ("s:Fault" == node.nodeName) {
                    for (var j = 0; j < node.childNodes.length; j++) {
                        var faultStringNode = node.childNodes[j];
                        if ("faultstring" == faultStringNode.nodeName) {
                            errorMessage = faultStringNode.text;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        catch (e) { };
    }
    return new Error(errorMessage);
}

function getClientUrl() {

    var strUrl = Xrm.Page.context.getClientUrl();

    if (strUrl.substr(strUrl.length - 1) != "/") {
        strUrl += "/";
    }

    return strUrl;
}

Add mapping for custom attribute of Opportunity Product to Quote Product, Quote product to Order Product and Order product to Invoice product in Dynamics CRM

Friday, 1 January 2016

Change Business Process flow in JavaScript in CRM 2016 by Business Process Flow Name

 


In  the following function I am getting Business Process name from an Option Set and passing to Webapi query by getting Business Process flow Id and then Changing  Business flow  on Opportunity Entity form.


function ChangeBusinessProcessFlow() {
        try {

            var opportunityType = Xrm.Page.getAttribute("po_opportunitytype");
            if (opportunityType != null) {

                var opportunityTypeName = opportunityType.getSelectedOption().text;

                if (opportunityTypeName != null || opportunityTypeName != '') {

                    var odataQuery = "workflows?$select=workflowid,name &$filter=name eq '" + opportunityTypeName + "'";
                    var oDataEndpointUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/" + odataQuery;
                    var service = new XMLHttpRequest();
                    service.open("GET", oDataEndpointUrl, false);
                    service.setRequestHeader("Accept", "application/json");
                    service.setRequestHeader("OData-MaxVersion", "4.0");
                    service.setRequestHeader("OData-Version", "4.0");

                    service.send();

                    if (service.readyState == 4 /* complete */) {
                        if (service.status == 201 || service.status == 200) {
                            var data = JSON.parse(service.response);
                            if (data.value.length > 0) {
                                if (data.value[0].workflowid != null) {

                                    Xrm.Page.data.save().then(function () {

                                        Xrm.Page.data.process.setActiveProcess(data.value[0].workflowid, afterChangeBpf);

}
            }
        } catch (ex) {
            alert("error occured in ChangeBusinessProcessFlowOnOpportunityType() function");
        }
    
}
function afterChangeBpf() {
    
}

  

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...