1. 程式人生 > WINDOWS開發 >Dynamics CRM 2015/2016新特性之二十三:使用Web API執行函式

Dynamics CRM 2015/2016新特性之二十三:使用Web API執行函式

關注本人微信和易信公眾號: 微軟動態CRM專家羅勇 ,回覆206或者20160315可方便獲取本文,同時可以在第一間得到我釋出的最新的博文資訊,follow me! 函式分為函式(function)和查詢函式(query function),是不是有點兒繞口?函式的列表請參考SDK的 Web API Function Reference 章節,每個函式都有一個訊息和它對應,函式不會改變資料,一般是查詢資料,返回一個複雜型別或者集合。查詢函式的列表請參考SDK的Web API Query Function Reference 章節,每個函式對應的是一個FetchXML的操作符,用來判斷是否符合條件。 下面舉例子來說明下,呼叫 RetrieveAllChildUsersSystemUser 這個函式吧,它說起來是繫結函式(bound function),所有繫結函式都有一個屬性值是IsBound="true" 。這個必須點贊,現在執行訊息方便多了,以前版本執行訊息很麻煩,可以參考我的部落格:
通過JavaScript呼叫SOAP終結點執行實體訊息
下面這個是函式的相關元資料資訊: 技術分享圖片

示例呼叫程式碼如下:
var clientURL = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest()
req.open("GET",encodeURI(clientURL + "/api/data/v8.0/systemusers(4C6A6247-43A9-E511-80CF-000D3A806074)/Microsoft.Dynamics.CRM.RetrieveAllChildUsersSystemUser()?$select=fullname"),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 responseJSON = JSON.parse(this.responseText); var popstr = ""; if (responseJSON.value != null && responseJSON.value.length >= 1) { for (var i = 0; i < responseJSON.value.length; i++) { popstr += responseJSON.value[i].fullname + ";"; } } Xrm.Utility.alertDialog("這個人下屬(含直接下屬和非直接下屬)包括:" + popstr); } else { var error = JSON.parse(this.response).error; Xrm.Utility.alertDialog("呼叫函數出錯." + error.message); } } }; req.send();

非繫結函式(unbound function)就是不是和實體繫結的函式,所有的查詢函式都是非繫結函式,還有部分函式,他們沒有IsBound屬性。
下圖是非繫結函式 WhoAmI 定義的元資料。 技術分享圖片

下面是呼叫非繫結函式的示例程式碼:
var clientURL = Xrm.Page.context.getClientUrl();
var req = new XMLHttpRequest()
req.open("GET",encodeURI(clientURL + "/api/data/v8.0/WhoAmI()"),"4.0");
req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 200) {
            var responseJSON = JSON.parse(this.responseText);
            Xrm.Utility.alertDialog("當前使用者的ID是:" + responseJSON.UserId + ";所屬業務部門ID是" + responseJSON.BusinessUnitId);
        }
        else {
            var error = JSON.parse(this.response).error;
            Xrm.Utility.alertDialog("呼叫函數出錯." + error.message);
        }
    }
};
req.send();
從Dynamics 365 V9版本開始提供了新的客戶端API來方便程式設計,請參考Xrm.WebApi.online.execute (Client API reference),還可以參考我的博文 Dynamics 365 V9版本新的客戶端API Xrm.WebApi.online.execute 使用例項 。 更多資訊請參考官方文件:Use Web API functions