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

先上图让大家看效果。权限列没有值则代表没有授予这个权限,1为个人级别,2为业务部门级别,3为上:下级业务部门,4为组织级别。

然后上代码,代码比较通俗易懂,有注意的地方我红色标注了一下,自己可以加上一些筛选,比如去掉导出对大部分标准实体的权限等,当然这个程序并没有导出杂项权限,有兴趣的可以自己修改下。

using Microsoft.Crm.Sdk.Messages;
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 System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel.Description;
using Excel = Microsoft.Office.Interop.Excel; namespace ExportRolePrivileges
{
class lyPrivilege
{
public string EntitySchemaName;
public string EntityDisplayName;
public string CreatePrivilege;
public string ReadPrivilege;
public string WritePrivilege;
public string DeletePrivilege;
public string AppendPrivilege;
public string AppendToPrivilege;
public string AssignPrivilege;
public string SharePrivilege;
}
class Program
{
static void Main(string[] args)
{
IServiceManagement<IOrganizationService> orgServiceMgr = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(ConfigurationManager.AppSettings["orgUrl"]));
AuthenticationCredentials orgAuCredentials = new AuthenticationCredentials();
orgAuCredentials.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings["userName"];
orgAuCredentials.ClientCredentials.UserName.Password = ConfigurationManager.AppSettings["passWord"];
using (OrganizationServiceProxy orgSvc = GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceMgr, orgAuCredentials))
{
WhoAmIRequest whoReq = new WhoAmIRequest();
WhoAmIResponse whoRep = orgSvc.Execute(whoReq) as WhoAmIResponse;
var userEntity = orgSvc.Retrieve("systemuser", whoRep.UserId, new ColumnSet("fullname"));
Console.WriteLine(string.Format("登录组织{0}成功,欢迎{1},继续操作请输入y!", ConfigurationManager.AppSettings["orgUrl"], userEntity.GetAttributeValue<string>("fullname")));
var input = Console.ReadLine().ToString().ToUpper();
if (input == "Y")
{
Console.WriteLine(string.Format("程序开始处理 - {0}", DateTime.Now.ToString()));
var meta = GetEntityMetadata(orgSvc);
var excelApp = new Excel.Application();
excelApp.Visible = false;
Excel.Workbook rolePrivilegeWorkbook = excelApp.Workbooks.Add(); var roleList = GetRoleList(orgSvc);
Console.WriteLine(string.Format("共有{0}个角色 - {1}", roleList.Count, DateTime.Now.ToString()));
foreach (var role in roleList)
{
Excel.Worksheet activeWorksheet = rolePrivilegeWorkbook.Worksheets.Add();
activeWorksheet.Name = role.Value;
int row = ;
activeWorksheet.Cells[, ] = "实体架构名称";
activeWorksheet.Cells[, ] = "实体显示名称(中文)";
activeWorksheet.Cells[, ] = "创建权限";
activeWorksheet.Cells[, ] = "读权限";
activeWorksheet.Cells[, ] = "写权限";
activeWorksheet.Cells[, ] = "删除权限";
activeWorksheet.Cells[, ] = "追加权限";
activeWorksheet.Cells[, ] = "追加到权限";
activeWorksheet.Cells[, ] = "分派权限";
activeWorksheet.Cells[, ] = "共享权限";
activeWorksheet.Rows[].Font.Bold = true;//字体加粗
row++;
var ls = GetRolePrivileges(orgSvc, role.Key, role.Value, meta).OrderBy(t => t.EntityDisplayName);
foreach (var item in ls)
{
activeWorksheet.Cells[row, ] = item.EntitySchemaName;
activeWorksheet.Cells[row, ] = item.EntityDisplayName;
activeWorksheet.Cells[row, ] = item.CreatePrivilege;
activeWorksheet.Cells[row, ] = item.ReadPrivilege;
activeWorksheet.Cells[row, ] = item.WritePrivilege;
activeWorksheet.Cells[row, ] = item.DeletePrivilege;
activeWorksheet.Cells[row, ] = item.AppendPrivilege;
activeWorksheet.Cells[row, ] = item.AppendToPrivilege;
activeWorksheet.Cells[row, ] = item.AssignPrivilege;
activeWorksheet.Cells[row, ] = item.SharePrivilege;
row++;
}
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
activeWorksheet.Columns[].AutoFit();//自动列宽
Console.WriteLine(string.Format("角色{0}处理完毕 - {1}", role.Value, DateTime.Now.ToString()));
}
rolePrivilegeWorkbook.SaveAs(Filename: @"D:\SecurityRolePrivileges.xlsx", FileFormat: Excel.XlFileFormat.xlWorkbookDefault);
rolePrivilegeWorkbook.Close();
excelApp.Quit();
}
}
Console.Write("程序执行完毕!");
Console.ReadKey();
} private static TProxy GetProxy<TService, TProxy>(
IServiceManagement<TService> serviceManagement,
AuthenticationCredentials authCredentials)
where TService : class
where TProxy : ServiceProxy<TService>
{
Type classType = typeof(TProxy); if (serviceManagement.AuthenticationType !=
AuthenticationProviderType.ActiveDirectory)
{
AuthenticationCredentials tokenCredentials =
serviceManagement.Authenticate(authCredentials);
return (TProxy)classType
.GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })
.Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });
}
return (TProxy)classType
.GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(ClientCredentials) })
.Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials });
} /// <summary>
/// 获得角色列表,这里排除了一部分角色
/// </summary>
/// <param name="orgSvc"></param>
/// <returns></returns>
private static Dictionary<Guid, string> GetRoleList(OrganizationServiceProxy orgSvc)
{
Dictionary<Guid, string> returnVal = new Dictionary<Guid, string>();
string[] excludeRoles = new string[] { "Support User", "Delegate","System Administrator","Activity Feeds",
"Scheduler","System Customizer","Knowledge Manager","UIIAgent","UIIAdministrator","USD Administrator","USD Agent","系统定制员","系统管理员","代理","知识管理员"};
var rootBuId = GetRootBUId(orgSvc);
string fetchXml = string.Format(@"<fetch version='1.0' no-lock='true' mapping='logical' distinct='false'>
<entity name='role'>
<attribute name='name' />
<attribute name='roleid' />
<filter type='and'>
<condition attribute='businessunitid' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>", rootBuId);
foreach (var item in orgSvc.RetrieveMultiple(new FetchExpression(fetchXml)).Entities)
{
var roleName = item.GetAttributeValue<string>("name");
if (!excludeRoles.Contains(roleName))
{
returnVal.Add(item.GetAttributeValue<Guid>("roleid"), roleName);
}
}
return returnVal;
} private static List<lyPrivilege> GetRolePrivileges(OrganizationServiceProxy orgSvc, Guid roleId, string roleName, Dictionary<string, string> entityMetadata)
{
Console.WriteLine(string.Format("开始提取角色 {0} - {1} 的权限", roleName, roleId));
List<lyPrivilege> temList = new List<lyPrivilege>();
List<lyPrivilege> returnVal = new List<lyPrivilege>();
string fetchXml = string.Format(@"<fetch version='1.0' mapping='logical' distinct='false' no-lock='true'>
<entity name='roleprivileges'>
<attribute name='privilegedepthmask'/>
<filter type='and'>
<condition attribute='roleid' operator='eq' value='{0}' />
</filter>
<link-entity name='privilege' alias='prvs' to='privilegeid' from='privilegeid' link-type='inner'>
<attribute name='name'/>
<attribute name='accessright'/>
</link-entity>
</entity>
</fetch>", roleId);
foreach (var item in orgSvc.RetrieveMultiple(new FetchExpression(fetchXml)).Entities)
{
lyPrivilege lyp = new lyPrivilege();
string prvName = item.GetAttributeValue<AliasedValue>("prvs.name").Value.ToString();
lyp.EntitySchemaName = GetEntitySchemaName(prvName);
lyp.EntityDisplayName = GetEntityDisplayName(lyp.EntitySchemaName, entityMetadata);
int accessRight = Convert.ToInt32(item.GetAttributeValue<AliasedValue>("prvs.accessright").Value);
//可以根据需要排除对一些实体的权限导出来,做到更加简洁
if (lyp.EntityDisplayName != string.Empty)//为空的不是实体权限不需要处理
{
switch (accessRight)
{
case :
lyp.ReadPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.WritePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.AppendPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.AppendToPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.CreatePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.DeletePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.SharePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
case :
lyp.AssignPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString();
break;
}
temList.Add(lyp);
}
}
var distinctQuery = temList.GroupBy(p => new { p.EntitySchemaName }).Select(g => g.First()).ToList();
foreach (var item in distinctQuery)
{
lyPrivilege prv = new lyPrivilege();
prv.EntitySchemaName = item.EntitySchemaName;
prv.EntityDisplayName = item.EntityDisplayName;
prv.ReadPrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.ReadPrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.ReadPrivilege)).First().ReadPrivilege : string.Empty;
prv.WritePrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.WritePrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.WritePrivilege)).First().WritePrivilege : string.Empty;
prv.CreatePrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.CreatePrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.CreatePrivilege)).First().CreatePrivilege : string.Empty;
prv.AssignPrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.AssignPrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.AssignPrivilege)).First().AssignPrivilege : string.Empty;
prv.SharePrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.SharePrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.SharePrivilege)).First().SharePrivilege : string.Empty;
prv.AppendToPrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.AppendToPrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.AppendToPrivilege)).First().AppendToPrivilege : string.Empty;
prv.AppendPrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.AppendPrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.AppendPrivilege)).First().AppendPrivilege : string.Empty;
prv.DeletePrivilege = temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && (!string.IsNullOrEmpty(t.DeletePrivilege))).Count() >= ? temList.Where(t => t.EntitySchemaName == prv.EntitySchemaName && !string.IsNullOrEmpty(t.DeletePrivilege)).First().DeletePrivilege : string.Empty;
returnVal.Add(prv);
}
return returnVal;
} //活动实体需要特别处理,替换的时候先替换prvAppendTo,在替换prvAppend,否则获取不到追加到权限。
//用户和业务部门实体有Disable权限,用户的实体名称在权限表中是User要特别转换成真的实体名称
private static string GetEntitySchemaName(string privelegeName)
{
string returnVal = string.Empty;
returnVal = privelegeName.Replace("prvAssign", "");
returnVal = privelegeName.Replace("prvDisable", "");
returnVal = returnVal.Replace("prvDelete", "");
returnVal = returnVal.Replace("prvRead", "");
returnVal = returnVal.Replace("prvCreate", "");
returnVal = returnVal.Replace("prvWrite", "");
returnVal = returnVal.Replace("prvAppendTo", "");
returnVal = returnVal.Replace("prvAppend", "");
returnVal = returnVal.Replace("prvShare", "");
returnVal = returnVal.Replace("prv", "");
if (returnVal == "Activity")
{
returnVal = "ActivityPointer";
}
if (returnVal == "User")
{
returnVal = "SystemUser";
}
return returnVal;
}
private static string GetEntityDisplayName(string entitySchemaName, Dictionary<string, string> entityMetadata)
{
string returnVal = string.Empty;
if (!string.IsNullOrEmpty(entitySchemaName) && entityMetadata.Where(item => item.Key == entitySchemaName.ToLower()).ToList().Count() >= )
{
returnVal = entityMetadata.Where(item => item.Key == entitySchemaName.ToLower()).First().Value;
}
return returnVal;
}
private static int TransferPrivilege(int privilegedepthmask)
{
int returnVal = -;
switch (privilegedepthmask)
{
case :
returnVal = ;
break;
case :
returnVal = ;
break;
case :
returnVal = ;
break;
case :
returnVal = ;
break;
}
return returnVal;
} /// <summary>
/// 获取实体架构名称及其中文显示名称
/// </summary>
/// <param name="orgSvc"></param>
/// <returns></returns>
private static Dictionary<string, string> GetEntityMetadata(OrganizationServiceProxy orgSvc)
{
Dictionary<string, string> returnVal = new Dictionary<string, string>();
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
{
EntityFilters = EntityFilters.Entity,
RetrieveAsIfPublished = true
};
RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)orgSvc.Execute(request);
foreach (EntityMetadata currentEntity in response.EntityMetadata)
{
returnVal.Add(currentEntity.LogicalName,
currentEntity.DisplayName.LocalizedLabels.Where(a => a.LanguageCode == ).Count() >= ? currentEntity.DisplayName.LocalizedLabels.Where(a => a.LanguageCode == ).FirstOrDefault().Label : string.Empty);
}
return returnVal;
} /// <summary>
/// 获取根业务部门的GUID
/// </summary>
/// <param name="orgSvc">组织服务</param>
/// <returns></returns>
private static Guid GetRootBUId(OrganizationServiceProxy orgSvc)
{
Guid returnVal = Guid.Empty;
string fetchXml = @"<fetch version='1.0' mapping='logical' distinct='false' count='1' no-lock='true'>
<entity name='businessunit'>
<attribute name='businessunitid' />
<filter type='and'>
<condition attribute='parentbusinessunitid' operator='null' />
</filter>
</entity>
</fetch>";
var buEntities = orgSvc.RetrieveMultiple(new FetchExpression(fetchXml));
if (buEntities.Entities.Count >= )
{
returnVal = buEntities.Entities[].GetAttributeValue<Guid>("businessunitid");
}
return returnVal;
}
}
}

自定义控制台程序导出角色对实体的权限为Excel文件的更多相关文章

  1. 自定义控制台程序导出Dynamics 365实体信息到Excel中。

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

  2. Excelbatis-一个将excel文件读入成实体列表、将实体列表解析成excel文件的ORM框架,简洁易于配置、可扩展性好

    欢迎使用Excelbatis! github地址:https://github.com/log4leo/Excelbatis Excelbatis的优点 和spring天然结合,易于接入 xsd支持, ...

  3. PHP导出带有emoji表情的文本到excel文件出问题了

    前段时间做了一个导出用户信息(包含微信昵称)到excel文件的功能,一直没问题,今天突然有人反馈说导出来的数据有一些丢失了.我试了一下,发现有些数据导出没问题,有些有问题,某些列出现了空白,数据打印出 ...

  4. Java导出页面数据或数据库数据至Excel文件并下载,采用JXL技术,小demo(servlet实现)

    public class ExportExcelServlet extends HttpServlet { /** * */ private static final long serialVersi ...

  5. 控制台程序读取Excel设置角色权限

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

  6. java使用POI操作excel文件,实现批量导出,和导入

    一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...

  7. winfrom窗体加载控制台程序,可以自定义输出语句颜色

    winfrom窗体加载控制台程序,可以自定方输出语句颜色,如下图所示 怎么实现的此功能,网上有大把的方法,我这里已经把方法打包成了一个类,只需要引用调用就可以使用了,写的比较粗糙,如有发现需要改进的地 ...

  8. 【半小时大话.net依赖注入】(一)理论基础+实战控制台程序实现AutoFac注入

    系列目录 第一章|理论基础+实战控制台程序实现AutoFac注入 第二章|AutoFac的常见使用套路 第三章|实战Asp.Net Framework Web程序实现AutoFac注入 第四章|实战A ...

  9. 理论基础+实战控制台程序实现AutoFac注入

    [半小时大话.net依赖注入](一)理论基础+实战控制台程序实现AutoFac注入   系列目录# 第一章|理论基础+实战控制台程序实现AutoFac注入 第二章|AutoFac的常见使用套路 第三章 ...

随机推荐

  1. 【分享】【原创开源应用第4期】给ili9488,RA8875类显示屏的emWin底层增加DMA加速方案

    说明:1.emWin底层中最重要的一个优化就是16bpp绘制,特此为其增加DMA加速,已经支持RA8875和ili9488.2.使用中务必将emWin任务设置为除了空闲任务,统计任务以外的最低优先级, ...

  2. xss挖掘初上手

    本文主要总结了xss可能出现的场景.偏向于案例,最后分享一哈简单的绕过和比较好用的标签. 1.搜索框 首先看能否闭合前面的标签. 如输入111”><svg/onload=alert(1)& ...

  3. [Swift]LeetCode375. 猜数字大小 II | Guess Number Higher or Lower II

    We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...

  4. [Swift]LeetCode989. 数组形式的整数加法 | Add to Array-Form of Integer

    For a non-negative integer X, the array-form of X is an array of its digits in left to right order.  ...

  5. [Swift]LeetCode1000. 合并石头的最低成本 | Minimum Cost to Merge Stones

    There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones. A move consists ...

  6. Hibernate框架笔记04HQL_QBC查询详解_抓取策略优化机制

    目录 1. Hibernate的查询方式 1.1 方式一:OID查询 1.2 方式二:对象导航查询 1.3 方式三:HQL方式 1.4 方式四:QBC查询 1.5 方式五:SQL查询 2. 环境搭建 ...

  7. JVM基础系列第2讲:Java 虚拟机的历史

    说起 Java 虚拟机,许多人就会将其与 HotSpot 虚拟机等同看待.但实际上 Java 虚拟机除了 HotSpot 之外,还有 Sun Classic VM.Exact VM.BEA JRock ...

  8. 【Git】(2)---checkout、branch、log、diff、.gitignore

    常用命令 一.命令 1.checkout 切换分支 git checkout 分支名 #切换分支 #如果在当前分支上对文件进行修改之后,没有commit就切换到另外一个分支b, 这个时候会报错,因为没 ...

  9. qt 拖拽 修改大小

    写次篇文章之前,qt窗口的放大缩小和拖拽我都是通过setGeometry方法实现的,但是作为windows程序,windows支持橡 皮筋式(拖拽时有一个虚框)拖拽和拉伸.通过setGeometry方 ...

  10. Android--从系统Gallery获取图片

    前言 在Android应用中,经常有场景会需要使用到设备上存储的图片,而直接从路径中获取无疑是非常不便利的.所以一般推荐调用系统的Gallery应用,选择图片,然后使用它.本篇博客将讲解如何在Andr ...