Ticket (Solved)

Assigning a Role on User Creation not working?

Hi Pro's, I am programmatically creating a user with an attached profile part which works as expected. But when adding a role to the user, the records appear to populate in the DB alright, but when viewing the user in admin - the role is not selected, nor are there any roles visibly available to select in the first place? [Note: If I add a user via normal admin GUI procedure, all the roles appear as per normal and work if selected]

My code to Create Account:

public ProfilePart CreateProfile(string username, string email, string password)
    {
        var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
        if (!registrationSettings.UsersCanRegister) {
            return null;
        }

        var profile = _orchardServices.ContentManager.New("Profile");
        var userPart = profile.As<UserPart>();
        var profilePart = profile.As<ProfilePart>();

        userPart.UserName = username;
        userPart.Email = email;
        userPart.NormalizedUserName = username.ToLowerInvariant();
        userPart.Record.HashAlgorithm = "SHA1";
        userPart.Record.RegistrationStatus = UserStatus.Approved; //Pending;
        userPart.Record.EmailStatus = UserStatus.Approved;

        profilePart.CreatedAt = _dateTimeService.Now;

        _membershipService.SetPassword(userPart, password);
        _orchardServices.ContentManager.Create(profile);

        return profilePart;
    }       

Create: -

var profile = _profileService.CreateProfile(Email, Email, FirstName);
profile.FirstName = FirstName;
 ////Add role
var role = _roleService.GetRoleByName(Site);
_roleRepository.Create(new UserRolesPartRecord { UserId = profile.User.Id, Role = role });

Can anyone see what I'm doing wrong? Many thanks :)

Re: Assigning a Role on User Creation not working?

Hey Guys, pretty sure I got this working now by using Orchards membership/createuser service and attaching profilepart thereafter. I was using an old tutorial, so not using IUser may not have wired things up correctly in the background re: roles. Thanks all the same ;)

Thursday, July 7, 2016 2:14:52 AM bypug
  • pug
  • Lv. 04 Rookie
  • Total EXP: 144

Post a reply

You need to be signed in to post a reply.

Sign In