Roles for the new user (created in the code)

Murugesan Manokaran asked on November 9, 2017 17:56

created a new user in the code using UserInfoProvider APIs with proper roles which are existing in the site. User creation successfully completed. But in the user list for the newly created user detail page, Roles are not showing up.

any help?

Correct Answer

Brenden Kehren answered on November 9, 2017 18:57

Here is some standard code we use. Essentially the steps are:

  1. Create the user,
  2. Check the user was created successfully,
  3. Add the user to the site,
  4. Get the role you want to add them to,
  5. Check if the role you want to add them to exists,
  6. Add them to the role.

See code below:

UserInfo ui = new UserInfo();
ui.UserName = "user1";
ui.FullName = "user one";

UserInfoProvider.SetUserInfo(ui);

if (ui != null)
{
    UserInfoProvider.AddUserToSite(ui.UserName, SiteContext.CurrentSiteName);
    RoleInfo ri = RoleInfoProvider.GetRoleInfo("yourRoleCodeName", SiteContext.CurrentSiteID);
    if (ri != null)
    {
        UserInfoProvider.AddUserToRole(ui.UserID, ri.RoleID);
    }
}
3 votesVote for this answer Unmark Correct answer

Recent Answers


Matt Nield answered on November 9, 2017 18:34

If you could send a snippes of your code, that might help get an understanding of what is not working.

One thing I have noted before is that there is an order of events that you need to follow. You need to make sure that you save the user before you assign and save the roles.

0 votesVote for this answer Mark as a Correct answer

David Pearson answered on November 9, 2017 20:02 (last edited on November 9, 2017 20:03)

I found this for adding User Custom User Field ui.SetValue("someCustomFiled","someValueFromForm");

It save to the User Custom User Fields.....

0 votesVote for this answer Mark as a Correct answer

Murugesan Manokaran answered on November 9, 2017 20:14

Thanks, Brenden. Exactly same steps my code has. but I used this line to add the role to the user UserInfoProvider.AddUserToRole(newUser.UserName, role.RoleName, SiteContext.CurrentSiteName);

I will try with this one: UserInfoProvider.AddUserToRole(newUser.UserID, role.RoleID);

0 votesVote for this answer Mark as a Correct answer

Murugesan Manokaran answered on November 9, 2017 20:21

UserInfoProvider.AddUserToRole(newUser.UserID, role.RoleID) worked!

Not this one: UserInfoProvider.AddUserToRole(newUser.UserName, role.RoleName, SiteContext.CurrentSiteName)

Thank you, Brenden!!

1 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.