Showing posts with label Dynamics CRM 2016. Show all posts
Showing posts with label Dynamics CRM 2016. Show all posts

Dynamics CRM 2016 Web API (OData V4.0)

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Microsoft introduces Web API (OData v4) with the release of Dynamics CRM 2016 to perform CRUD operations and also some other special operations. Following are some posts for CRUD operation...


Retrieve Record using Web API

Retrieve Multiple using Web API

Retrieve Multiple through fetch XML using Web API

Create Record using Web API

Update Record using Web API

Delete Record using Web API

Associate Record using Web API

Disassociate Record using Web API

Calling entity based Action using Web API

Calling Global Action using Web API

Associate Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to Associate a record using Web API in Dynamics CRM.
/*
currentEntityPlurarName: currentEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
currentEntityId: guid of current entity record
otherEntityPlurarName: otherEntityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
otherEntityId: guid of other entity record       
*/
function associateRequest(currentEntityPlurarName, currentEntityId, relationShipName, otherEntityPlurarName, otherEntityId) {
    var serverURL = Xrm.Page.context.getClientUrl();
    var associate = {}
    associate["@odata.id"] = serverURL + "/api/data/v8.2/" + otherEntityPlurarName + "(" + otherEntityId + ")"
    
    var req = new XMLHttpRequest();
    req.open("POST", serverURL + "/api/data/v8.2/" + currentEntityPlurarName + "(" + currentEntityId + ")/" + relationShipName + "/$ref", true);
    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.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 204) {
                //alert('Record Associated');
            } else {
                var error = JSON.parse(this.response).error;
                Xrm.Utility.alertDialog(error.message);
            }
        }
    };
    req.send(JSON.stringify(associate));
}
You can call the associate record method as:
 var currentEntityName = "accounts";
var currentEntityId = removeCurlyBraces(Xrm.Page.data.entity.getId())
var relationShipName = "new_account_contact";
var otherEntityName = "contacts";
var otherEntityId = removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id);
associateRequest(currentEntityName, currentEntityId, relationShipName, otherEntityName, otherEntityId);

Delete Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to delete a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
id: guid of record going to delete       
*/
function deleteRecord(entityPlurarName, id) {
    id = id.replace('{', '').replace('}', '');
    var IsDeleted = false;
    var serverURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest();
    req.open("DELETE", serverURL + "/api/data/v8.2/" + entityPlurarName + "(" + id + ")", 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();
    if (req.readyState == 4 /* complete */) {
        if (req.status == 204) {
            IsDeleted = true;
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return IsDeleted;
}
You can call the delete record method as:
var id=Xrm.Page.data.entity.getId();
alert(deleteRecord("accounts", id));

Retrieve Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to retrieve a record using Web API in Dynamics CRM.
/*
entityName: entityName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
entityId: Guid of entity record
return:-Entity record       
*/
function retrieveEntityById(entityName, entityId) {
    entityId = entityId.replace('{', '').replace('}', '');
    var data = null;
    var req = new XMLHttpRequest();
    req.open('GET', Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityName + "(" + entityId + ")", false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Prefer", "odata.include-annotations=*");
    req.send();
    if (req.readyState == 4 /* complete */) {
        if (req.status == 200) {
            data = JSON.parse(req.response);
        }
        else {
            var error = JSON.parse(req.response).error;
            console.log(error.message);
        }
    }
    return data;
}
You can call the retrieve record method as:
var accountId=Xrm.Page.data.entity.getId();
var account=retrieveEntityById("accounts",accountId);
if(account!=null)
var accountName=account.name;
var accountNumber=account.accountnumber;

Update Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to update a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
id: guid of record going to update
entityObject: entityObject is an object that of entity contians fields and values that needed to be create.
e.g
  var entityObject = {};
      entityObject["originatingleadid@odata.bind"] = "/leads(" + guid + ")";  // lookup    
      contact["firstname"] = string value;  // Single line of text 
      contact["po_preferredlanguage"] = string value; //Option set
      contact["donotemail"] = true/false //two Option
*/
function updateRecord(entityPlurarName, id, entityObject) {
    var IsUpdated = false;
    var req = new XMLHttpRequest();
    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityPlurarName + "(" + id + ")", 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.send(JSON.stringify(entityObject));
    if (req.readyState === 4) {
        if (req.status === 204) {
            IsUpdated = true;
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return IsUpdated;
}
You can call the update record method as:
var account = {};
account["name"] = "Test Account name 2";  // Single line of text 
account["paymenttermscode"] = "4";//Text(Net 30) //Option set
account["creditonhold"] = false; //two Option 
alert(updateRecord("accounts", removeCurlyBraces(Xrm.Page.data.entity.getId()), account));

Create Record using Web API

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Following is detail sample code to create a record using Web API in Dynamics CRM.
/*
entityPlurarName: entityPlurarName is the plural entity logical name of entity e.g for account it is accounts. for opportunity it is opportunities
entityObject: entityObject is an object that of entity contians fields and values that needed to be create.
e.g
  var entityObject = {};
      entityObject["originatingleadid@odata.bind"] = "/leads(" + guid + ")";  // lookup   
      contact["firstname"] = string value;  // Single line of text 
      contact["po_preferredlanguage"] = string value; //Option set
      contact["donotemail"] = true/false //two Option  
*/
function createRecord(entityPlurarName, entityObject) {
    var id = null;
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityPlurarName, 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.send(JSON.stringify(entityObject));
    if (req.readyState === 4) {
        if (req.status === 204) {
            var uri = req.getResponseHeader("OData-EntityId");
            var regExp = /\(([^)]+)\)/;
            var matches = regExp.exec(uri);
            id = matches[1];
        }
        else {
            var error = JSON.parse(req.response).error;
            Xrm.Utility.alertDialog(error.message);
        }
    }
    return id;
}
You can call the create record method as:
var account = {};
account["primarycontactid@odata.bind"] = "/contacts(" + removeCurlyBraces(Xrm.Page.getAttribute("primarycontactid").getValue()[0].id) + ")";  // lookup 
account["name"] = "Test Account name";  // Single line of text 
account["paymenttermscode"] = "1";//Text(Net 30) //Option set
account["creditonhold"] = true; //two Option
var accountid=createRecord("accounts", account);

Step by step way to create dynamics CRM trial org

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

I have created this post by just copy paste the email body I have sent to one of my functional client, thinking it will be helpful for others like my functional client was seeking the step by step way to create trail CRM org.

Type “Dynamics CRM free trial” in Google.

Click the highlighted link.












Click "Get started" button to start the sign up process.
Click Next to proceed.

Click “Create my account” button.


Verify by text message OR Call.
In case of Text message, enter the code you have received to your phone.


Wait

Click Setup


Click Complete Setup




















Setting Up

Finally will redirect to the dynamics 365.

So finally following is the information for login to CRM
Company Name: Dynamics365Demo11
URL: https://[CompanyName].crm.dynamics.com
User Name: siddique.mahsud@[CompanyName].onmicrosoft.com
Password: *******

Get Object Type Code for entities in Dynamics CRM

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

In Microsoft Dynamics We Often need objectTypeCodes while doing data migration from CRM On-Premise to online.

If you have On-Premise CRM then you can query SQL database to get object type codes for any entity. Below query will retrieve entity logical name and objectTypeCode list for all OOB and Custom entities.

select Name, ObjectTypeCode from EntityView order by ObjectTypeCode


If you need Just for custom entities then just filter by object type code greator then 9999.

select Name, ObjectTypeCode from EntityView WHERE ObjectTypeCode>9999 order by ObjectTypeCode
                        

For CRM online you can retrieve objectTypeCodes by a Meta Data Call using Web API.

[org Url]/api/data/v8.2/EntityDefinitions?$select=LogicalName,ObjectTypeCode

Filter for Custom Entities:

[org Url]//api/data/v8.2/EntityDefinitions?$select=LogicalName,ObjectTypeCode&$filter=ObjectTypeCode gt 9999

Creating, Registering and Calling Custom Actions

Welcome to my old Blogspot blog! You can read this post on our new website: Read this post on our new website 

Actions are actually Custom messages defined for an entity. Following action is created for lead entity having input and out parameters.
































Custom Action Plugin C# code, using input parameter and output parameters.

public class CustomQualify : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
       IPluginExecutionContext context = (IPluginExecutionContext
                     serviceProvider.GetService(typeof(IPluginExecutionContext)); 
       IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)
                     serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
       IOrganizationService service=    
                     serviceFactory.CreateOrganizationService(context.UserId);
        try
        {
            string leadId = string.Empty;
            bool CreateContact = false;
            bool CreateAccount = false;
            bool CreateOpportunity = false; 

            if (context.PrimaryEntityId != null && context.PrimaryEntityId != Guid.Empty)    
                leadId = context.PrimaryEntityId.ToString();
                

            if (context.InputParameters.Contains("CreateContact") && 
                                      context.InputParameters["CreateContact"] != null)      
                CreateContact = (bool)context.InputParameters["CreateContact"];
             

            if (context.InputParameters.Contains("CreateAccount") && 
                                        context.InputParameters["CreateAccount"] != null)   
                CreateAccount = (bool)context.InputParameters["CreateAccount"];
                

            if (context.InputParameters.Contains("CreateOpportunity") && 
                                    context.InputParameters["CreateOpportunity"] != null)   
                CreateOpportunity = (bool)context.InputParameters["CreateOpportunity"];
               

            if (leadId.Equals(string.Empty)) return;

            QualifyLeadRequest req = new QualifyLeadRequest();
            req.LeadId = new EntityReference("lead"new Guid(leadId));
            req.Status = new OptionSetValue(3);
            req.CreateContact = CreateContact;
            req.CreateAccount = CreateAccount;
            req.CreateOpportunity = CreateOpportunity;
            QualifyLeadResponse res = (QualifyLeadResponse)service.Execute(req); 

            context.OutputParameters["success"] = "Done Successfully";
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}  

Register the action plugin, and add step by selecting messge as "msd_CustomQualify" and "lead" as Primary entity.







































Calling an action associated with specific entity from web API 

var leadId = Xrm.Page.data.entity.getId().substring(1, 37);
var ServiceURL = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/";
var ActionName = "msd_CustomQualify";
var parameter = {
    CreateContact: true,
    CreateAccount: false,
    CreateOpportunity: false
};

var request = new XMLHttpRequest();
request.open("POST", ServiceURL + "/leads(" + leadId + ")/Microsoft.Dynamics.CRM." + ActionName, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.setRequestHeader("OData-MaxVersion", "4.0");
request.setRequestHeader("OData-Version", "4.0");

request.onreadystatechange = function () {
    if (this.readyState == 4) {
        request.onreadystatechange = null;
        if (this.status == 200 || this.status == 204) {
            var data = JSON.parse(this.responseText);
            if (data != null) {
                alert(data.success);
                Xrm.Page.data.refresh();
            }
        } else {
            var error = JSON.parse(this.response).error;
            if (error != null)
                alert(error.message);
        }
    }
};

request.send(JSON.stringify(parameter));


Also we can created global actions that are not dependent on specific entity, for making an action global we will select entity name as None (global) as shown below.



































Calling Global action using web API

var leadId = Xrm.Page.data.entity.getId().substring(1, 37);
var ServiceURL = Xrm.Page.context.getClientUrl() + "/api/data/v8.0/";
var ActionName = "msd_CustomQualify";
var parameter = {
    leadId: leadId,
    CreateContact: true,
    CreateAccount: false,
    CreateOpportunity: false
};

var request = new XMLHttpRequest();
request.open("POST", ServiceURL + ActionName, false);
request.setRequestHeader("Accept""application/json");
request.setRequestHeader("Content-Type""application/json; charset=utf-8");
request.setRequestHeader("OData-MaxVersion""4.0");
request.setRequestHeader("OData-Version""4.0");

request.onreadystatechange = function () {
    if (this.readyState == 4) {
        request.onreadystatechange = null;
        if (this.status == 200 || this.status == 204) {
            var data = JSON.parse(this.responseText);
            if (data != null) {
                alert(data.success);
                Xrm.Page.data.refresh();
            }
        } else {
            var error = JSON.parse(this.response).error;
            if (error != null)
                alert(error.message);
        }
    }
};
request.send(JSON.stringify(parameter));