Reassign Security Roles on change of Business Unit
Back when I worked for a CRM partner, and in my early days of CRM development, I would often get asked how long something would take to code – a “ballpark figure” – usually for a small requirement or change request. Invariably I would have a quick look and give an educated guess with a few caveats. Back then I perhaps was a bit out with some of my estimates but generally I was within an acceptable margin of error. However on occasions I am completely wide of of mark. And last week was such an occasion.
I needed to move around 30 users to different Business Units. As we know Security Roles are dropped when users move Business Unit. Unfortunately the average number of Security Roles for each of these users was probably around 6. The prospect of manually reassigning these didn’t exactly fill me with joy (somewhere on my mid/long term project list I’m sure I have a task to simply make users members of Teams and assign the roles to the team instead – a lot less cumbersome). Fortunately I came up with a temporary plan.
- Write a plugin on update of a user’s Business Unit
- Execute on Pre-Operation stage to generate a list of RoleIds that the user has before they change Business Unit
- Add the the list of RoleIds to the plugin Shared Variables
- Grab these RoleIds from Shared Variables in the post-operation stage and then reassign
Simple. Can get that done in an hour tops.
Problems with the above:
- Security Roles are dropped prior to pre-operation and the plugin would not execute pre-validation
- Security Roles have a different RoleId for each Business Unit so attempting to reassign a Security Role from a different BU resorts in an error
4 hours later here’s the solution that actually worked:
- Use an on-demand custom workflow activity to retrieve all of the user’s role names (Not RoleIds!). Write this list of role names as a comma separated list to store in a hidden text field on the user record
- Change the user’s Business Unit
- Use another on-demand workflow to iterate through each of the roles listed in the aforementioned hidden field. For each role query the role table filtered by role name and the new Business Unit Id to retrieve the new Role Id
- With the retrieved Role Id associate it to the user (code below)
service.Associate( "systemuser", userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference("systemuserroles", buRole) });
I’ve not got round to tidying the code up yet (stripping out my other gunk) but if anybody is interested in the completed solution drop a message in the comments and I’ll be sure to get round to posting it. Hopefully save somebody else some time at least.
This was originally posted here.
*This post is locked for comments