private IEnumerable <RolePrivilege> GetUserPrivileges(Guid idUser) { var request = new RetrieveUserPrivilegesRequest() { UserId = idUser, }; var response = (RetrieveUserPrivilegesResponse)_service.Execute(request); return(response.RolePrivileges); }
/// <summary> /// Retrieve the set of <c>Privilege</c> for <c>System User</c>. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.retrieveuserprivilegesrequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="userId"></param> /// <returns> /// /// </returns> public List <RolePrivilege> GetPrivilegesByUserId(Guid userId) { ExceptionThrow.IfGuidEmpty(userId, "userId"); RetrieveUserPrivilegesRequest request = new RetrieveUserPrivilegesRequest() { UserId = userId }; RetrieveUserPrivilegesResponse serviceResponse = (RetrieveUserPrivilegesResponse)this.OrganizationService.Execute(request); return(serviceResponse.RolePrivileges.ToList()); }
public bool UserHasPrivilege(string priv, Guid userId) { var privilege = Connection.SourceService.GetFirstOrDefault("privilege", "name", priv); if (privilege == null) { return(false); } var request = new RetrieveUserPrivilegesRequest { UserId = userId }; var response = (RetrieveUserPrivilegesResponse)Connection.SourceService.Execute(request); return(response.RolePrivileges.Any(p => p.PrivilegeId == privilege.Id)); }
private static void GetUserPrivs() { if (_userPriviledgeNames == null) { // Get the Users' Privileges OrganizationServiceProxy.RegisterExecuteMessageResponseType("RetrieveUserPrivileges", typeof(RetrieveUserPrivilegesResponse)); RetrieveUserPrivilegesRequest request = new RetrieveUserPrivilegesRequest(); request.UserId = new Guid(Page.Context.GetUserId()); RetrieveUserPrivilegesResponse response = (RetrieveUserPrivilegesResponse)OrganizationServiceProxy.Execute(request); // Translate into names string priviledgeFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='privilege'> <attribute name='name'/> <filter type='and'> <condition attribute='privilegeid' operator='in'> {0} </condition> <condition attribute='name' operator='in'> {1} </condition> </filter> </entity> </fetch>"; string priviledgeIds = ""; // Load the names of the privs where the user has them in their roles foreach (RolePrivilege p in response.RolePrivileges) { priviledgeIds += @"<value>" + p.PrivilegeId.Value + "</value>"; } // Load only the names/ids where we need to compare in the sitemap string priviledgeNames = ""; foreach (string priv in _siteMap.privileges) { priviledgeNames += @"<value>" + priv + "</value>"; } EntityCollection userPrivNameResults = OrganizationServiceProxy.RetrieveMultiple(string.Format(priviledgeFetchXml, priviledgeIds, priviledgeNames)); _userPriviledgeNames = new Dictionary <string, string>(); foreach (Entity priv in userPrivNameResults.Entities) { _userPriviledgeNames[priv.GetAttributeValueString("name").ToLowerCase()] = "1"; } } }
public IList <UserPrivilege> GetUserPrivileges(string Username, string CorrelationId) { using (apiClient = new APIServiceClient(endpoint)) { RetrieveUserPrivilegesRequest request = new RetrieveUserPrivilegesRequest() { ApplicationId = Constants.APPLICATION_ID, Username = Username }; RetrieveUserPrivilegesResponse response = apiClient.RetrieveUserPrivileges(GetRequester(CorrelationId, Username), request); if (response.StatusCode == "SUCCESS") { return(response.UserPrivileges.ToList <UserPrivilege>()); } else { throw new Exception(response.Messages.First().Message); } } }
private static void GetUserPrivs() { if (_userPriviledgeNames == null) { // Get the Users' Privileges OrganizationServiceProxy.RegisterExecuteMessageResponseType("RetrieveUserPrivileges", typeof(RetrieveUserPrivilegesResponse)); RetrieveUserPrivilegesRequest request = new RetrieveUserPrivilegesRequest(); request.UserId = new Guid(Page.Context.GetUserId()); RetrieveUserPrivilegesResponse response = (RetrieveUserPrivilegesResponse)OrganizationServiceProxy.Execute(request); // Translate into names string priviledgeFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='privilege'> <attribute name='name'/> <filter type='and'> <condition attribute='privilegeid' operator='in'> {0} </condition> <condition attribute='name' operator='in'> {1} </condition> </filter> </entity> </fetch>"; string priviledgeIds = ""; // Load the names of the privs where the user has them in their roles foreach (RolePrivilege p in response.RolePrivileges) { priviledgeIds += @"<value>" + p.PrivilegeId.Value + "</value>"; } // Load only the names/ids where we need to compare in the sitemap string priviledgeNames = ""; foreach (string priv in _siteMap.privileges) { priviledgeNames += @"<value>" + priv + "</value>"; } EntityCollection userPrivNameResults = OrganizationServiceProxy.RetrieveMultiple(string.Format(priviledgeFetchXml, priviledgeIds, priviledgeNames)); _userPriviledgeNames = new Dictionary<string, string>(); foreach (Entity priv in userPrivNameResults.Entities) { _userPriviledgeNames[priv.GetAttributeValueString("name").ToLowerCase()] = "1"; } } }
/// <summary> /// This method first checks if the logged on user has prvReadPOAA permissions. /// Afterwards, the method creates the secure custom fields required for this sample, /// an account record for testing purposes, and POAA records for the user /// and those custom fields. /// Finally, the method retrieves the User Shared Attribute permissions for that user. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetRetrieveUserSharedAttributePermissions1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); //<snippetRetrieveUserSharedAttributePermissions2> #region Check if this user has prvReadPOAA // Get the GUID of the current user. WhoAmIRequest whoAmI = new WhoAmIRequest(); Guid userLoggedId = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId; Console.WriteLine("User logged: " + userLoggedId); // Check if this user has prvReadPOAA. RetrieveUserPrivilegesRequest userPrivilegesRequest = new RetrieveUserPrivilegesRequest(); userPrivilegesRequest.UserId = userLoggedId; RetrieveUserPrivilegesResponse userPrivilegesResponse = (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest); // Fixed the GUID for prvReadPOAA. Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}"); if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA))) { Console.WriteLine("This user DOES have prvReadPOAA"); } else { Console.WriteLine("This user DOESN'T have prvReadPOAA"); } Console.WriteLine(); #endregion Check if this user has prvReadPOAA //</snippetRetrieveUserSharedAttributePermissions2> #region Create an account record // Create an account record Account accountRecord = new Account(); accountRecord.Name = "Ane"; accountRecord["secret_phone"] = "123456"; _accountRecordId = _serviceProxy.Create(accountRecord); Console.WriteLine("Account record created."); #endregion Create an account record #region Create POAA entity for field #1 // Create POAA entity for field #1 PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretHomeId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; _serviceProxy.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Home created."); #endregion Create POAA entity for field #1 #region Create POAA entity for field #2 // Create POAA entity for field #2 poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretPhoneId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; _serviceProxy.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Phone created."); #endregion Create POAA entity for field #2 #region Retrieve User Shared Attribute Permissions // Create the query for retrieve User Shared Attribute permissions. QueryExpression queryPOAA = new QueryExpression("principalobjectattributeaccess"); queryPOAA.ColumnSet = new ColumnSet (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" }); queryPOAA.Criteria.FilterOperator = LogicalOperator.And; queryPOAA.Criteria.Conditions.Add (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId)); queryPOAA.Criteria.Conditions.Add (new ConditionExpression("principalid", ConditionOperator.EqualUserId)); Console.WriteLine(); Console.WriteLine("POAA for user: "******" principalid: " + ((EntityReference)entity["principalid"]).Id); Console.WriteLine(" attributeid: " + entity["attributeid"].ToString()); Console.WriteLine(" readaccess: " + entity["readaccess"].ToString()); Console.WriteLine(" updateaccess: " + entity["updateaccess"].ToString()); Console.WriteLine(); } } catch (Exception exc) { Console.WriteLine("Error: " + exc.Message); } #endregion Retrieve User Shared Attribute Permissions DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveUserSharedAttributePermissions1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code //////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate #region Check if this user has prvReadPOAA // Get the GUID of the current user. WhoAmIRequest whoAmI = new WhoAmIRequest(); Guid userLoggedId = ((WhoAmIResponse)service.Execute(whoAmI)).UserId; Console.WriteLine("User logged: " + userLoggedId); // Check if this user has prvReadPOAA. RetrieveUserPrivilegesRequest userPrivilegesRequest = new RetrieveUserPrivilegesRequest(); userPrivilegesRequest.UserId = userLoggedId; RetrieveUserPrivilegesResponse userPrivilegesResponse = (RetrieveUserPrivilegesResponse)service.Execute(userPrivilegesRequest); // Fixed the GUID for prvReadPOAA. Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}"); if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA))) { Console.WriteLine("This user DOES have prvReadPOAA"); } else { Console.WriteLine("This user DOESN'T have prvReadPOAA"); } Console.WriteLine(); #endregion Check if this user has prvReadPOAA #region Create an account record // Create an account record Account accountRecord = new Account(); accountRecord.Name = "Ane"; accountRecord["secret_phone"] = "123456"; _accountRecordId = service.Create(accountRecord); Console.WriteLine("Account record created."); #endregion Create an account record #region Create POAA entity for field #1 // Create POAA entity for field #1 PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretHomeId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; service.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Home created."); #endregion Create POAA entity for field #1 #region Create POAA entity for field #2 // Create POAA entity for field #2 poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretPhoneId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; service.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Phone created."); #endregion Create POAA entity for field #2 #region Retrieve User Shared Attribute Permissions // Create the query for retrieve User Shared Attribute permissions. QueryExpression queryPOAA = new QueryExpression("principalobjectattributeaccess"); queryPOAA.ColumnSet = new ColumnSet (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" }); queryPOAA.Criteria.FilterOperator = LogicalOperator.And; queryPOAA.Criteria.Conditions.Add (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId)); queryPOAA.Criteria.Conditions.Add (new ConditionExpression("principalid", ConditionOperator.EqualUserId)); EntityCollection responsePOAA = service.RetrieveMultiple(queryPOAA); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Check if this user has prvReadPOAA else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } #endregion Sample Code catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// This method first checks if the logged on user has prvReadPOAA permissions. /// Afterwards, the method creates the secure custom fields required for this sample, /// an account record for testing purposes, and POAA records for the user /// and those custom fields. /// Finally, the method retrieves the User Shared Attribute permissions for that user. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Check if this user has prvReadPOAA // Get the GUID of the current user. WhoAmIRequest whoAmI = new WhoAmIRequest(); Guid userLoggedId = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId; Console.WriteLine("User logged: " + userLoggedId); // Check if this user has prvReadPOAA. RetrieveUserPrivilegesRequest userPrivilegesRequest = new RetrieveUserPrivilegesRequest(); userPrivilegesRequest.UserId = userLoggedId; RetrieveUserPrivilegesResponse userPrivilegesResponse = (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest); // Fixed the GUID for prvReadPOAA. Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}"); if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA))) { Console.WriteLine("This user DOES have prvReadPOAA"); } else { Console.WriteLine("This user DOESN'T have prvReadPOAA"); } Console.WriteLine(); #endregion Check if this user has prvReadPOAA #region Create an account record // Create an account record Account accountRecord = new Account(); accountRecord.Name = "Ane"; accountRecord["secret_phone"] = "123456"; _accountRecordId = _serviceProxy.Create(accountRecord); Console.WriteLine("Account record created."); #endregion Create an account record #region Create POAA entity for field #1 // Create POAA entity for field #1 PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretHomeId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; _serviceProxy.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Home created."); #endregion Create POAA entity for field #1 #region Create POAA entity for field #2 // Create POAA entity for field #2 poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretPhoneId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; _serviceProxy.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Phone created."); #endregion Create POAA entity for field #2 #region Retrieve User Shared Attribute Permissions // Create the query for retrieve User Shared Attribute permissions. QueryExpression queryPOAA = new QueryExpression("principalobjectattributeaccess"); queryPOAA.ColumnSet = new ColumnSet (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" }); queryPOAA.Criteria.FilterOperator = LogicalOperator.And; queryPOAA.Criteria.Conditions.Add (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId)); queryPOAA.Criteria.Conditions.Add (new ConditionExpression("principalid", ConditionOperator.EqualUserId)); Console.WriteLine(); Console.WriteLine("POAA for user: "******" principalid: " + ((EntityReference)entity["principalid"]).Id); Console.WriteLine(" attributeid: " + entity["attributeid"].ToString()); Console.WriteLine(" readaccess: " + entity["readaccess"].ToString()); Console.WriteLine(" updateaccess: " + entity["updateaccess"].ToString()); Console.WriteLine(); } } catch (Exception exc) { Console.WriteLine("Error: " + exc.Message); } #endregion Retrieve User Shared Attribute Permissions DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }