补充三:Dynamics 365操纵示例
Posted 位永光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了补充三:Dynamics 365操纵示例相关的知识,希望对你有一定的参考价值。
常见问题
- 前端请求400错误,参数问题
- 前端请求500错误,请求地址问题,后端方法问题
- 流程唯一名称不可同名,添加,导入后按唯一名称查询下
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种查询数据的方式,分别是QueryExpression
、fetchxml
、linq
,本篇讲述的条件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(选项值);
以上是关于补充三:Dynamics 365操纵示例的主要内容,如果未能解决你的问题,请参考以下文章
Dynamics 365Online Lookup查找字段多选