CRM中如何利用位掩码对象设置主体的AccessRights?
Hey there, let's break down how to use that bitmask value you're getting from FetchEngine.GetPrincipalPriviliges() to set your principal's AccessMask.
First, let's recall that AccessRights is a flags enumeration in the CRM SDK. That means each permission (like ReadAccess, WriteAccess) corresponds to a specific bit in an integer, and the number you're seeing (e.g., 851991) is just the sum of all the enabled permission bits. The good news is that converting this integer back to the AccessRights type is straightforward.
Step 1: Convert the Object to an Integer
First, you'll need to cast or convert the returned object from GetPrincipalPriviliges() to an integer type (since CRM permission bitmasks fit neatly in an int):
// Get the raw bitmask value from your FetchEngine call object rawMask = FetchEngine.GetPrincipalPriviliges(Globals.incomingTeamId, Globals.incomingRecordId); // Convert to int (add a null/type check if you want to avoid runtime errors) int permissionMask = rawMask is int maskValue ? maskValue : Convert.ToInt32(rawMask);
Step 2: Cast the Integer to AccessRights
Since AccessRights is a flags enum, you can directly cast the integer to this type and assign it to AccessMask:
// Cast the integer to AccessRights and set the principal's permission mask principal.AccessMask = (Microsoft.Crm.Sdk.Messages.AccessRights)permissionMask;
Step 3: Verify the Permissions (Optional)
If you want to double-check that the conversion worked correctly, use Enum.HasFlag() to confirm specific permissions are included:
AccessRights convertedRights = (Microsoft.Crm.Sdk.Messages.AccessRights)permissionMask; // Check if ReadAccess is enabled bool hasReadAccess = convertedRights.HasFlag(Microsoft.Crm.Sdk.Messages.AccessRights.ReadAccess); // Check if WriteAccess is enabled bool hasWriteAccess = convertedRights.HasFlag(Microsoft.Crm.Sdk.Messages.AccessRights.WriteAccess);
Important Notes
- Always add a quick type check (like the ternary operator in Step 1) to handle cases where
GetPrincipalPriviliges()might return null or a non-integer value—this prevents unexpected runtime exceptions. - CRM's
AccessRightsuses 32-bit integers, sointis sufficient for most scenarios. If you ever encounter larger bitmask values, switch tolonginstead.
That's all there is to it! This works because flags enums are just human-readable wrappers around bitmask integers, so casting between the two is seamless.
内容的提问来源于stack exchange,提问作者Martin Felber

