Dynamics 365 for Sales: Web API Client编程辅助类

最近博主写了一个Web API Client端的编程辅助类,我们可以用它在客户端层面调用Web API 完成CRUD操作。辅助类的Ajax请求是基于Jquery完成的,也就是说,大家在使用这个类的时候需要引用JQUERY,具体情况如下图所示:


JSHelper

var WEB_API_VERSION = "8.1";
var JQUERY_URL = "/WebResources/new_jquery.1.11.js";

function XrmHelper()
{
     var _clientUrl = Xrm.Page.context.getClientUrl();
     this._webApiUrl = _clientUrl + "/api/data/v" + WEB_API_VERSION + "/";

}


XrmHelper.prototype.Create = function (url, content) {

    var data = null;
    

    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': content != null ? content.length : 0 },
        type: "POST",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        data:content,
        complete: function (context) {
            if (context.status>=200 && context.status<300) {
                try {
                    data = context.getResponseHeader("OData-EntityId");
                } catch (e) { }
            }
        }
    });//ajax
    return data;

};

XrmHelper.prototype.CreateAsync = function (url, content, callbackHandler) {



    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': content != null ? content.length : 0 },
        type: "POST",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        data: content,
        complete: function (context,result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    //data = $.parseJSON(context.responseText).d;
                    callbackHandler(context.getResponseHeader("OData-EntityId"));
                } catch (e) { }
            }
        }
    });//ajax


};

XrmHelper.prototype.Read = function (url) {

    var data = null;

    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8'},
        type: "GET",
        url: url.indexOf("http")==-1? this._webApiUrl + url:url,
        async: false,
        cache: true,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    data = context.responseJSON;
                } catch (e) { }
            }
        }
    });//ajax
    return data;

};

XrmHelper.prototype.ReadAsync = function (url, callbackHandler) {



    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8'},
        type: "GET",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: true,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    //data = $.parseJSON(context.responseText).d;
                    callbackHandler(context.responseJSON);
                } catch (e) { }
            }
        }
    });//ajax


};

XrmHelper.prototype.Update = function (url, content) {

    var data = null;

    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': content != null ? content.length : 0 },
        type: "PATCH",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        data:content,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    data = result;
                } catch (e) { }
            }
        }
    });//ajax
    return data;

};

XrmHelper.prototype.UpdateAsync = function (url, content, callbackHandler) {



    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': content != null ? content.length : 0 },
        type: "PATCH",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        data:content,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    
                    callbackHandler(result);
                } catch (e) { }
            }
        }
    });//ajax


};

XrmHelper.prototype.Delete = function (url) {

    var data = false;

    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8'},
        type: "DELETE",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    data = true;
                } catch (e) { }
            }
        }
    });//ajax
    return data;

};

XrmHelper.prototype.DeleteAsync = function (url, callbackHandler) {


    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8' },
        type: "DELETE",
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    callbackHandler(true);
                }
                catch (e) { }
            }
            else {
                callbackHandler(false);
            }
        }
    });//ajax

};

XrmHelper.prototype.ExecuteAPI = function (method,url, content) {

    var data = null;

    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': content != null ? content.length : 0 },
        type: method,
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        data:content,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                   
                    if (context.responseJSON != null) {
                        data = context.responseJSON;
                    }
                    else{
                        data=result;
                    }

                } catch (e) { }
            }
        }
    });//ajax
    return data;

};

XrmHelper.prototype.ExecuteAPIAsync = function (method,url, content, callbackHandler) {



    $.ajax({
        headers: { Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': content != null ? content.length : 0 },
        type: method,
        url: url.indexOf("http") == -1 ? this._webApiUrl + url : url,
        async: false,
        cache: false,
        data:content,
        complete: function (context, result) {
            if (context.status >= 200 && context.status < 300) {
                try {
                    var data = null;
                    if (context.responseJSON != null) {
                        data = context.responseJSON;
                    }
                    else {
                        data = result;
                    }

                    callbackHandler(data);
                } catch (e) { }
            }
        }
    });//ajax


};



Unit Test 代码

function xrmHelperUT() {
    debugger;
    //alert('onload');
    var xrmHelper = new XrmHelper();



    //test code
    xrmHelper.Create("contacts", { "firstname": "hello", "lastname": "webapi" });


    //create account
    var entityUrl = xrmHelper.Create("accounts", "{'name':'create test account sync'}");
    console.log(entityUrl + "create sync\n");
    
    var entityAsyncUrl = null;
    xrmHelper.CreateAsync("accounts", "{'name':'create test account async'}", function (result) {
        entityAsyncUrl = result;
        console.log(result+ "create async\n")
    });

    //read account
    var createdAcc = xrmHelper.Read(entityUrl);
    console.log(createdAcc.name+" Read \n");

    var createdAccAsync = null;
    xrmHelper.ReadAsync(entityAsyncUrl, function (result) {
       
        console.log(result.name + " Read Async\n");
    });



    //update account
    var uptsyncObj = "{ 'telephone1': '15000303158' }";
 
    xrmHelper.Update(entityUrl, uptsyncObj);
    console.log("update\n");


    var uptAsyncObj = "{ 'telephone1': '15000303155' }";
    
    
    xrmHelper.UpdateAsync(entityAsyncUrl, uptAsyncObj, function (c, r) {
        console.log("update async\n");
    })


    //delete account
    var isDeleted=xrmHelper.Delete(entityUrl);
    console.log("delete "+isDeleted+" \n");

    xrmHelper.DeleteAsync(entityAsyncUrl, function (isDeleted) {
        console.log("delete " + isDeleted + " \n");
    })


    //execute API
    //who am I
    var userInfo=xrmHelper.ExecuteAPI("GET", "WhoAmI()", null);

    xrmHelper.ExecuteAPIAsync("GET", "WhoAmI()", null, function (r) {
        if (r != null)
        {
            console.log(r.UserId);
        }
    });}



  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值