8 May 2018

Assign Roles To User through code + AX 2012

static void AssignRoleToUser(Args _args)

{
    SecurityRole        role;
    SecurityUserRole    userRole;
    boolean             added;
    UserInfo            userInfo;
    Name                userRoleName;
    UserId              userId;
    container           userRoleContainer;
    int                 counter;

    userId       = 'AXAPTAEXPLORER';

    userRoleContainer = conIns(userRoleContainer, 1, "Budget clerk");
    userRoleContainer = conIns(userRoleContainer, 2, "Budget manager");
    userRoleContainer = conIns(userRoleContainer, 3, "Buying agent");

    for (counter = 1; counter <= conLen(userRoleContainer); counter++)
    {

        userRoleName = conPeek(userRoleContainer, counter);

        select role where role.Name == userRoleName;

        if (role.RecId)
        {
            while select userInfo
                where userInfo.id == userId
            {
                select * from userRole
                    where userRole.SecurityRole == role.RecId
                       && userRole.User == userInfo.id;

                if (!userRole || (userRole.AssignmentStatus != RoleAssignmentStatus::Enabled))
                {
                    userRole.User              = userInfo.id;
                    userRole.SecurityRole      = role.RecId;
                    userRole.AssignmentMode    = RoleAssignmentMode::Manual;
                    userRole.AssignmentStatus  = RoleAssignmentStatus::Enabled;
                    SecuritySegregationOfDuties::assignUserToRole(userRole, null);

                    info(strFmt('Role %1 added to the user %2 successfully.', role.Name, userInfo.id));
                }
                else
                {
                    warning(strFmt('skipping – Role %1 already assigned to the user %2.', role.Name, userInfo.id));
                }
            }
        }
    }
}

No comments:

Create number sequence in D365 FO

Create the data type. Add code in the loadModule method of the appropriate NumberSeqModule subclass. Add a method to the module’s paramet...