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

Friends,

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));

        }

    }

}

 

Happy dax6ng,

Sreenath Reddy

Advertisements

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

  1. Luk Truyen Says:

    Hi,
    Very interesting note! Is it also possible to add a user to several (not all) users? I want to do this, but don’t know how to do it..;
    Regards,
    Luk


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: