关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复240或者20161204可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me 。

为了便利于用户及用户权限审计,需要将系统的用户及其角色、角色、角色权限等导出到Excel方便查看。我这里就以这样一个需求为例来做一个简单的控制台应用程序来导出这些信息到Excel中。为了方便查看结果,我这里除了系统管理员,还建立几个用户,团队来展示效果。
这里说一下如何为Dynamics 365建立CRM用户。我们On-Premise的Dynamics CRM一般(注意是一般,因为你如果了SSO的话,用户信息也可以不存储在CRM服务器所在AD中)需要先在CRM服务器所在的AD中增加用户。而Dynamics 365则是需要先在 Office 365 门户的用户管理部分 增加用户。打开的界面如下,点击 管理员 这个磁贴。
 
点击 添加用户 链接添加一个用户,我这里自己创建密码,不使用生成的随机密码。注意产品许可证要包括Dynamics 365的许可证,我这里是 Dynamics 365 Plan 1 Enterprise Edition。
 
然后我们就可以去Dynamics 365中的 设置 > 安全性 >用户就可以看到这个新建的用户了。
然后就是设置业务部门,安全角色等,这里和On-Premise版本的Dynamics CRM一样,就不赘述了。
下面就是我们的程序了,我创建一个控制台应用程序,除了要添加对Dynamics 365相关DLL的引用外,还需要添加对Microsoft.Office.Interop.Excel的引用,添加引用的时候选择 COM, 然后搜索excel就可以找到。运行后面的程序还需要本机安装了Excel。
Dynamics 365中的 安全角色 没有导出功能,包括使用高级查找也是如此,所以我们只有写程序导出了。
所有使用的程序代码如下:
using Microsoft.Office.Interop.Excel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Xml; namespace LuoYongLab
{
class Program
{
static void Main(string[] args)
{
try
{
var crmSvc = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRM365"].ConnectionString);
if (crmSvc.IsReady)
{
Console.WriteLine("导出安全角色开始");
var fetchXml = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='role'>
<attribute name='name' />
<attribute name='businessunitid' />
<attribute name='roleid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='parentroleid' operator='null' />
</filter>
</entity>
</fetch>");
EntityCollection ecRoles = crmSvc.RetrieveMultiple(new FetchExpression(fetchXml));
var excelApp = new Application();
excelApp.Visible = false;
Workbook securityWorkbook = excelApp.Workbooks.Add();
Worksheet rolesWorksheet = (Worksheet)excelApp.ActiveSheet;
rolesWorksheet.Name = "安全角色";
int row = ;
rolesWorksheet.Cells[, ] = "角色名称";
rolesWorksheet.Cells[, ] = "业务部门";
rolesWorksheet.Cells[, ] = "角色ID";
//rolesWorksheet.Rows[1].Font.Bold = true;//字体加粗
row++;
foreach (var roleEntity in ecRoles.Entities)
{
rolesWorksheet.Cells[row, ] = roleEntity.GetAttributeValue<string>("name");
rolesWorksheet.Cells[row, ] = roleEntity.GetAttributeValue<EntityReference>("businessunitid").Name;
rolesWorksheet.Cells[row, ] = roleEntity.GetAttributeValue<Guid>("roleid").ToString();
row++;
}
//rolesWorksheet.Columns[1].AutoFit();//自动列宽
rolesWorksheet.Range["A1", "C" + (row - )].AutoFormat(XlRangeAutoFormat.xlRangeAutoFormatColor1);
Console.WriteLine("导出用户及其安全角色开始");
fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='systemuser'>
<attribute name='fullname' />
<attribute name='businessunitid' />
<attribute name='systemuserid' />
<attribute name='domainname' />
<order attribute='fullname' descending='false' />
<filter type='and'>
<condition attribute='isdisabled' operator='eq' value='0' />
<condition attribute='accessmode' operator='ne' value='3' />
</filter>
</entity>
</fetch>";
EntityCollection ecUsers = crmSvc.RetrieveMultiple(new FetchExpression(fetchXml));
Worksheet usersWorksheet = securityWorkbook.Worksheets.Add();
usersWorksheet.Name = "用户";
row = ;
usersWorksheet.Cells[, ] = "用户姓名";
usersWorksheet.Cells[, ] = "业务部门";
usersWorksheet.Cells[, ] = "用户账户";
usersWorksheet.Cells[, ] = "用户角色";
usersWorksheet.Cells[, ] = "用户ID";
row++;
foreach (var userEntity in ecUsers.Entities)
{
usersWorksheet.Cells[row, ] = userEntity.GetAttributeValue<string>("fullname");
usersWorksheet.Cells[row, ] = userEntity.GetAttributeValue<EntityReference>("businessunitid").Name;
usersWorksheet.Cells[row, ] = userEntity.GetAttributeValue<string>("domainname");
usersWorksheet.Cells[row, ] = string.Join(",", GetUserRoles(crmSvc.OrganizationServiceProxy, userEntity.GetAttributeValue<Guid>("systemuserid")).Distinct());
usersWorksheet.Cells[row, ] = userEntity.GetAttributeValue<Guid>("systemuserid").ToString();
row++;
}
usersWorksheet.Range["A1", "E" + (row - )].AutoFormat(XlRangeAutoFormat.xlRangeAutoFormatColor1);
securityWorkbook.SaveAs(Filename: "CRMSecurities.xlsx", FileFormat: XlFileFormat.xlWorkbookDefault);
securityWorkbook.Close();
excelApp.Quit();
}
else
{
Console.WriteLine("连接CRM出错:" + crmSvc.LastCrmError);
}
Console.WriteLine("程序运行完成!");
Console.ReadKey();
}
catch (FaultException ex)
{
Console.WriteLine("程序出现异常:ex.Message=" + ex.Message);
Console.ReadKey();
}
} static IEnumerable<string> GetUserRoles(IOrganizationService service, Guid userId)
{
//首先获取用户直接授予的角色
string fetchXml = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='true'>
<entity name='role'>
<attribute name='name' />
<link-entity name='systemuserroles' from='roleid' to='roleid' visible='false' intersect='true'>
<link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ad'>
<filter type='and'>
<condition attribute='systemuserid' operator='eq' value='{0}' />
</filter>
</link-entity>
</link-entity>
</entity>
</fetch>", userId);
var userRolesDirect = service.RetrieveMultiple(new FetchExpression(fetchXml)).Entities.Select(x => x.GetAttributeValue<string>("name"));
//找出用户加入的所有负责人团队
fetchXml = string.Format(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='team'>
<attribute name='teamid' />
<filter type='and'>
<condition attribute='teamtype' operator='eq' value='0' />
</filter>
<link-entity name='teammembership' from='teamid' to='teamid' visible='false' intersect='true'>
<link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ah'>
<filter type='and'>
<condition attribute='systemuserid' operator='eq' value='{0}' />
</filter>
</link-entity>
</link-entity>
</entity>
</fetch>", userId);
var userTeams = service.RetrieveMultiple(new FetchExpression(fetchXml)).Entities.Select(x => x.GetAttributeValue<Guid>("teamid"));
//团队拥有的角色也是这个团队所有用户拥有的角色,所以还要加上这部分角色
var fetchXmlSb = new StringBuilder("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>");
fetchXmlSb.Append("<entity name='role'>");
fetchXmlSb.Append("<attribute name='name' />");
fetchXmlSb.Append("<order attribute='name' descending='false' />");
fetchXmlSb.Append("<link-entity name='teamroles' from='roleid' to='roleid' visible='false' intersect='true'>");
fetchXmlSb.Append("<link-entity name='team' from='teamid' to='teamid' alias='ak'>");
fetchXmlSb.Append("<filter type='or'>");
foreach (var team in userTeams)
{
fetchXmlSb.Append(string.Format("<condition attribute='teamid' operator='eq' value='{0}' />", team));
}
fetchXmlSb.Append("</filter>");
fetchXmlSb.Append("</link-entity>");
fetchXmlSb.Append("</link-entity>");
fetchXmlSb.Append("</entity>");
fetchXmlSb.Append("</fetch>");
var userRolesInTeam = service.RetrieveMultiple(new FetchExpression(fetchXmlSb.ToString())).Entities.Select(x => x.GetAttributeValue<string>("name"));
return userRolesDirect.Concat(userRolesInTeam);
}
}
}
得到的结果如下,这个Excel有两个Sheet,我分别截图,我的测试结果是把用户直接授予的角色和用户加入团队获取的角色都拿到了。
 
 

将Dynamics 365中的用户及其角色、角色导出到Excel中的更多相关文章

  1. html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式

    先上代码   <script type="text/javascript" language="javascript">   var idTmr; ...

  2. 将datagrid中数据导出到excel中 -------<<工作日志2014-6-6>>

    前台datagrid数据绑定 #region 导出到excel中    /// <summary>    /// 2014-6-6    /// </summary>    / ...

  3. 将Datagridview中的数据导出至Excel中

        首先添加一个模块ImportToExcel,并添加引用         然后导入命名空间: Imports Microsoft.Office.Interop Imports System.Da ...

  4. Winform 中 dataGridView 导出到Excel中的方法总结

    最近,在做CS端数据导出到Excel中时网上找了很多代码感觉都不是自己想要的,通过自己的整理归纳得到一个比较通用的方法,就给大家分享一下: 该方法需要用到两个参数(即对象),一个  DataGridV ...

  5. HTML table导出到Excel中的解决办法

    第一部分:html+js 1.需要使用的表格数据(先不考虑动态生成的table) <table class="table tableStyles" id="tabl ...

  6. C# html的Table导出到Excel中

    C#中导出Excel分为两大类.一类是Winform的,一类是Web.今天说的这一种是Web中的一种,把页面上的Table部分导出到Excel中. Table导出Excel,简单点说,分为以下几步: ...

  7. 把数据库里面的stu表中的数据,导出到excel中

    # 2.写代码实现,把我的数据库里面的stu表中的数据,导出到excel中 #编号 名字 性别 # 需求分析:# 1.连接好数据库,写好SQL,查到数据 [[1,'name1','男'],[1,'na ...

  8. html table导出到Excel中,不走后台,js完成

    静态表格table <table class="table tableStyles" id="tables"> <caption>不正经 ...

  9. JS将页面中表格,导出到Excel中(IE中)

    原文地址:http://blog.csdn.net/sinat_15114467/article/details/51098522 var idTmr; function getExplorer() ...

随机推荐

  1. java中的堆,栈和方法区(转)

    来源:https://www.cnblogs.com/iliuyuet/p/5603618.html https://blog.csdn.net/lin542405822/article/detail ...

  2. [Swift]LeetCode110. 平衡二叉树 | Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...

  3. [Swift]LeetCode165. 比较版本号 | Compare Version Numbers

    Compare two version numbers version1 and version2.If version1 > version2 return 1; if version1 &l ...

  4. shell脚本_查找无效网址

    #!/bin/bashif [ $# -ne 1 ];then      echo -e "$Usage: $0 URL\n"      exit 1;fi echo Broken ...

  5. 如何解决http请求返回结果中文乱码

    如何解决http请求返回结果中文乱码 1.问题描述 http请求中,请求的结果集中包含中文,最终以乱码展示. 2.问题的本质 乱码的本质是服务端返回的字符集编码与客户端的编码方式不一致. 场景的如服务 ...

  6. 我们为什么要搞长沙.NET技术社区?

    我们为什么要搞长沙.NET技术社区? 感谢大家的关注,请允许我冒昧的向大家汇报长沙.NET技术社区第一次交流会的会议进展情况. 活动过程汇报 2019年2月17日,继深圳,广州,西安,成都,苏州相继成 ...

  7. Jquery 对DOM 的操作

     .focus 获取焦点  .blus离开焦点----------------------------------------------------------------------------- ...

  8. Jenkins 集群搭建

    一.前言 Jenkins是当下比较流行的一款功能强大的持续集成工具,它支持搭建集群,来提高多项目的构建速度,模式为主从模式,master会将任务分配到各个从节点进行并发构建,从而提高速度,下面介绍一下 ...

  9. RAID磁盘阵列是什么(一看就懂)

    在单机时代,采用单块磁盘进行数据存储和读写的方式,由于寻址和读写的时间消耗,导致I/O性能非常低,且存储容量还会受到限制.另外,单块磁盘极其容易出现物理故障,经常导致数据的丢失.因此大家就在想,有没有 ...

  10. Spring系列(七) Spring MVC 异常处理

    Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...