補充三:Dynamics 365操縱示例


常見問題

  1. 前端請求400錯誤,參數問題
  2. 前端請求500錯誤,請求地址問題,后端方法問題
  3. 流程唯一名稱不可同名,添加,導入后按唯一名稱查詢下

C#示例

示例一:多表內聯

需求:根據記錄的id查詢給記錄的歷史記錄中的更改人(用戶名稱)是否擁有管理員角色

分步查詢

// 根據唯一線索id獲取所有記錄中的用戶名稱
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
    <entity name="jk_assignment_log" >
		<attribute name="jk_assignment_object" />
        <filter type="and" >
            <condition attribute="statecode" operator="eq" value="0" />
            <condition attribute="jk_lead" operator="eq" value="618620BD-EF28-417E-982C-8057201B6D48" />
        </filter>
    </entity>
</fetch>

// 根據用戶名稱獲取用戶名稱和id
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
    <entity name="systemuser" >
        <attribute name="systemuserid" />
		<attribute name="fullname" />
		<filter type="and" >
            <condition attribute="fullname" operator="eq" value="優文途新管理員" />
        </filter>
    </entity>
</fetch>


// 查詢此用戶id是否存在執行角色名稱
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
    <entity name="role" >
        <attribute name="name" />
        <attribute name="businessunitid" />
        <attribute name="roleid" />
        <filter type="and" >
            <condition attribute="name" operator="eq" value="系統管理員" />
        </filter>
        <link-entity name="systemuserroles" from="roleid" to="roleid" visible="false" intersect="true" >
            <link-entity name="systemuser" from="systemuserid" to="systemuserid" alias="ad" >
                <attribute name="systemuserid" />
                <filter type="and" >
                    <condition attribute="systemuserid" operator="eq" value="65AD644C-64F7-E811-A81E-9A16184AF7BF" />
                </filter>
            </link-entity>
        </link-entity>
    </entity>
</fetch>

聯表查詢

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
    <entity name="jk_assignment_log" >
		<attribute name="jk_assignment_object" />
        <filter type="and" >
            <condition attribute="statecode" operator="eq" value="0" />
            <condition attribute="jk_lead" operator="eq" value="618620BD-EF28-417E-982C-8057201B6D48" />
        </filter>
		<link-entity name="systemuser" from="fullname" to="jk_assignment_object">
			<attribute name="systemuserid" />
			<attribute name="fullname" />
			<link-entity name="systemuserroles" from="systemuserid" to="systemuserid">
				<link-entity name="role" from="roleid" to="roleid">
					<filter type="and" >
						<condition attribute="name" operator="eq" value="系統管理員" />
					</filter>
				</link-entity>
			</link-entity>
		</link-entity>
    </entity>
</fetch>

示例二:事務操作

Dynamics CRM 2015 UR1 新增了 ExecuteTransactionRequest,主要用來處理事務操作,即一組操作;

例一

using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;

public static void ExecuteTransactionAction(OrganizationServiceProxy server)
{
    #region 增加操作
    CreateRequest add_req = new CreateRequest();
    Entity add_entity = new Entity("mcs_tc_order");
    add_entity["mcs_state"] = new OptionSetValue(1);
    add_entity["mcs_approvalstatus"] = new OptionSetValue(1);
    add_req.Target = add_entity;
    #endregion

    #region 修改操作
    UpdateRequest up_req = new UpdateRequest();
    ColumnSet attributes = new ColumnSet(new string[] { "mcs_state", "ownerid" });
    Entity up_entity = server.Retrieve("mcs_tc_order", new Guid("xxx"), attributes);
    up_entity.Attributes["mcs_state"] = new OptionSetValue(2);
    up_req.Target = up_entity;
    #endregion

    #region 刪除操作
    DeleteRequest del_req = new DeleteRequest();
    Guid id = new Guid("xxx");
    del_req.Target = new EntityReference("mcs_tc_order",id);
    #endregion

    ExecuteTransactionRequest req = new ExecuteTransactionRequest();
    req.Requests = new OrganizationRequestCollection() { add_req,up_req, del_req };
    server.Execute(req);
}

例二

// 1.創建事務對象
var TranRequest = new ExecuteTransactionRequest()
{
    ReturnResponses = true, // 可選
    Requests = new OrganizationRequestCollection(),
};

// 2.1 更新操作,temp為更新的記錄且已存在的記錄
TranRequest.Requests.Add(new UpdateRequest() { Target = temp });

// 2.2 刪除操作,temp為ToEntityReference類型且已存在的記錄
TranRequest.Requests.Add(new DeleteRequest() { Target = temp.ToEntityReference() });

// 2.3 新建操作,temp為新記錄
TranRequest.Requests.Add(new CreateRequest() { Target = temp });

// 3. 執行事務
if (TranRequest.Requests.Count() > 0) service.Execute(TranRequest);

示例三:構建IN查詢

CRM中有3種查詢數據的方式,分別是QueryExpressionfetchxmllinq,本篇講述的條件IN的查詢只支持前兩種,linq並不支持

QueryExpression方式

var Names = new string[] { "劉慶", "王雲帆" };
var filter = new FilterExpression(LogicalOperator.And)
{
    Conditions =
        {
            new ConditionExpression("new_name", ConditionOperator.In, Names)
        }
};
var query = new QueryExpression("new_service")
{
    ColumnSet = new ColumnSet(true),
    Criteria = filter
};

fetchxml方式

<fetch version='1.0' output-format='xml-platform' mapping='logical'>
    <entity name ='new_service'>
        <attribute name ='new_name'/>
        <filter type = 'and'>
        	<condition attribute = 'new_name' operator='in'>
                <value>劉慶</value>
                <value>王雲帆</value>
            </condition>
        </filter>
    </entity>
</fetch>

示例四:共享操作

取消用戶/團隊對此記錄的共享|權限

RevokeAccessRequest revokerequest = new RevokeAccessRequest
{
    Revokee = new EntityReference(user.LogicalName,user.Id),	// 用戶/團隊,
    Target = new EntityReference(entity.LogicalName, entity.Id)		// 記錄
};

設置共享

GrantAccessRequest grantAccessRequest = new GrantAccessRequest
{
    PrincipalAccess = new PrincipalAccess
    {
        Principal = teamOrSystem,   // 團隊或用戶
        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess // 權限
    },
    Target = Record,    // 記錄
};

獲取此記錄的所有共享者

//1.創建請求
EntityReference target = new EntityReference(entity.LogicalName,entity.Id);
RetrieveSharedPrincipalsAndAccessRequest shareRequest = 
    new RetrieveSharedPrincipalsAndAccessRequest();
shareRequest.Target = target;

//2.執行請求,獲取共享者
RetrieveSharedPrincipalsAndAccessResponse shareResponse = (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(shareRequest);

if (shareResponse.PrincipalAccesses != null)
{
    //3.遍歷共享者列表
    foreach (PrincipalAccess pa in shareResponse.PrincipalAccesses)
    {
        Console.WriteLine("AccessMask: " + pa.AccessMask);
        Console.WriteLine("用戶Id: " + pa.Principal.Id + ",LogicalName: " + pa.Principal.LogicalName); 
    }
}

示例五:用戶是否擁有指定角色

// 查詢擁有某個角色的用戶
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true" >
    <entity name="role" >
        <attribute name="name" />
        <attribute name="businessunitid" />
        <attribute name="roleid" />
        <filter type="and" >
            <condition attribute="name" operator="eq" value="系統管理員" />
        </filter>
        <link-entity name="systemuserroles" from="roleid" to="roleid" visible="false" intersect="true" >
            <link-entity name="systemuser" from="systemuserid" to="systemuserid" alias="ad" >
                <attribute name="systemuserid" />
				<attribute name="fullname" />
            </link-entity>
        </link-entity>
    </entity>
</fetch>
public bool GetExitOrRole(Guid uid)
{
    var fetch = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' >
                        <entity name='role' >
                            <attribute name='name' />
                            <attribute name='businessunitid' />
                            <attribute name='roleid' />
                            <filter type='or' >
                                <condition attribute='name' operator='in'>
                                    <value>線索-廳店-銷售顧問</value>
                                    <value>線索-廳店-店長</value>
                                </condition>
                            </filter>
                            <link-entity name='systemuserroles' from='roleid' to='roleid' visible='false' intersect='true' >
                                <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ad' >
                                    <attribute name='systemuserid' />
                                    <filter type='and' >
                                        <condition attribute='systemuserid' operator='eq' value='{uid}' />
                                    </filter>
                                </link-entity>
                            </link-entity>
                        </entity>
                    </fetch>";
    List<Entity> listData = new List<Entity>();
    var result = CRMEntityHelper.Retrive(fetch);
    if (result != null) return true;
    return false;
}

示例六:查詢用戶指定實體待辦

public List<Entity> GetTask(string entityName, Guid userId)
{
    string xml = 
        $@"<fetch>
            <entity name=‘task‘ >
                <all-attributes/>
                <link-entity name=‘{entityName}‘ from=‘{entityName}id‘ to=‘regardingobjectid‘>
                    <filter>
                        <condition attribute=‘statecode‘ operator=‘eq‘ value=‘0‘ />
                    </filter>
                </link-entity>
                <filter>
                    <condition attribute=‘ownerid‘ operator=‘eq‘ value=‘{userId}‘ />
                    <condition attribute=‘statecode‘ operator=‘eq‘ value=‘0‘ />
                </filter>
            </entity>
            </fetch>";
    ...
}

示例七:待辦任務

前提是關聯實體要支持創建活動

創建待辦

Entity task = new Entity("task");
task["subject"] = $"您有新的任務,請及時關注!";
task["regardingobjectid"] = new EntityReference("mcs_activity", id);
task["ownerid"] = owner;
task["statecode"] = new OptionSetValue(0);//已開啟
service.Create(task);

示例八:查詢團隊下所有用戶

<fetch mapping='logical' version='1.0'>
	<entity name='team'>
		<filter>
			<condition attribute='name' operator='eq' value='客服部培訓講師' />
		</filter>
		<link-entity name='teammembership' from='teamid' to='teamid' alias='u' >
			<attribute name='systemuserid' />
		</link-entity>  
	</entity>            
</fetch>

JavaScript示例

示例零:處理ID

"{7DF7D073-7EB1-EB11-9C19-005056A6E132}".replace("{", "").replace("}", "")

示例一:禁用表單字段

function disableForm(){
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls) {
        var control = controls[i];
        if (control.getControlType() != "iframe" 
            && control.getControlType() != "webresource"
            && control.getControlType() != "subgrid" 
            && control.getDisabled() == false) 
        {
            control.setDisabled(true);
        }
    }
}

示例二:窗體保存事件

該代碼需要配置OnSave事件,並啟用“將執行上下文作為第一個參數”

示例場景:通過判斷是否字段未保存來防止觸發

function SaveAlert(ExecutionObj) {
    var project_stage = Xrm.Page.getAttribute("new_productproject_stage").getValue();
    if (project_stage >= 7) {
        if (Xrm.Page.getAttribute("new_internalresourcesid").getIsDirty()) {
            if (confirm("生產公司簡稱變更將會郵件通知總經理,請點擊確認/取消變更。")) {
            }
            else {
                ExecutionObj.getEventArgs().preventDefault();//阻止保存操作
            }
        }    
    }
}

示例三:禁用子網格列不可編輯

function LockGuidByItemListCol() {
	var gridename = "tb_itemlist";
	var field = [
		"jk_purchaseorderno", "jk_erporderlinenumber", "jk_partcode"
	];

	if (gridename && field && field instanceof Array) {
		var rows = Xrm.Page.getControl(gridename).getGrid().getSelectedRows();
		var attributes = rows.get(0).data.entity.attributes;
		for (var i = 0; i < field.length; i++) {
			var contr = attributes.getByName(field[i]);
			if (contr) {
				contr.controls.get(0).setDisabled(true);
			}
		}
	}
}

示例四:自定義頁面

打開頁面(A頁面)

// 調用B頁面
function LinkToThatPage() {
    // 傳遞參數
    var parameters = {}
    parameters.EntityId = Xrm.Page.data.entity.getId();
    parameters.EnityName = "唯一線索";
    
    // 窗體的屬性
    var DialogOptions = new Xrm.DialogOptions;
    DialogOptions.height = 400;
    DialogOptions.width = Xrm.Page.context.client.getClient() === "Mobile" ? 500 : 450;
    
    Xrm.Internal.openDialog("/B.html",DialogOptions, parameters, null, ThatCallback);
};

//B頁面回調函數
function ThatCallback(data) {
    console.log(data)
}

處理頁面(B頁面)

$(function () {
    loadData();
})

// 加載數據
function loadData() {
    // 獲取傳遞參數
    var DialogArguments = window.getDialogArguments();
    if (!DialogArguments) {
        return;
    }
    var id = window.getDialogArguments().EntityId;
    ...
}

// 返回數據
function okay() {
    var data = {};
    data.uid = val;
    Mscrm.Utilities.setReturnValue(data);
    closeWindow(true);
}

// 關閉窗體
function cancel() {
    closeWindow(true);
}

示例五:獲取缺少權限的實體

https://stncdev.stnct.cn:446/api/data/v9.0/EntityDefinitions?$filter=ObjectTypeCode eq 10250 &$select=LogicalName

示例六:查找類型增加篩選條件

簡單篩選,適用於兩個實體,只是在原有視圖中增加了查詢條件

查找控件增加preSearch事件,此事件發生在查找控件顯示對話框供用戶查找記錄之前,只有通過代碼方式添加

添加事件:Xrm.Page.getControl(arg).addPreSearch(handler)

移除事件:Xrm.Page.getControl(arg).removePreSearch(handler)

說明:此條件查詢的關聯關系為 inner 關聯

/**
 * 窗體加載事件
 */
function from_load() {
    Xrm.Page.getControl("new_cityid").addPreSearch(function () { // 市
        addPostingByShiLookupFilter();
    });
}

/**
 * 篩選市
 */
function addPostingByShiLookupFilter() {
    var gl = Xrm.Page.getAttribute("new_provinceid").getValue(); // 省
    var fetchXml = "<filter type='and'><condition attribute='new_provinceid' operator='eq' value='" + gl[0].id + "' /></filter>";
    Xrm.Page.getControl("new_cityid").addCustomFilter(fetchXml); // 市
}

高級篩選:可用於多個實體,使用自定義視圖

/**
 * 窗體加載事件
 */
function from_load() {
    TaxCodeCustomView();
}

function TaxCodeCustomView() {
    var company = Xrm.Page.getAttribute("new_cityid").getValue(); // 市
    var viewId = "{00000000-0000-0000-0000-000000000001}";
    var viewDisplayName = "自定義視圖";
    var filter = "";

    if (company != null) {
        filter = "<filter><condition attribute='new_cityid' operator='eq' value='" + company[0].id + "' /></filter>";
    }

    var fetchXml = "<fetch mapping='logical'>" +
        "<entity name='new_region'>" +
        "<attribute name='new_code' />" +
        "<attribute name='new_name' />" +
        filter +
        "</entity>" +
        "</fetch>";

    var layoutXml = "<grid name='resultSet' object='10024' jump='new_name' select='1' icon='1' preview='1'>" +
        "<row name='result' id='new_taxprocedure_taxcodeid'>" +
        "<cell name='new_code' width='100' />" +
        "<cell name='new_name' width='300' />" +
        "</row></grid>";
    Xrm.Page.getControl("new_regionid").addCustomView(viewId, "new_region", viewDisplayName, fetchXml, layoutXml, true);
}

示例七:獲取TAB中節中所有控件

Xrm.Page.ui.tabs.get("tab_11").getSections().get("tab_11_section_1").getControls().getLength();

示例八:刷新當前頁面

function Refresh() {
	var id = Xrm.Page.data.entity.getId();
	var entityname = Xrm.Page.data.entity.getEntityName();
	Xrm.Utility.openEntityForm(entityname, id);
}

示例九:選項集操作

移除選項集項

Xrm.Page.getControl("屬性名").removeOption(選項值);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM