本人微信公衆號:微軟動態CRM專家羅勇 ,回覆282或者20181116可方便獲取本文,同時能夠在第一間獲得我發佈的最新博文信息,follow me!個人網站是 www.luoyong.me 。微信
先上圖讓你們看效果。權限列沒有值則表明沒有授予這個權限,1爲我的級別,2爲業務部門級別,3爲上:下級業務部門,4爲組織級別。架構
而後上代碼,代碼比較通俗易懂,有注意的地方我紅色標註了一下,本身能夠加上一些篩選,好比去掉導出對大部分標準實體的權限等,固然這個程序並無導出雜項權限,有興趣的能夠本身修改下。app
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 = 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.Rows[1].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, 1] = item.EntitySchemaName; activeWorksheet.Cells[row, 2] = item.EntityDisplayName; activeWorksheet.Cells[row, 3] = item.CreatePrivilege; activeWorksheet.Cells[row, 4] = item.ReadPrivilege; activeWorksheet.Cells[row, 5] = item.WritePrivilege; activeWorksheet.Cells[row, 6] = item.DeletePrivilege; activeWorksheet.Cells[row, 7] = item.AppendPrivilege; activeWorksheet.Cells[row, 8] = item.AppendToPrivilege; activeWorksheet.Cells[row, 9] = item.AssignPrivilege; activeWorksheet.Cells[row, 10] = item.SharePrivilege; row++; } 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();//自動列寬 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 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) { 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("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() >= 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 = 2; 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 == 2052).Count() >= 1 ? currentEntity.DisplayName.LocalizedLabels.Where(a => a.LanguageCode == 2052).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; } } }