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





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);
}
}
}


将Dynamics 365中的用户及其角色、角色导出到Excel中的更多相关文章
- 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; ...
- 将datagrid中数据导出到excel中 -------<<工作日志2014-6-6>>
前台datagrid数据绑定 #region 导出到excel中 /// <summary> /// 2014-6-6 /// </summary> / ...
- 将Datagridview中的数据导出至Excel中
首先添加一个模块ImportToExcel,并添加引用 然后导入命名空间: Imports Microsoft.Office.Interop Imports System.Da ...
- Winform 中 dataGridView 导出到Excel中的方法总结
最近,在做CS端数据导出到Excel中时网上找了很多代码感觉都不是自己想要的,通过自己的整理归纳得到一个比较通用的方法,就给大家分享一下: 该方法需要用到两个参数(即对象),一个 DataGridV ...
- HTML table导出到Excel中的解决办法
第一部分:html+js 1.需要使用的表格数据(先不考虑动态生成的table) <table class="table tableStyles" id="tabl ...
- C# html的Table导出到Excel中
C#中导出Excel分为两大类.一类是Winform的,一类是Web.今天说的这一种是Web中的一种,把页面上的Table部分导出到Excel中. Table导出Excel,简单点说,分为以下几步: ...
- 把数据库里面的stu表中的数据,导出到excel中
# 2.写代码实现,把我的数据库里面的stu表中的数据,导出到excel中 #编号 名字 性别 # 需求分析:# 1.连接好数据库,写好SQL,查到数据 [[1,'name1','男'],[1,'na ...
- html table导出到Excel中,不走后台,js完成
静态表格table <table class="table tableStyles" id="tables"> <caption>不正经 ...
- JS将页面中表格,导出到Excel中(IE中)
原文地址:http://blog.csdn.net/sinat_15114467/article/details/51098522 var idTmr; function getExplorer() ...
随机推荐
- ABP入门系列(2)——领域层创建实体
ABP入门系列目录--学习Abp框架之实操演练 这一节我们主要和领域层打交道.首先我们要对ABP的体系结构以及从模板创建的解决方案进行一一对应.网上有代码生成器去简化我们这一步的任务,但是不建议初学者 ...
- [Swift]LeetCode25. k个一组翻转链表 | Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k ...
- [Swift]LeetCode847. 访问所有节点的最短路径 | Shortest Path Visiting All Nodes
An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph. graph.lengt ...
- 为什么大一先要学C语言(面向过程)再学C++或JAVA(面向对象)?
面向对象和面向过程各有千秋 一.面向过程与面向对象对比 面向过程:强调的是每一个功能的步骤,有很多很多方法组成,这些方法相互调用,完成需求. 面向对象:强调的是对象,然后由对象去调用功能. 面向过程 ...
- SSM框架报HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException错
如下图 一番排查之后发现原来是server层写漏注释了 粗心大意,一天内出现两次写漏注释,SSM框架有意思.
- Tomcat相关面试题,看这篇就够了!保证能让面试官颤抖!
Tomcat相关的面试题出场的几率并不高,正式因为如此,很多人忽略了对Tomcat相关技能的掌握. 这次整理了Tomcat相关的系统架构,介绍了Server.Service.Connector.Con ...
- C# 获取 ipv4的方法
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adap ...
- 行为驱动:Cucumber + Selenium + Java(二) - 第一个测试
在上一篇中,我们搭建好了Selenium + Cucumber + Java的自动化测试环境,这一篇我们就赶紧开始编写我们的第一个BDD测试用例. 2.1 创建features 我们在新建的java项 ...
- Vue2.0中的transition组件
组件的过度 Vue1.0中transition做为标签的行内属性被vue支持.但在Vue2.0中.Vue放弃了旧属性的支持并提供了transition组件,transition做为标签被使用. 使用t ...
- 自定义的jdbc连接工具类JDBCUtils【java 工具类】
JDBCUtils 类设计: 1. 创建私有的属性*(连接数据库必要的四个变量):dreiver url user password 2. 将构造函数私有化 3.将注册驱动写入静态代码块 4.外界只能 ...