本人微信公众号:微软动态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 Microsoft.Xrm.Tooling.Connector;using System;using System.Collections.Generic;using System.Configuration;using System.Linq;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) { try { Console.WriteLine($"程序正在尝试连接到Dynamics 365/Power Apps环境..."); CrmServiceClient crmSvc = new CrmServiceClient(ConfigurationManager.AppSettings["connStr"]); if (!crmSvc.IsReady) { throw new Exception("连接CRM失败!" + crmSvc.LastCrmError); } var orgSvc = crmSvc.OrganizationServiceProxy; WhoAmIRequest whoReq = new WhoAmIRequest(); WhoAmIResponse whoRep = crmSvc.Execute(whoReq) as WhoAmIResponse; var userEntity = crmSvc.Retrieve("systemuser", whoRep.UserId, new ColumnSet("fullname")); Console.WriteLine($"登录组织{crmSvc.ConnectedOrgFriendlyName}成功,欢迎{userEntity.GetAttributeValue<string>("fullname")},将会导出角色权限到Excel文件,继续操作请输入y!"); var input = Console.ReadLine().ToString().ToUpper(); if (input == "Y") { Console.WriteLine($"程序开始处理 - {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($"共有{roleList.Count}个角色 - {DateTime.Now.ToString()}"); Excel.Worksheet activeWorksheet = rolePrivilegeWorkbook.ActiveSheet; activeWorksheet.Name = "SecurityRolePrivileges"; int row = 1; activeWorksheet.Cells[1, 1] = "角色名称"; activeWorksheet.Cells[1, 2] = "实体架构名称"; activeWorksheet.Cells[1, 3] = "实体显示名称"; activeWorksheet.Cells[1, 4] = "创建权限"; activeWorksheet.Cells[1, 5] = "读权限"; activeWorksheet.Cells[1, 6] = "写权限"; activeWorksheet.Cells[1, 7] = "删除权限"; activeWorksheet.Cells[1, 8] = "追加权限"; activeWorksheet.Cells[1, 9] = "追加到权限"; activeWorksheet.Cells[1, 10] = "分派权限"; activeWorksheet.Cells[1, 11] = "共享权限"; activeWorksheet.Rows[1].Font.Bold = true;//字体加粗 row++; foreach (var role in roleList) { var ls = GetRolePrivileges(orgSvc, role.Key, role.Value, meta).OrderBy(t => t.EntityDisplayName); foreach (var item in ls) { activeWorksheet.Cells[row, 1] = role.Value; activeWorksheet.Cells[row, 2] = item.EntitySchemaName; activeWorksheet.Cells[row, 3] = item.EntityDisplayName; activeWorksheet.Cells[row, 4] = item.CreatePrivilege; activeWorksheet.Cells[row, 5] = item.ReadPrivilege; activeWorksheet.Cells[row, 6] = item.WritePrivilege; activeWorksheet.Cells[row, 7] = item.DeletePrivilege; activeWorksheet.Cells[row, 8] = item.AppendPrivilege; activeWorksheet.Cells[row, 9] = item.AppendToPrivilege; activeWorksheet.Cells[row, 10] = item.AssignPrivilege; activeWorksheet.Cells[row, 11] = item.SharePrivilege; row++; } Console.WriteLine($"角色【{role.Value}】处理完毕 - {DateTime.Now.ToString()}"); } activeWorksheet.Columns[1].AutoFit();//自动列宽 activeWorksheet.Columns[2].AutoFit();//自动列宽 activeWorksheet.Columns[3].AutoFit();//自动列宽 activeWorksheet.Columns[4].AutoFit();//自动列宽 activeWorksheet.Columns[5].AutoFit();//自动列宽 activeWorksheet.Columns[6].AutoFit();//自动列宽 activeWorksheet.Columns[7].AutoFit();//自动列宽 activeWorksheet.Columns[8].AutoFit();//自动列宽 activeWorksheet.Columns[9].AutoFit();//自动列宽 activeWorksheet.Columns[10].AutoFit();//自动列宽 activeWorksheet.Columns[11].AutoFit();//自动列宽 rolePrivilegeWorkbook.SaveAs(Filename: ConfigurationManager.AppSettings["outPutFileName"], FileFormat: Excel.XlFileFormat.xlWorkbookDefault); rolePrivilegeWorkbook.Close(); excelApp.Quit(); } } catch (Exception ex) { Console.Write($"程序执行出现异常{ex.Message + ex.StackTrace}"); } finally { Console.Write("程序执行完毕,按任意键退出!"); Console.ReadKey(); } } /// <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[] includeRoles = ConfigurationManager.AppSettings["includeRoles"].Split(';'); 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 (includeRoles.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($"开始提取角色【{roleName}】- {roleId} 的权限", 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='acce***ight'/> </link-entity> </entity></fetch>", roleId); var ec = orgSvc.RetrieveMultiple(new FetchExpression(fetchXml)).Entities; 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 acce***ight = Convert.ToInt32(item.GetAttributeValue<AliasedValue>("prvs.acce***ight").Value); //可以根据需要排除对一些实体的权限导出来,做到更加简洁 if (lyp.EntityDisplayName != string.Empty)//为空的不是实体权限不需要处理 { //https://docs.microsoft.com/en-us/dotnet/api/microsoft.crm.sdk.messages.acce***ights?view=dynamics-general-ce-9 switch (acce***ight) { case 1: lyp.ReadPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 2: lyp.WritePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 4: lyp.AppendPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 16: lyp.AppendToPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 32: lyp.CreatePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 65536: lyp.DeletePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 262144: lyp.SharePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 524288: 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) { //https://docs.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327406(v=crm.8) 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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("prvDisable", ""); returnVal = returnVal.Replace("prvAssign", ""); 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() >= 1) { returnVal = entityMetadata.Where(item => item.Key == entitySchemaName.ToLower()).First().Value; } return returnVal; } private static int TransferPrivilege(int privilegedepthmask) { int returnVal = -1; switch (privilegedepthmask) { case 8: returnVal = 4; break; case 4: returnVal = 3; break; case 2: returnVal = 2; break; case 1: returnVal = 1; 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 == 1033).Count() >= 1 ? currentEntity.DisplayName.LocalizedLabels.Where(a => a.LanguageCode == 1033).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 >= 1) { returnVal = buEntities.Entities[0].GetAttributeValue<Guid>("businessunitid"); } return returnVal; } }}
下面是比较新版的代码,到处到一个sheet:
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 Microsoft.Xrm.Tooling.Connector;using System;using System.Collections.Generic;using System.Configuration;using System.Linq;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) { try { Console.WriteLine($"程序正在尝试连接到Dynamics 365/Power Apps环境..."); CrmServiceClient crmSvc = new CrmServiceClient(ConfigurationManager.AppSettings["connStr"]); if (!crmSvc.IsReady) { throw new Exception("连接CRM失败!" + crmSvc.LastCrmError); } WhoAmIRequest whoReq = new WhoAmIRequest(); WhoAmIResponse whoRep = crmSvc.Execute(whoReq) as WhoAmIResponse; var userEntity = crmSvc.Retrieve("systemuser", whoRep.UserId, new ColumnSet("fullname")); Console.WriteLine($"登录组织{crmSvc.ConnectedOrgFriendlyName}成功,欢迎{userEntity.GetAttributeValue<string>("fullname")},将会导出角色权限到Excel文件,继续操作请输入y!"); var input = Console.ReadLine().ToString().ToUpper(); if (input == "Y") { Console.WriteLine($"程序开始处理 - {DateTime.Now.ToString()}"); var meta = GetEntityMetadata(crmSvc); var excelApp = new Excel.Application(); excelApp.Visible = false; Excel.Workbook rolePrivilegeWorkbook = excelApp.Workbooks.Add(); var roleList = GetRoleList(crmSvc); Console.WriteLine($"共有{roleList.Count}个角色 - {DateTime.Now.ToString()}"); Excel.Worksheet activeWorksheet = rolePrivilegeWorkbook.ActiveSheet; activeWorksheet.Name = "SecurityRolePrivileges"; int row = 1; activeWorksheet.Cells[1, 1] = "Role Name"; activeWorksheet.Cells[1, 2] = "Entity Schema Name"; activeWorksheet.Cells[1, 3] = "Entity Display Name"; activeWorksheet.Cells[1, 4] = "Create"; activeWorksheet.Cells[1, 5] = "Read"; activeWorksheet.Cells[1, 6] = "Write"; activeWorksheet.Cells[1, 7] = "Delete"; activeWorksheet.Cells[1, 8] = "Append"; activeWorksheet.Cells[1, 9] = "Append To"; activeWorksheet.Cells[1, 10] = "Assign"; activeWorksheet.Cells[1, 11] = "Share"; activeWorksheet.Rows[1].Font.Bold = true;//字体加粗 row++; foreach (var role in roleList) { var ls = GetRolePrivileges(crmSvc, role.Key, role.Value, meta).OrderBy(t => t.EntityDisplayName); foreach (var item in ls) { activeWorksheet.Cells[row, 1] = role.Value; activeWorksheet.Cells[row, 2] = item.EntitySchemaName; activeWorksheet.Cells[row, 3] = item.EntityDisplayName; activeWorksheet.Cells[row, 4] = item.CreatePrivilege; activeWorksheet.Cells[row, 5] = item.ReadPrivilege; activeWorksheet.Cells[row, 6] = item.WritePrivilege; activeWorksheet.Cells[row, 7] = item.DeletePrivilege; activeWorksheet.Cells[row, 8] = item.AppendPrivilege; activeWorksheet.Cells[row, 9] = item.AppendToPrivilege; activeWorksheet.Cells[row, 10] = item.AssignPrivilege; activeWorksheet.Cells[row, 11] = item.SharePrivilege; row++; } Console.WriteLine($"角色【{role.Value}】处理完毕 - {DateTime.Now.ToString()}"); } activeWorksheet.Columns[1].AutoFit();//自动列宽 activeWorksheet.Columns[2].AutoFit();//自动列宽 activeWorksheet.Columns[3].AutoFit();//自动列宽 activeWorksheet.Columns[4].AutoFit();//自动列宽 activeWorksheet.Columns[5].AutoFit();//自动列宽 activeWorksheet.Columns[6].AutoFit();//自动列宽 activeWorksheet.Columns[7].AutoFit();//自动列宽 activeWorksheet.Columns[8].AutoFit();//自动列宽 activeWorksheet.Columns[9].AutoFit();//自动列宽 activeWorksheet.Columns[10].AutoFit();//自动列宽 activeWorksheet.Columns[11].AutoFit();//自动列宽 rolePrivilegeWorkbook.SaveAs(Filename: ConfigurationManager.AppSettings["outPutFileName"], FileFormat: Excel.XlFileFormat.xlWorkbookDefault); rolePrivilegeWorkbook.Close(); excelApp.Quit(); } } catch (Exception ex) { Console.Write($"程序执行出现异常{ex.Message + ex.StackTrace}"); } finally { Console.Write("程序执行完毕,按任意键退出!"); Console.ReadKey(); } } /// <summary> /// 获得角色列表 /// </summary> /// <param name="crmSC"></param> /// <returns></returns> private static Dictionary<Guid, string> GetRoleList(CrmServiceClient crmSC) { Dictionary<Guid, string> returnVal = new Dictionary<Guid, string>(); string[] includeRoles = ConfigurationManager.AppSettings["includeRoles"].Split(';'); var rootBuId = GetRootBUId(crmSC); string fetchXml = string.Format(@"<fetch version='1.0' no-lock='true' mapping='logical' distinct='false'> <entity name='role'> <attribute name='name' /> <attribute name='roleid' /> <order attribute='name' descending ='false' /> <filter type='and'> <condition attribute='businessunitid' operator='eq' value='{0}' /> </filter> </entity></fetch>", rootBuId); foreach (var item in crmSC.RetrieveMultiple(new FetchExpression(fetchXml)).Entities) { var roleName = item.GetAttributeValue<string>("name"); if (includeRoles.Contains(roleName)) { returnVal.Add(item.GetAttributeValue<Guid>("roleid"), roleName); } } return returnVal; } private static List<lyPrivilege> GetRolePrivileges(CrmServiceClient crmSC, Guid roleId, string roleName, Dictionary<string, string> entityMetadata) { Console.WriteLine($"开始提取角色【{roleName}】- {roleId} 的权限", 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='acce***ight'/> </link-entity> </entity></fetch>", roleId); var ec = crmSC.RetrieveMultiple(new FetchExpression(fetchXml)).Entities; foreach (var item in crmSC.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 acce***ight = Convert.ToInt32(item.GetAttributeValue<AliasedValue>("prvs.acce***ight").Value); //可以根据需要排除对一些实体的权限导出来,做到更加简洁 if (lyp.EntityDisplayName != string.Empty)//为空的不是实体权限不需要处理 { //https://docs.microsoft.com/en-us/dotnet/api/microsoft.crm.sdk.messages.acce***ights?view=dynamics-general-ce-9 switch (acce***ight) { case 1: lyp.ReadPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 2: lyp.WritePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 4: lyp.AppendPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 16: lyp.AppendToPrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 32: lyp.CreatePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 65536: lyp.DeletePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 262144: lyp.SharePrivilege = TransferPrivilege(item.GetAttributeValue<int>("privilegedepthmask")).ToString(); break; case 524288: 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) { //https://docs.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327406(v=crm.8) 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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() >= 1 ? 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("prvDisable", ""); returnVal = returnVal.Replace("prvAssign", ""); 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() >= 1) { returnVal = entityMetadata.Where(item => item.Key == entitySchemaName.ToLower()).First().Value; } return returnVal; } private static int TransferPrivilege(int privilegedepthmask) { int returnVal = -1; switch (privilegedepthmask) { case 8: returnVal = 4; break; case 4: returnVal = 3; break; case 2: returnVal = 2; break; case 1: returnVal = 1; break; } return returnVal; } /// <summary> /// 获取实体架构名称及其中文显示名称 /// </summary> /// <param name="crmSC"></param> /// <returns></returns> private static Dictionary<string, string> GetEntityMetadata(CrmServiceClient crmSC) { Dictionary<string, string> returnVal = new Dictionary<string, string>(); RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity, RetrieveAsIfPublished = true }; RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)crmSC.Execute(request); foreach (EntityMetadata currentEntity in response.EntityMetadata) { returnVal.Add(currentEntity.LogicalName, currentEntity.DisplayName.LocalizedLabels.Where(a => a.LanguageCode == 1033).Count() >= 1 ? currentEntity.DisplayName.LocalizedLabels.Where(a => a.LanguageCode == 1033).FirstOrDefault().Label : string.Empty); } return returnVal; } /// <summary> /// 获取根业务部门的GUID /// </summary> /// <param name="crmSC">组织服务</param> /// <returns></returns> private static Guid GetRootBUId(CrmServiceClient crmSC) { 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 = crmSC.RetrieveMultiple(new FetchExpression(fetchXml)); if (buEntities.Entities.Count >= 1) { returnVal = buEntities.Entities[0].GetAttributeValue<Guid>("businessunitid"); } return returnVal; } }}