Tuesday, 5 August 2014

Adding a role to all or multiple users using X++ Code [Dynamics AX 2012]


In AX 2012, we can add a role to all the users by running the automated role assignment job based on the rule which we define in the “Assign users to Role” form.
Navigation : System administration >> Setup >> Security >> Assign users to rolesassign users
And the code behind this is :
SysSecurityDynamicRoleAssignment::synchronize(args.record().RecId); // selected Role (this is Security Role table buffer) in the form
I tried to run the above code independently by passing the “Budget clerk” Security Role but did not work due to obvious reasons as it needed a rule assignment table buffer.
The equivalent code to assign a role to all users is below.
This doesn’t need to add any rules like what we do in the form.This is just an experiment to handle the roles through code and request to test the code before using it.
static void SR_AssignRoleToAllUsers(Args _args)
{
    SecurityRole        role;
    SecurityUserRole    userRole;
    boolean             added;
    UserInfo            userInfo;
    ;

    select role where role.Name == ‘Budget clerk’;
    while select userInfo
    {
        select * from userRole
            where userRole.SecurityRole == role.RecId &&
                userRole.User == userInfo.id;

        if (!userRole || (userRole.AssignmentStatus != RoleAssignmentStatus::Enabled))
        {
            info(strFmt(‘Role %1 added to the user %2 successfully.’, role.Name, userInfo.id));

            userRole.User = userInfo.id;
            userRole.SecurityRole = role.RecId;
            userRole.AssignmentMode = RoleAssignmentMode::Manual;
            userRole.AssignmentStatus = RoleAssignmentStatus::Enabled;
            SecuritySegregationOfDuties::assignUserToRole(userRole, null);
        }
        else
        {
            warning(strFmt(‘skipping – Role %1 to the user %2.’, role.Name, userInfo.id));
        }
    }
}

No comments:

Post a Comment