Execute Action using Web API in Dynamics 365


Sharing simple scenario to call custom action from JavaScript (from ribbon button).
First of all, create an Action for Sales Order entity and a step to change status to Active(New) as shown below.
Action

Call below function form ribbon button to change the status of Sales Order to New.

function ChangeAgreementStatus() {
var Id = Xrm.Page.data.entity.getId().replace(‘{‘, ”).replace(‘}’, ”);
var clientURL = Xrm.Page.context.getClientUrl();

// pass the id as inpurt parameter
var data = {
“agreementid”: Id
};

var req = new XMLHttpRequest();

// specify name of the entity, record id and name of the action in the Wen API Url
req.open(“POST”, clientURL + “/api/data/v8.2/salesorders(” + Id + “)/Microsoft.Dynamics.CRM.new_ActivateAgreement”, 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 == 200) {
var data = JSON.parse(this.response);
alert(data);
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};

// send the request with the data for the input parameter
req.send(window.JSON.stringify(data));

//Refresh form
Xrm.Page.data.refresh();
}

For details, please refer below URL.

https://community.dynamics.com/crm/b/nishantranaweblog/archive/2017/05/27/sample-code-to-call-action-using-web-api-in-crm

hope this help you

Debug WCF Restful service (POST/GET) – Part 2


There are many way to debug WCF/Cloud service hosted in Azure and you can refer the below tutorial but I prefer to debug the service old and easy way by deploying the service in local IIS then publish to Azure.

https://docs.microsoft.com/en-us/azure/vs-azure-tools-debug-cloud-services-virtual-machines

https://docs.microsoft.com/en-us/azure/vs-azure-tools-debugging-cloud-services-overview

In Part 1, I explain how to create and deploy WCF Restful service in Azure.

https://arvindcsit.blog/crm-and-azure-integration/

I will use the same existing code and will add another POST method to explain debugging.

I am going to create one POST method which takes User Name and Password as request body and return predefined token.

So I added below code in Part 1 source code.

Contract: ICRMService.cs

Under ServiceContract

[OperationContract]
[WebInvoke(Method = “POST”,
UriTemplate = “/getauth”,
ResponseFormat = WebMessageFormat.Json)]
CRMTokenResponse GetCRMToken(CRMTokenRequest tokenReqeust);

DataContract
[DataContract]
public class CRMTokenResponse
{
public CRMTokenResponse()
{
this.Token = “”;
this.Error = “”;
}
[DataMember(IsRequired = false)]
public string Token { get; set; }
[DataMember(IsRequired = false)]
public string Error { get; set; }
}
[DataContract]
public class CRMTokenRequest
{
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
}
CRMService.svc.cs
public CRMTokenResponse GetCRMToken(CRMTokenRequest tokenRequest)
{
CRMTokenResponse resp = new CRMTokenResponse();
if (tokenRequest != null)
{
string userName = WebConfigurationManager.AppSettings[“CRM.Username”];
string password = WebConfigurationManager.AppSettings[“CRM.Password”];
string tokenId = WebConfigurationManager.AppSettings[“CRM.Token”];
if (tokenRequest.Username == null || tokenRequest.Password == null)
{
resp.Error = “Enter UserName and Password”;
return resp;
}
if (tokenRequest.Username.Equals(userName) && tokenRequest.Password.Equals(password))
{
resp.Token = tokenId;
}
else
{
resp.Error = “Invalid Username & Password”;
}
}
else
{
resp.Error = “Request is Null”;
}
return resp;
} 

Web.config

Add these three lines under <appSettings></appSettings> tag.
<add key=”CRM.Username” value=”Arvind” />
<add key=”CRM.Password” value=”Singh” />
<add key=”CRM.Token” value=”8178746c24b9f5544d259f2a38d7c1a785bc70a2″ />

We are done with code changes, make sure you build the project in Debug mode and deploy in local IIS.

Browse the service and make sure the service is running without any error. I will use PostMan to hit and debug the service.

Set the breakpoint and attached to W3WP process. Select the Content Type and Request Body as below.

Then Click “Send” and cursor will stop at breakpoint as shown below.

you can see the token value while debugging as below

Finally, you get output in output window of PostMan as below.

Similarly, you can debug it for GET method. Once your service is working fine, you can publish your service to Azure using steps mentioned in PART 1 (https://arvindcsit.blog/crm-and-azure-integration/)

Hope this helps you.

 

 

 

 

Check open activity related case using oData query


Sharing below code which returns some value using oData query. This function will check if there is any open activity related to Incident entity.

function CheckOpenActivity() {

var Id = parent.Xrm.Page.data.entity.getId();

var IncidentId = Id.substring(1, 37);

//Retrieve dynamically the organization’s server url

var serverUrl = document.location.protocol + “//” + document.location.host + “/” + Xrm.Page.context.getOrgUniqueName();

var ODATA_ENDPOINT = “/xrmservices/2011/OrganizationData.svc”;

var ODATA_EntityCollection = “/IncidentSet?$select=IncidentId,Incident_ActivityPointers/ActivityId,Incident_ActivityPointers/StateCode&$expand=Incident_ActivityPointers”;

var ODATA_Filter1 = “&$filter=IncidentId eq guid'” + IncidentId + “‘”;

var oDataRequestUrl = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Filter1;

var result = syncODataCall(oDataRequestUrl);

var isOpenActivity = ProcessReturnedEntities(result);

if (isOpenActivity)
alert(‘The Case has open Activity’);
else
alert(‘The Case has not any open Activity’);

}

// function to make synchronous oData call

function syncODataCall(odataSelect) {

var request = new XMLHttpRequest();

request.open(“GET”, odataSelect, false);

request.setRequestHeader(“Accept”, “application/json”);

request.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

request.send();

var objJQuery = jQuery.parseJSON(request.responseText);

return objJQuery.d

}

function ProcessReturnedEntities(d) {

var hasRelated = false;

if (d.results[0] != null) {

var activities = d.results[0].Incident_ActivityPointers;

if (activities != null) {

if (activities.results.length > 0) {

$.each(activities.results, function (index) {

if (activities.results[index].StateCode.Value == ‘0’) {

hasRelated = true;
return hasRelated;

}
});

} else {
hasRelated = false;
return hasRelated;
}

} else {
hasRelated = false;
return hasRelated;
}
}
return hasRelated;
}

 

Hope this help you.

Get Internet Explorer (IE) Version


Hi,
We faced some CRM Issue based IE Version i.e some of the functionality was working fine in IE 8.0 and IE 9.0 but not working on IE 10.0 or later.. I had written the below function to detect the IE version and chage the logic accordingly.

function MSIEVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf(“MSIE “)
var rv = ua.indexOf(“rv:”);
var compatible = ua.indexOf(“compatible”);
var ieVersion;

// If IE Version <= 10 and compatiable mode return version number
if ((msie > 0) && (rv == -1) && (compatible > 0))
{
ieVersion = parseInt(ua.substring(msie + 4, ua.indexOf(“.”, msie)));
if (ieVersion == 10)
{
ieVersion = ieVersion + 1;
}
return ieVersion;
}
// If IE Version <= 10 and not in compatiable mode return version number
if ((msie > 0) && (rv == -1) && (compatible == -1))
{
ieVersion = parseInt(ua.substring(msie + 4, ua.indexOf(“.”, msie)));

return ieVersion;
}
// If IE Version > 10, return version number
if ((msie == -1) && (rv > 0))
{

// If IE Version > 10
ieVersion = parseInt(ua.substring(rv + 3, ua.indexOf(“.”, rv + 5)));         r
eturn ieVersion;
}
}

Hope it helps..

Make Enable / Editable field on Assign of Entity Record


To Enable the field on Assign of any entity record, call the below function. On Assign of record, only save event triggered in CRM 2013, so we have to call the function on OnSave. Check the Save Mode for Assign( Save Mode of Assign = 47) and write your logic there..

function EnableFieldOnAssign(prmContext)
{
if (prmContext.getEventArgs().getSaveMode() == 47)
{
Xrm.Page.getControl(“mst_casestatus”).setDisabled(false);

}

}

Hope this helps..

Cleared Microsoft Dynamics CRM 2013 Customization and Configuration ( MB2 – 703 ) Exam today


Cleared Microsoft Dynamics CRM 2013 Customization and Configuration ( MB2 – 703 ) Exam today which contains mainly below topics.

  • Business Process Flow
  • Dashboard and Charts
  • Access Teams
  • Quick Create Forms
  • Views
  • CRM for Tablets

Set Custom View as Default View for Lookup Control


Let’s say we have to set Custom View as Default View of a particular Lookup. Below are the steps to set Custom View as default View.

1. Create a Custom View as per your requirement and Save it.(In my case, Created a custom view of Account which will be shown on contact entity for Primary Customer Field)
CustomView

2. Get View Id from Browser. 3. Download Fetch XML for your custom view as shown below. In my case, below is the FetchXML query..

<fetch version=”1.0″ output-format=”xml-platform” mapping=”logical” distinct=”false”>   <entity name=”account”>     <attribute name=”name” />     <attribute name=”primarycontactid” />     <attribute name=”telephone1″ />     <attribute name=”accountid” />     <attribute name=”accountratingcode” />     <order attribute=”name” descending=”false” />     <filter type=”and”>       <condition attribute=”telephone1″ operator=”eq” value=”555-0135″ />     </filter>   </entity> </fetch>

4. Format the FetchXML  as string variable as below.

    var fetchXml = “<fetch version=’1.0′ “ +
 “output-format=’xml-platform’ “ +
 ” mapping=’logical’ “ +
 ” distinct=’false’>” +
  “<entity name=’account’>” +
    “<attribute name=’name’ />” +
    “<attribute name=’primarycontactid’ />” +
    “<attribute name=’telephone1′ />” +
    “<attribute name=’accountid’ />” +
    “<attribute name=’accountratingcode’ />” +
    “<order attribute=’name’ descending=’false’ />” +
    “<filter type=’and’>” +
     ” <condition attribute=’telephone1′ operator=’eq’ value=’555-0135′ />” +
    “</filter>” +
  “</entity>” +
“</fetch>”;
5. Create layoutXml to set Grid properties to display the view as below.
var layoutXml = “<grid name=’resultset’ “ +
“object=’1′ “ +
“jump=’name’ “ +
“select=’1′ “ +
“icon=’1′ “ +
“preview=’1′>” +
“<row name=’result’ “ +
“id=’accountid’>” +
“<cell name=’name’ “ +
“width=’300′ />” +
“<cell name=’primarycontactid’ “ +
“width=’150′ />” +
“<cell name=’telephone1′ “ +
“width=’100′ />” +
“<cell name=’accountratingcode’ “ +
“width=’100′ />” +
“disableSorting=’1′ />” +
“</row>” +
“</grid>”;

6. Call the addCustomView() method of Lookup to set custom view as Default View.

Sets the viewId, viewDisplayName, fetchXml, and layoutXml variables to pass as arguments so that a custom view is added as the default view to the control for the Parent Customer lookup field.

7. Add above steps in a custom function and call it on OnLoad or OnChange as per requirement
function setDefaultCustomView() {
    var viewId = “{00000000-0000-0000-00AA-000010001001}”;
    var viewDisplayName = “Custom Account View”;
    var fetchXml = “<fetch version=’1.0′ ” +
“output-format=’xml-platform’ ” +
” mapping=’logical’ ” +
” distinct=’false’>” +
“<entity name=’account’>” +
“<attribute name=’name’ />” +
“<attribute name=’primarycontactid’ />” +
“<attribute name=’telephone1′ />” +
“<attribute name=’accountid’ />” +
“<attribute name=’accountratingcode’ />” +
“<order attribute=’name’ descending=’false’ />” +
“<filter type=’and’>” +
” <condition attribute=’telephone1′ operator=’eq’ value=’555-0135′ />” +
“</filter>” +
“</entity>” +
“</fetch>”;

    var layoutXml = “<grid name=’resultset’ ” +
“object=’1′ ” +
“jump=’name’ ” +
“select=’1′ ” +
“icon=’1′ ” +
“preview=’1′>” +
“<row name=’result’ ” +
“id=’accountid’>” +
“<cell name=’name’ ” +
“width=’300′ />” +
“<cell name=’primarycontactid’ ” +
“width=’150′ />” +
“<cell name=’telephone1′ ” +
“width=’100′ />” +
“<cell name=’accountratingcode’ ” +
“width=’100′ />” +
“disableSorting=’1′ />” +
“</row>” +
“</grid>”;

Xrm.Page.getControl(“parentcustomerid”).addCustomView(viewId, “account”, viewDisplayName, fetchXml, layoutXml, true); 

}

Note: Pls change the double quote(“) manually before testing the code.

%d bloggers like this: